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/formats/agp.py | infer | def infer(args):
"""
%prog infer scaffolds.fasta genome.fasta
Infer where the components are in the genome. This function is rarely used,
but can be useful when distributor does not ship an AGP file.
"""
from jcvi.apps.grid import WriteJobs
from jcvi.formats.bed import sort
p = OptionParser(infer.__doc__)
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
scaffoldsf, genomef = args
inferbed = "infer-components.bed"
if need_update((scaffoldsf, genomef), inferbed):
scaffolds = Fasta(scaffoldsf, lazy=True)
genome = Fasta(genomef)
genome = genome.tostring()
args = [(scaffold_name, scaffold, genome) \
for scaffold_name, scaffold in scaffolds.iteritems_ordered()]
pool = WriteJobs(map_one_scaffold, args, inferbed, cpus=opts.cpus)
pool.run()
sort([inferbed, "-i"])
bed = Bed(inferbed)
inferagpbed = "infer.bed"
fw = open(inferagpbed, "w")
seen = []
for b in bed:
r = (b.seqid, b.start, b.end)
if check_seen(r, seen):
continue
print("\t".join(str(x) for x in \
(b.accn, 0, b.span, b.seqid, b.score, b.strand)), file=fw)
seen.append(r)
fw.close()
frombed([inferagpbed]) | python | def infer(args):
"""
%prog infer scaffolds.fasta genome.fasta
Infer where the components are in the genome. This function is rarely used,
but can be useful when distributor does not ship an AGP file.
"""
from jcvi.apps.grid import WriteJobs
from jcvi.formats.bed import sort
p = OptionParser(infer.__doc__)
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
scaffoldsf, genomef = args
inferbed = "infer-components.bed"
if need_update((scaffoldsf, genomef), inferbed):
scaffolds = Fasta(scaffoldsf, lazy=True)
genome = Fasta(genomef)
genome = genome.tostring()
args = [(scaffold_name, scaffold, genome) \
for scaffold_name, scaffold in scaffolds.iteritems_ordered()]
pool = WriteJobs(map_one_scaffold, args, inferbed, cpus=opts.cpus)
pool.run()
sort([inferbed, "-i"])
bed = Bed(inferbed)
inferagpbed = "infer.bed"
fw = open(inferagpbed, "w")
seen = []
for b in bed:
r = (b.seqid, b.start, b.end)
if check_seen(r, seen):
continue
print("\t".join(str(x) for x in \
(b.accn, 0, b.span, b.seqid, b.score, b.strand)), file=fw)
seen.append(r)
fw.close()
frombed([inferagpbed]) | [
"def",
"infer",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"apps",
".",
"grid",
"import",
"WriteJobs",
"from",
"jcvi",
".",
"formats",
".",
"bed",
"import",
"sort",
"p",
"=",
"OptionParser",
"(",
"infer",
".",
"__doc__",
")",
"p",
".",
"set_cpus",
"... | %prog infer scaffolds.fasta genome.fasta
Infer where the components are in the genome. This function is rarely used,
but can be useful when distributor does not ship an AGP file. | [
"%prog",
"infer",
"scaffolds",
".",
"fasta",
"genome",
".",
"fasta"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/agp.py#L887-L930 | train | 200,800 |
tanghaibao/jcvi | jcvi/formats/agp.py | format | def format(args):
"""
%prog format oldagpfile newagpfile
Reformat AGP file. --switch will replace the ids in the AGP file.
"""
from jcvi.formats.base import DictFile
p = OptionParser(format.__doc__)
p.add_option("--switchcomponent",
help="Switch component id based on")
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
oldagpfile, newagpfile = args
switchcomponent = opts.switchcomponent
if switchcomponent:
switchcomponent = DictFile(switchcomponent)
agp = AGP(oldagpfile)
fw = open(newagpfile, "w")
nconverts = 0
for i, a in enumerate(agp):
if not a.is_gap and a.component_id in switchcomponent:
oldid = a.component_id
newid = switchcomponent[a.component_id]
a.component_id = newid
logging.debug("Covert {0} to {1} on line {2}".\
format(oldid, newid, i+1))
nconverts += 1
print(a, file=fw)
logging.debug("Total converted records: {0}".format(nconverts)) | python | def format(args):
"""
%prog format oldagpfile newagpfile
Reformat AGP file. --switch will replace the ids in the AGP file.
"""
from jcvi.formats.base import DictFile
p = OptionParser(format.__doc__)
p.add_option("--switchcomponent",
help="Switch component id based on")
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
oldagpfile, newagpfile = args
switchcomponent = opts.switchcomponent
if switchcomponent:
switchcomponent = DictFile(switchcomponent)
agp = AGP(oldagpfile)
fw = open(newagpfile, "w")
nconverts = 0
for i, a in enumerate(agp):
if not a.is_gap and a.component_id in switchcomponent:
oldid = a.component_id
newid = switchcomponent[a.component_id]
a.component_id = newid
logging.debug("Covert {0} to {1} on line {2}".\
format(oldid, newid, i+1))
nconverts += 1
print(a, file=fw)
logging.debug("Total converted records: {0}".format(nconverts)) | [
"def",
"format",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"base",
"import",
"DictFile",
"p",
"=",
"OptionParser",
"(",
"format",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--switchcomponent\"",
",",
"help",
"=",
"\"Switch compo... | %prog format oldagpfile newagpfile
Reformat AGP file. --switch will replace the ids in the AGP file. | [
"%prog",
"format",
"oldagpfile",
"newagpfile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/agp.py#L933-L967 | train | 200,801 |
tanghaibao/jcvi | jcvi/formats/agp.py | frombed | def frombed(args):
"""
%prog frombed bedfile
Generate AGP file based on bed file. The bed file must have at least 6
columns. With the 4-th column indicating the new object.
"""
p = OptionParser(frombed.__doc__)
p.add_option("--gapsize", default=100, type="int",
help="Insert gaps of size [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
bedfile, = args
gapsize = opts.gapsize
agpfile = bedfile.replace(".bed", ".agp")
fw = open(agpfile, "w")
bed = Bed(bedfile, sorted=False)
for object, beds in groupby(bed, key=lambda x: x.accn):
beds = list(beds)
for i, b in enumerate(beds):
if gapsize and i != 0:
print("\t".join(str(x) for x in \
(object, 0, 0, 0, "U", \
gapsize, "scaffold", "yes", "map")), file=fw)
print("\t".join(str(x) for x in \
(object, 0, 0, 0, "W", \
b.seqid, b.start, b.end, b.strand)), file=fw)
fw.close()
# Reindex
return reindex([agpfile, "--inplace"]) | python | def frombed(args):
"""
%prog frombed bedfile
Generate AGP file based on bed file. The bed file must have at least 6
columns. With the 4-th column indicating the new object.
"""
p = OptionParser(frombed.__doc__)
p.add_option("--gapsize", default=100, type="int",
help="Insert gaps of size [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
bedfile, = args
gapsize = opts.gapsize
agpfile = bedfile.replace(".bed", ".agp")
fw = open(agpfile, "w")
bed = Bed(bedfile, sorted=False)
for object, beds in groupby(bed, key=lambda x: x.accn):
beds = list(beds)
for i, b in enumerate(beds):
if gapsize and i != 0:
print("\t".join(str(x) for x in \
(object, 0, 0, 0, "U", \
gapsize, "scaffold", "yes", "map")), file=fw)
print("\t".join(str(x) for x in \
(object, 0, 0, 0, "W", \
b.seqid, b.start, b.end, b.strand)), file=fw)
fw.close()
# Reindex
return reindex([agpfile, "--inplace"]) | [
"def",
"frombed",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"frombed",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--gapsize\"",
",",
"default",
"=",
"100",
",",
"type",
"=",
"\"int\"",
",",
"help",
"=",
"\"Insert gaps of size [default... | %prog frombed bedfile
Generate AGP file based on bed file. The bed file must have at least 6
columns. With the 4-th column indicating the new object. | [
"%prog",
"frombed",
"bedfile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/agp.py#L970-L1006 | train | 200,802 |
tanghaibao/jcvi | jcvi/formats/agp.py | swap | def swap(args):
"""
%prog swap agpfile
Swap objects and components. Will add gap lines. This is often used in
conjuction with formats.chain.fromagp() to convert between different
coordinate systems.
"""
from jcvi.utils.range import range_interleave
p = OptionParser(swap.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
agpfile, = args
agp = AGP(agpfile, nogaps=True, validate=False)
agp.sort(key=lambda x: (x.component_id, x.component_beg))
newagpfile = agpfile.rsplit(".", 1)[0] + ".swapped.agp"
fw = open(newagpfile, "w")
agp.transfer_header(fw)
for cid, aa in groupby(agp, key=(lambda x: x.component_id)):
aa = list(aa)
aranges = [(x.component_id, x.component_beg, x.component_end) \
for x in aa]
gaps = range_interleave(aranges)
for a, g in zip_longest(aa, gaps):
a.object, a.component_id = a.component_id, a.object
a.component_beg = a.object_beg
a.component_end = a.object_end
print(a, file=fw)
if not g:
continue
aline = [cid, 0, 0, 0]
gseq, ga, gb = g
cspan = gb - ga + 1
aline += ["N", cspan, "fragment", "yes"]
print("\t".join(str(x) for x in aline), file=fw)
fw.close()
# Reindex
idxagpfile = reindex([newagpfile, "--inplace"])
return newagpfile | python | def swap(args):
"""
%prog swap agpfile
Swap objects and components. Will add gap lines. This is often used in
conjuction with formats.chain.fromagp() to convert between different
coordinate systems.
"""
from jcvi.utils.range import range_interleave
p = OptionParser(swap.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
agpfile, = args
agp = AGP(agpfile, nogaps=True, validate=False)
agp.sort(key=lambda x: (x.component_id, x.component_beg))
newagpfile = agpfile.rsplit(".", 1)[0] + ".swapped.agp"
fw = open(newagpfile, "w")
agp.transfer_header(fw)
for cid, aa in groupby(agp, key=(lambda x: x.component_id)):
aa = list(aa)
aranges = [(x.component_id, x.component_beg, x.component_end) \
for x in aa]
gaps = range_interleave(aranges)
for a, g in zip_longest(aa, gaps):
a.object, a.component_id = a.component_id, a.object
a.component_beg = a.object_beg
a.component_end = a.object_end
print(a, file=fw)
if not g:
continue
aline = [cid, 0, 0, 0]
gseq, ga, gb = g
cspan = gb - ga + 1
aline += ["N", cspan, "fragment", "yes"]
print("\t".join(str(x) for x in aline), file=fw)
fw.close()
# Reindex
idxagpfile = reindex([newagpfile, "--inplace"])
return newagpfile | [
"def",
"swap",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"utils",
".",
"range",
"import",
"range_interleave",
"p",
"=",
"OptionParser",
"(",
"swap",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len... | %prog swap agpfile
Swap objects and components. Will add gap lines. This is often used in
conjuction with formats.chain.fromagp() to convert between different
coordinate systems. | [
"%prog",
"swap",
"agpfile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/agp.py#L1009-L1056 | train | 200,803 |
tanghaibao/jcvi | jcvi/formats/agp.py | stats | def stats(args):
"""
%prog stats agpfile
Print out a report for length of gaps and components.
"""
from jcvi.utils.table import tabulate
p = OptionParser(stats.__doc__)
p.add_option("--warn", default=False, action="store_true",
help="Warnings on small component spans [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(p.print_help())
agpfile, = args
agp = AGP(agpfile)
gap_lengths = []
component_lengths = []
for a in agp:
span = a.object_span
if a.is_gap:
label = a.gap_type
gap_lengths.append((span, label))
else:
label = "{0}:{1}-{2}".format(a.component_id, a.component_beg, \
a.component_end)
component_lengths.append((span, label))
if opts.warn and span < 50:
logging.error("component span too small ({0}):\n{1}".\
format(span, a))
table = dict()
for label, lengths in zip(("Gaps", "Components"),
(gap_lengths, component_lengths)):
if not lengths:
table[(label, "Min")] = table[(label, "Max")] \
= table[(label, "Sum")] = "n.a."
continue
table[(label, "Min")] = "{0} ({1})".format(*min(lengths))
table[(label, "Max")] = "{0} ({1})".format(*max(lengths))
table[(label, "Sum")] = sum(x[0] for x in lengths)
print(tabulate(table), file=sys.stderr) | python | def stats(args):
"""
%prog stats agpfile
Print out a report for length of gaps and components.
"""
from jcvi.utils.table import tabulate
p = OptionParser(stats.__doc__)
p.add_option("--warn", default=False, action="store_true",
help="Warnings on small component spans [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(p.print_help())
agpfile, = args
agp = AGP(agpfile)
gap_lengths = []
component_lengths = []
for a in agp:
span = a.object_span
if a.is_gap:
label = a.gap_type
gap_lengths.append((span, label))
else:
label = "{0}:{1}-{2}".format(a.component_id, a.component_beg, \
a.component_end)
component_lengths.append((span, label))
if opts.warn and span < 50:
logging.error("component span too small ({0}):\n{1}".\
format(span, a))
table = dict()
for label, lengths in zip(("Gaps", "Components"),
(gap_lengths, component_lengths)):
if not lengths:
table[(label, "Min")] = table[(label, "Max")] \
= table[(label, "Sum")] = "n.a."
continue
table[(label, "Min")] = "{0} ({1})".format(*min(lengths))
table[(label, "Max")] = "{0} ({1})".format(*max(lengths))
table[(label, "Sum")] = sum(x[0] for x in lengths)
print(tabulate(table), file=sys.stderr) | [
"def",
"stats",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"utils",
".",
"table",
"import",
"tabulate",
"p",
"=",
"OptionParser",
"(",
"stats",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--warn\"",
",",
"default",
"=",
"False",
",",
"action"... | %prog stats agpfile
Print out a report for length of gaps and components. | [
"%prog",
"stats",
"agpfile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/agp.py#L1059-L1106 | train | 200,804 |
tanghaibao/jcvi | jcvi/formats/agp.py | cut | def cut(args):
"""
%prog cut agpfile bedfile
Cut at the boundaries of the ranges in the bedfile.
"""
p = OptionParser(cut.__doc__)
p.add_option("--sep", default=".", help="Separator for splits")
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
agpfile, bedfile = args
sep = opts.sep
agp = AGP(agpfile)
bed = Bed(bedfile)
simple_agp = agp.order
newagpfile = agpfile.replace(".agp", ".cut.agp")
fw = open(newagpfile, "w")
agp_fixes = defaultdict(list)
for component, intervals in bed.sub_beds():
i, a = simple_agp[component]
object = a.object
component_span = a.component_span
orientation = a.orientation
assert a.component_beg, a.component_end
cuts = set()
for i in intervals:
start, end = i.start, i.end
end -= 1
assert start <= end
cuts.add(start)
cuts.add(end)
cuts.add(0)
cuts.add(component_span)
cuts = list(sorted(cuts))
sum_of_spans = 0
for i, (a, b) in enumerate(pairwise(cuts)):
oid = object + "{0}{1}".format(sep, i + 1)
aline = [oid, 0, 0, 0]
cspan = b - a
aline += ['D', component, a + 1, b, orientation]
sum_of_spans += cspan
aline = "\t".join(str(x) for x in aline)
agp_fixes[component].append(aline)
assert component_span == sum_of_spans
# Finally write the masked agp
for a in agp:
if not a.is_gap and a.component_id in agp_fixes:
print("\n".join(agp_fixes[a.component_id]), file=fw)
else:
print(a, file=fw)
fw.close()
# Reindex
reindex([newagpfile, "--inplace"])
return newagpfile | python | def cut(args):
"""
%prog cut agpfile bedfile
Cut at the boundaries of the ranges in the bedfile.
"""
p = OptionParser(cut.__doc__)
p.add_option("--sep", default=".", help="Separator for splits")
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
agpfile, bedfile = args
sep = opts.sep
agp = AGP(agpfile)
bed = Bed(bedfile)
simple_agp = agp.order
newagpfile = agpfile.replace(".agp", ".cut.agp")
fw = open(newagpfile, "w")
agp_fixes = defaultdict(list)
for component, intervals in bed.sub_beds():
i, a = simple_agp[component]
object = a.object
component_span = a.component_span
orientation = a.orientation
assert a.component_beg, a.component_end
cuts = set()
for i in intervals:
start, end = i.start, i.end
end -= 1
assert start <= end
cuts.add(start)
cuts.add(end)
cuts.add(0)
cuts.add(component_span)
cuts = list(sorted(cuts))
sum_of_spans = 0
for i, (a, b) in enumerate(pairwise(cuts)):
oid = object + "{0}{1}".format(sep, i + 1)
aline = [oid, 0, 0, 0]
cspan = b - a
aline += ['D', component, a + 1, b, orientation]
sum_of_spans += cspan
aline = "\t".join(str(x) for x in aline)
agp_fixes[component].append(aline)
assert component_span == sum_of_spans
# Finally write the masked agp
for a in agp:
if not a.is_gap and a.component_id in agp_fixes:
print("\n".join(agp_fixes[a.component_id]), file=fw)
else:
print(a, file=fw)
fw.close()
# Reindex
reindex([newagpfile, "--inplace"])
return newagpfile | [
"def",
"cut",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"cut",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--sep\"",
",",
"default",
"=",
"\".\"",
",",
"help",
"=",
"\"Separator for splits\"",
")",
"opts",
",",
"args",
"=",
"p",
... | %prog cut agpfile bedfile
Cut at the boundaries of the ranges in the bedfile. | [
"%prog",
"cut",
"agpfile",
"bedfile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/agp.py#L1109-L1176 | train | 200,805 |
tanghaibao/jcvi | jcvi/formats/agp.py | summary | def summary(args):
"""
%prog summary agpfile
print a table of scaffold statistics, number of BACs, no of scaffolds,
scaffold N50, scaffold L50, actual sequence, PSMOL NNNs, PSMOL-length, % of
PSMOL sequenced.
"""
from jcvi.utils.table import write_csv
p = OptionParser(summary.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(p.print_help())
agpfile, = args
header = "Chromosome #_Distinct #_Components #_Scaffolds " \
"Scaff_N50 Scaff_L50 Length".split()
agp = AGP(agpfile)
data = list(agp.summary_all())
write_csv(header, data, sep=" ") | python | def summary(args):
"""
%prog summary agpfile
print a table of scaffold statistics, number of BACs, no of scaffolds,
scaffold N50, scaffold L50, actual sequence, PSMOL NNNs, PSMOL-length, % of
PSMOL sequenced.
"""
from jcvi.utils.table import write_csv
p = OptionParser(summary.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(p.print_help())
agpfile, = args
header = "Chromosome #_Distinct #_Components #_Scaffolds " \
"Scaff_N50 Scaff_L50 Length".split()
agp = AGP(agpfile)
data = list(agp.summary_all())
write_csv(header, data, sep=" ") | [
"def",
"summary",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"utils",
".",
"table",
"import",
"write_csv",
"p",
"=",
"OptionParser",
"(",
"summary",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len"... | %prog summary agpfile
print a table of scaffold statistics, number of BACs, no of scaffolds,
scaffold N50, scaffold L50, actual sequence, PSMOL NNNs, PSMOL-length, % of
PSMOL sequenced. | [
"%prog",
"summary",
"agpfile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/agp.py#L1363-L1385 | train | 200,806 |
tanghaibao/jcvi | jcvi/formats/agp.py | phase | def phase(args):
"""
%prog phase genbankfiles
Input has to be gb file. Search the `KEYWORDS` section to look for PHASE.
Also look for "chromosome" and "clone" in the definition line.
"""
p = OptionParser(phase.__doc__)
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) < 1:
sys.exit(not p.print_help())
fw = must_open(opts.outfile, "w")
for gbfile in args:
for rec in SeqIO.parse(gbfile, "gb"):
bac_phase, keywords = get_phase(rec)
chr, clone = get_clone(rec)
keyword_field = ";".join(keywords)
print("\t".join((rec.id, str(bac_phase), keyword_field,
chr, clone)), file=fw) | python | def phase(args):
"""
%prog phase genbankfiles
Input has to be gb file. Search the `KEYWORDS` section to look for PHASE.
Also look for "chromosome" and "clone" in the definition line.
"""
p = OptionParser(phase.__doc__)
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) < 1:
sys.exit(not p.print_help())
fw = must_open(opts.outfile, "w")
for gbfile in args:
for rec in SeqIO.parse(gbfile, "gb"):
bac_phase, keywords = get_phase(rec)
chr, clone = get_clone(rec)
keyword_field = ";".join(keywords)
print("\t".join((rec.id, str(bac_phase), keyword_field,
chr, clone)), file=fw) | [
"def",
"phase",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"phase",
".",
"__doc__",
")",
"p",
".",
"set_outfile",
"(",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"<",
"1",
... | %prog phase genbankfiles
Input has to be gb file. Search the `KEYWORDS` section to look for PHASE.
Also look for "chromosome" and "clone" in the definition line. | [
"%prog",
"phase",
"genbankfiles"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/agp.py#L1432-L1454 | train | 200,807 |
tanghaibao/jcvi | jcvi/formats/agp.py | tpf | def tpf(args):
"""
%prog tpf agpfile
Print out a list of ids, one per line. Also known as the Tiling Path.
AC225490.9 chr6
Can optionally output scaffold gaps.
"""
p = OptionParser(tpf.__doc__)
p.add_option("--noversion", default=False, action="store_true",
help="Remove trailing accession versions [default: %default]")
p.add_option("--gaps", default=False, action="store_true",
help="Include gaps in the output [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
agpfile, = args
agp = AGP(agpfile)
for a in agp:
object = a.object
if a.is_gap:
if opts.gaps and a.isCloneGap:
print("\t".join((a.gap_type, object, "na")))
continue
component_id = a.component_id
orientation = a.orientation
if opts.noversion:
component_id = component_id.rsplit(".", 1)[0]
print("\t".join((component_id, object, orientation))) | python | def tpf(args):
"""
%prog tpf agpfile
Print out a list of ids, one per line. Also known as the Tiling Path.
AC225490.9 chr6
Can optionally output scaffold gaps.
"""
p = OptionParser(tpf.__doc__)
p.add_option("--noversion", default=False, action="store_true",
help="Remove trailing accession versions [default: %default]")
p.add_option("--gaps", default=False, action="store_true",
help="Include gaps in the output [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
agpfile, = args
agp = AGP(agpfile)
for a in agp:
object = a.object
if a.is_gap:
if opts.gaps and a.isCloneGap:
print("\t".join((a.gap_type, object, "na")))
continue
component_id = a.component_id
orientation = a.orientation
if opts.noversion:
component_id = component_id.rsplit(".", 1)[0]
print("\t".join((component_id, object, orientation))) | [
"def",
"tpf",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"tpf",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--noversion\"",
",",
"default",
"=",
"False",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Remove trailing accessi... | %prog tpf agpfile
Print out a list of ids, one per line. Also known as the Tiling Path.
AC225490.9 chr6
Can optionally output scaffold gaps. | [
"%prog",
"tpf",
"agpfile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/agp.py#L1457-L1492 | train | 200,808 |
tanghaibao/jcvi | jcvi/formats/agp.py | bed | def bed(args):
"""
%prog bed agpfile
print out the tiling paths in bed/gff3 format
"""
from jcvi.formats.obo import validate_term
p = OptionParser(bed.__doc__)
p.add_option("--gaps", default=False, action="store_true",
help="Only print bed lines for gaps [default: %default]")
p.add_option("--nogaps", default=False, action="store_true",
help="Do not print bed lines for gaps [default: %default]")
p.add_option("--bed12", default=False, action="store_true",
help="Produce bed12 formatted output [default: %default]")
p.add_option("--component", default=False, action="store_true",
help="Generate bed file for components [default: %default]")
p.set_outfile()
g1 = OptionGroup(p, "GFF specific parameters",
"Note: If not specified, output will be in `bed` format")
g1.add_option("--gff", default=False, action="store_true",
help="Produce gff3 formatted output. By default, ignores " +\
"AGP gap lines. [default: %default]")
g1.add_option("--source", default="MGSC",
help="Specify a gff3 source [default: `%default`]")
g1.add_option("--feature", default="golden_path_fragment",
help="Specify a gff3 feature type [default: `%default`]")
p.add_option_group(g1)
p.set_SO_opts()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
if opts.component:
opts.nogaps = True
# If output format is gff3 and 'verifySO' option is invoked, validate the SO term
if opts.gff and opts.verifySO:
validate_term(opts.feature, method=opts.verifySO)
agpfile, = args
agp = AGP(agpfile)
fw = must_open(opts.outfile, "w")
if opts.gff:
print("##gff-version 3", file=fw)
for a in agp:
if opts.nogaps and a.is_gap:
continue
if opts.gaps and not a.is_gap:
continue
if opts.bed12:
print(a.bed12line, file=fw)
elif opts.gff:
print(a.gffline(gff_source=opts.source, gff_feat_type=opts.feature), file=fw)
elif opts.component:
name = "{0}:{1}-{2}".\
format(a.component_id, a.component_beg, a.component_end)
print("\t".join(str(x) for x in (a.component_id, a.component_beg - 1,
a.component_end, name,
a.component_type, a.orientation)), file=fw)
else:
print(a.bedline, file=fw)
fw.close()
return fw.name | python | def bed(args):
"""
%prog bed agpfile
print out the tiling paths in bed/gff3 format
"""
from jcvi.formats.obo import validate_term
p = OptionParser(bed.__doc__)
p.add_option("--gaps", default=False, action="store_true",
help="Only print bed lines for gaps [default: %default]")
p.add_option("--nogaps", default=False, action="store_true",
help="Do not print bed lines for gaps [default: %default]")
p.add_option("--bed12", default=False, action="store_true",
help="Produce bed12 formatted output [default: %default]")
p.add_option("--component", default=False, action="store_true",
help="Generate bed file for components [default: %default]")
p.set_outfile()
g1 = OptionGroup(p, "GFF specific parameters",
"Note: If not specified, output will be in `bed` format")
g1.add_option("--gff", default=False, action="store_true",
help="Produce gff3 formatted output. By default, ignores " +\
"AGP gap lines. [default: %default]")
g1.add_option("--source", default="MGSC",
help="Specify a gff3 source [default: `%default`]")
g1.add_option("--feature", default="golden_path_fragment",
help="Specify a gff3 feature type [default: `%default`]")
p.add_option_group(g1)
p.set_SO_opts()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
if opts.component:
opts.nogaps = True
# If output format is gff3 and 'verifySO' option is invoked, validate the SO term
if opts.gff and opts.verifySO:
validate_term(opts.feature, method=opts.verifySO)
agpfile, = args
agp = AGP(agpfile)
fw = must_open(opts.outfile, "w")
if opts.gff:
print("##gff-version 3", file=fw)
for a in agp:
if opts.nogaps and a.is_gap:
continue
if opts.gaps and not a.is_gap:
continue
if opts.bed12:
print(a.bed12line, file=fw)
elif opts.gff:
print(a.gffline(gff_source=opts.source, gff_feat_type=opts.feature), file=fw)
elif opts.component:
name = "{0}:{1}-{2}".\
format(a.component_id, a.component_beg, a.component_end)
print("\t".join(str(x) for x in (a.component_id, a.component_beg - 1,
a.component_end, name,
a.component_type, a.orientation)), file=fw)
else:
print(a.bedline, file=fw)
fw.close()
return fw.name | [
"def",
"bed",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"obo",
"import",
"validate_term",
"p",
"=",
"OptionParser",
"(",
"bed",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--gaps\"",
",",
"default",
"=",
"False",
",",
"action... | %prog bed agpfile
print out the tiling paths in bed/gff3 format | [
"%prog",
"bed",
"agpfile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/agp.py#L1496-L1563 | train | 200,809 |
tanghaibao/jcvi | jcvi/formats/agp.py | extendbed | def extendbed(args):
"""
%prog extend agpfile componentfasta
Extend the components to fill the component range. For example, a bed/gff3 file
that was converted from the agp will contain only the BAC sequence intervals
that are 'represented' - sometimes leaving the 5` and 3` out (those that
overlap with adjacent sequences. This script fill up those ranges,
potentially to make graphics for tiling path.
"""
from jcvi.formats.sizes import Sizes
p = OptionParser(extendbed.__doc__)
p.add_option("--nogaps", default=False, action="store_true",
help="Do not print bed lines for gaps [default: %default]")
p.add_option("--bed12", default=False, action="store_true",
help="Produce bed12 formatted output [default: %default]")
p.add_option("--gff", default=False, action="store_true",
help="Produce gff3 formatted output. By default, ignores " +\
" AGP gap lines. [default: %default]")
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
# If output format is GFF3, ignore AGP gap lines.
if opts.gff:
opts.nogaps = True
agpfile, fastafile = args
agp = AGP(agpfile)
fw = must_open(opts.outfile, "w")
if opts.gff:
print("##gff-version 3", file=fw)
ranges = defaultdict(list)
thickCoords = [] # These are the coordinates before modify ranges
# Make the first pass to record all the component ranges
for a in agp:
thickCoords.append((a.object_beg, a.object_end))
if a.is_gap:
continue
ranges[a.component_id].append(a)
# Modify the ranges
sizes = Sizes(fastafile).mapping
for accn, rr in ranges.items():
alen = sizes[accn]
a = rr[0]
if a.orientation == "+":
hang = a.component_beg - 1
else:
hang = alen - a.component_end
a.object_beg -= hang
a = rr[-1]
if a.orientation == "+":
hang = alen - a.component_end
else:
hang = a.component_beg - 1
a.object_end += hang
for a, (ts, te) in zip(agp, thickCoords):
if opts.nogaps and a.is_gap:
continue
if opts.bed12:
line = a.bedline
a.object_beg, a.object_end = ts, te
line += "\t" + a.bedextra
print(line, file=fw)
elif opts.gff:
print(a.gffline(), file=fw)
else:
print(a.bedline, file=fw) | python | def extendbed(args):
"""
%prog extend agpfile componentfasta
Extend the components to fill the component range. For example, a bed/gff3 file
that was converted from the agp will contain only the BAC sequence intervals
that are 'represented' - sometimes leaving the 5` and 3` out (those that
overlap with adjacent sequences. This script fill up those ranges,
potentially to make graphics for tiling path.
"""
from jcvi.formats.sizes import Sizes
p = OptionParser(extendbed.__doc__)
p.add_option("--nogaps", default=False, action="store_true",
help="Do not print bed lines for gaps [default: %default]")
p.add_option("--bed12", default=False, action="store_true",
help="Produce bed12 formatted output [default: %default]")
p.add_option("--gff", default=False, action="store_true",
help="Produce gff3 formatted output. By default, ignores " +\
" AGP gap lines. [default: %default]")
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
# If output format is GFF3, ignore AGP gap lines.
if opts.gff:
opts.nogaps = True
agpfile, fastafile = args
agp = AGP(agpfile)
fw = must_open(opts.outfile, "w")
if opts.gff:
print("##gff-version 3", file=fw)
ranges = defaultdict(list)
thickCoords = [] # These are the coordinates before modify ranges
# Make the first pass to record all the component ranges
for a in agp:
thickCoords.append((a.object_beg, a.object_end))
if a.is_gap:
continue
ranges[a.component_id].append(a)
# Modify the ranges
sizes = Sizes(fastafile).mapping
for accn, rr in ranges.items():
alen = sizes[accn]
a = rr[0]
if a.orientation == "+":
hang = a.component_beg - 1
else:
hang = alen - a.component_end
a.object_beg -= hang
a = rr[-1]
if a.orientation == "+":
hang = alen - a.component_end
else:
hang = a.component_beg - 1
a.object_end += hang
for a, (ts, te) in zip(agp, thickCoords):
if opts.nogaps and a.is_gap:
continue
if opts.bed12:
line = a.bedline
a.object_beg, a.object_end = ts, te
line += "\t" + a.bedextra
print(line, file=fw)
elif opts.gff:
print(a.gffline(), file=fw)
else:
print(a.bedline, file=fw) | [
"def",
"extendbed",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"sizes",
"import",
"Sizes",
"p",
"=",
"OptionParser",
"(",
"extendbed",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--nogaps\"",
",",
"default",
"=",
"False",
",",
... | %prog extend agpfile componentfasta
Extend the components to fill the component range. For example, a bed/gff3 file
that was converted from the agp will contain only the BAC sequence intervals
that are 'represented' - sometimes leaving the 5` and 3` out (those that
overlap with adjacent sequences. This script fill up those ranges,
potentially to make graphics for tiling path. | [
"%prog",
"extend",
"agpfile",
"componentfasta"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/agp.py#L1566-L1642 | train | 200,810 |
tanghaibao/jcvi | jcvi/formats/agp.py | gaps | def gaps(args):
"""
%prog gaps agpfile
Print out the distribution of gapsizes. Option --merge allows merging of
adjacent gaps which is used by tidy().
"""
from jcvi.graphics.histogram import loghistogram
p = OptionParser(gaps.__doc__)
p.add_option("--merge", dest="merge", default=False, action="store_true",
help="Merge adjacent gaps (to conform to AGP specification)")
p.add_option("--header", default=False, action="store_true",
help="Produce an AGP header [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
merge = opts.merge
agpfile, = args
if merge:
merged_agpfile = agpfile.replace(".agp", ".merged.agp")
fw = open(merged_agpfile, "w")
agp = AGP(agpfile)
sizes = []
data = [] # store merged AGPLine's
priorities = ("centromere", "telomere", "scaffold", "contig", \
"clone", "fragment")
for is_gap, alines in groupby(agp, key=lambda x: (x.object, x.is_gap)):
alines = list(alines)
is_gap = is_gap[1]
if is_gap:
gap_size = sum(x.gap_length for x in alines)
gap_types = set(x.gap_type for x in alines)
for gtype in ("centromere", "telomere"):
if gtype in gap_types:
gap_size = gtype
sizes.append(gap_size)
b = deepcopy(alines[0])
b.object_beg = min(x.object_beg for x in alines)
b.object_end = max(x.object_end for x in alines)
b.gap_length = sum(x.gap_length for x in alines)
assert b.gap_length == b.object_end - b.object_beg + 1
b.component_type = 'U' if b.gap_length == 100 else 'N'
gtypes = [x.gap_type for x in alines]
for gtype in priorities:
if gtype in gtypes:
b.gap_type = gtype
break
linkages = [x.linkage for x in alines]
for linkage in ("no", "yes"):
if linkage in linkages:
b.linkage = linkage
break
alines = [b]
data.extend(alines)
loghistogram(sizes)
if opts.header:
AGP.print_header(fw, organism="Medicago truncatula",
taxid=3880, source="J. Craig Venter Institute")
if merge:
for ob, bb in groupby(data, lambda x: x.object):
for i, b in enumerate(bb):
b.part_number = i + 1
print(b, file=fw)
return merged_agpfile | python | def gaps(args):
"""
%prog gaps agpfile
Print out the distribution of gapsizes. Option --merge allows merging of
adjacent gaps which is used by tidy().
"""
from jcvi.graphics.histogram import loghistogram
p = OptionParser(gaps.__doc__)
p.add_option("--merge", dest="merge", default=False, action="store_true",
help="Merge adjacent gaps (to conform to AGP specification)")
p.add_option("--header", default=False, action="store_true",
help="Produce an AGP header [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
merge = opts.merge
agpfile, = args
if merge:
merged_agpfile = agpfile.replace(".agp", ".merged.agp")
fw = open(merged_agpfile, "w")
agp = AGP(agpfile)
sizes = []
data = [] # store merged AGPLine's
priorities = ("centromere", "telomere", "scaffold", "contig", \
"clone", "fragment")
for is_gap, alines in groupby(agp, key=lambda x: (x.object, x.is_gap)):
alines = list(alines)
is_gap = is_gap[1]
if is_gap:
gap_size = sum(x.gap_length for x in alines)
gap_types = set(x.gap_type for x in alines)
for gtype in ("centromere", "telomere"):
if gtype in gap_types:
gap_size = gtype
sizes.append(gap_size)
b = deepcopy(alines[0])
b.object_beg = min(x.object_beg for x in alines)
b.object_end = max(x.object_end for x in alines)
b.gap_length = sum(x.gap_length for x in alines)
assert b.gap_length == b.object_end - b.object_beg + 1
b.component_type = 'U' if b.gap_length == 100 else 'N'
gtypes = [x.gap_type for x in alines]
for gtype in priorities:
if gtype in gtypes:
b.gap_type = gtype
break
linkages = [x.linkage for x in alines]
for linkage in ("no", "yes"):
if linkage in linkages:
b.linkage = linkage
break
alines = [b]
data.extend(alines)
loghistogram(sizes)
if opts.header:
AGP.print_header(fw, organism="Medicago truncatula",
taxid=3880, source="J. Craig Venter Institute")
if merge:
for ob, bb in groupby(data, lambda x: x.object):
for i, b in enumerate(bb):
b.part_number = i + 1
print(b, file=fw)
return merged_agpfile | [
"def",
"gaps",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"graphics",
".",
"histogram",
"import",
"loghistogram",
"p",
"=",
"OptionParser",
"(",
"gaps",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--merge\"",
",",
"dest",
"=",
"\"merge\"",
",",... | %prog gaps agpfile
Print out the distribution of gapsizes. Option --merge allows merging of
adjacent gaps which is used by tidy(). | [
"%prog",
"gaps",
"agpfile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/agp.py#L1645-L1724 | train | 200,811 |
tanghaibao/jcvi | jcvi/formats/agp.py | tidy | def tidy(args):
"""
%prog tidy agpfile componentfasta
Given an agp file, run through the following steps:
1. Trim components with dangling N's
2. Merge adjacent gaps
3. Trim gaps at the end of an object
4. Reindex the agp
Final output is in `.tidy.agp`.
"""
p = OptionParser(tidy.__doc__)
p.add_option("--nogaps", default=False, action="store_true",
help="Remove all gap lines [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(p.print_help())
agpfile, componentfasta = args
originalagpfile = agpfile
# Step 1: Trim terminal Ns
tmpfasta = "tmp.fasta"
trimmed_agpfile = build([agpfile, componentfasta, tmpfasta,
"--newagp", "--novalidate"])
os.remove(tmpfasta)
agpfile = trimmed_agpfile
agpfile = reindex([agpfile, "--inplace"])
# Step 2: Merge adjacent gaps
merged_agpfile = gaps([agpfile, "--merge"])
os.remove(agpfile)
# Step 3: Trim gaps at the end of object
agpfile = merged_agpfile
agp = AGP(agpfile)
newagpfile = agpfile.replace(".agp", ".fixed.agp")
fw = open(newagpfile, "w")
for object, a in groupby(agp, key=lambda x: x.object):
a = list(a)
if a[0].is_gap:
g, a = a[0], a[1:]
logging.debug("Trim beginning Ns({0}) of {1}".\
format(g.gap_length, object))
if a and a[-1].is_gap:
a, g = a[:-1], a[-1]
logging.debug("Trim trailing Ns({0}) of {1}".\
format(g.gap_length, object))
print("\n".join(str(x) for x in a), file=fw)
fw.close()
os.remove(agpfile)
# Step 4: Final reindex
agpfile = newagpfile
reindex_opts = [agpfile, "--inplace"]
if opts.nogaps:
reindex_opts += ["--nogaps"]
agpfile = reindex(reindex_opts)
tidyagpfile = originalagpfile.replace(".agp", ".tidy.agp")
shutil.move(agpfile, tidyagpfile)
logging.debug("File written to `{0}`.".format(tidyagpfile))
return tidyagpfile | python | def tidy(args):
"""
%prog tidy agpfile componentfasta
Given an agp file, run through the following steps:
1. Trim components with dangling N's
2. Merge adjacent gaps
3. Trim gaps at the end of an object
4. Reindex the agp
Final output is in `.tidy.agp`.
"""
p = OptionParser(tidy.__doc__)
p.add_option("--nogaps", default=False, action="store_true",
help="Remove all gap lines [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(p.print_help())
agpfile, componentfasta = args
originalagpfile = agpfile
# Step 1: Trim terminal Ns
tmpfasta = "tmp.fasta"
trimmed_agpfile = build([agpfile, componentfasta, tmpfasta,
"--newagp", "--novalidate"])
os.remove(tmpfasta)
agpfile = trimmed_agpfile
agpfile = reindex([agpfile, "--inplace"])
# Step 2: Merge adjacent gaps
merged_agpfile = gaps([agpfile, "--merge"])
os.remove(agpfile)
# Step 3: Trim gaps at the end of object
agpfile = merged_agpfile
agp = AGP(agpfile)
newagpfile = agpfile.replace(".agp", ".fixed.agp")
fw = open(newagpfile, "w")
for object, a in groupby(agp, key=lambda x: x.object):
a = list(a)
if a[0].is_gap:
g, a = a[0], a[1:]
logging.debug("Trim beginning Ns({0}) of {1}".\
format(g.gap_length, object))
if a and a[-1].is_gap:
a, g = a[:-1], a[-1]
logging.debug("Trim trailing Ns({0}) of {1}".\
format(g.gap_length, object))
print("\n".join(str(x) for x in a), file=fw)
fw.close()
os.remove(agpfile)
# Step 4: Final reindex
agpfile = newagpfile
reindex_opts = [agpfile, "--inplace"]
if opts.nogaps:
reindex_opts += ["--nogaps"]
agpfile = reindex(reindex_opts)
tidyagpfile = originalagpfile.replace(".agp", ".tidy.agp")
shutil.move(agpfile, tidyagpfile)
logging.debug("File written to `{0}`.".format(tidyagpfile))
return tidyagpfile | [
"def",
"tidy",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"tidy",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--nogaps\"",
",",
"default",
"=",
"False",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Remove all gap lines [de... | %prog tidy agpfile componentfasta
Given an agp file, run through the following steps:
1. Trim components with dangling N's
2. Merge adjacent gaps
3. Trim gaps at the end of an object
4. Reindex the agp
Final output is in `.tidy.agp`. | [
"%prog",
"tidy",
"agpfile",
"componentfasta"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/agp.py#L1727-L1792 | train | 200,812 |
tanghaibao/jcvi | jcvi/formats/agp.py | build | def build(args):
"""
%prog build agpfile componentfasta targetfasta
Build targetfasta based on info from agpfile
"""
p = OptionParser(build.__doc__)
p.add_option("--newagp", dest="newagp", default=False, action="store_true",
help="Check components to trim dangling N's [default: %default]")
p.add_option("--novalidate", dest="novalidate", default=False,
action="store_true",
help="Don't validate the agpfile [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
agpfile, componentfasta, targetfasta = args
validate = not opts.novalidate
if opts.newagp:
assert agpfile.endswith(".agp")
newagpfile = agpfile.replace(".agp", ".trimmed.agp")
newagp = open(newagpfile, "w")
else:
newagpfile = None
newagp = None
agp = AGP(agpfile, validate=validate, sorted=True)
agp.build_all(componentfasta=componentfasta, targetfasta=targetfasta,
newagp=newagp)
logging.debug("Target fasta written to `{0}`.".format(targetfasta))
return newagpfile | python | def build(args):
"""
%prog build agpfile componentfasta targetfasta
Build targetfasta based on info from agpfile
"""
p = OptionParser(build.__doc__)
p.add_option("--newagp", dest="newagp", default=False, action="store_true",
help="Check components to trim dangling N's [default: %default]")
p.add_option("--novalidate", dest="novalidate", default=False,
action="store_true",
help="Don't validate the agpfile [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
agpfile, componentfasta, targetfasta = args
validate = not opts.novalidate
if opts.newagp:
assert agpfile.endswith(".agp")
newagpfile = agpfile.replace(".agp", ".trimmed.agp")
newagp = open(newagpfile, "w")
else:
newagpfile = None
newagp = None
agp = AGP(agpfile, validate=validate, sorted=True)
agp.build_all(componentfasta=componentfasta, targetfasta=targetfasta,
newagp=newagp)
logging.debug("Target fasta written to `{0}`.".format(targetfasta))
return newagpfile | [
"def",
"build",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"build",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--newagp\"",
",",
"dest",
"=",
"\"newagp\"",
",",
"default",
"=",
"False",
",",
"action",
"=",
"\"store_true\"",
",",
"h... | %prog build agpfile componentfasta targetfasta
Build targetfasta based on info from agpfile | [
"%prog",
"build",
"agpfile",
"componentfasta",
"targetfasta"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/agp.py#L1795-L1828 | train | 200,813 |
tanghaibao/jcvi | jcvi/formats/agp.py | validate | def validate(args):
"""
%prog validate agpfile componentfasta targetfasta
validate consistency between agpfile and targetfasta
"""
p = OptionParser(validate.__doc__)
opts, args = p.parse_args(args)
try:
agpfile, componentfasta, targetfasta = args
except Exception as e:
sys.exit(p.print_help())
agp = AGP(agpfile)
build = Fasta(targetfasta)
bacs = Fasta(componentfasta, index=False)
# go through this line by line
for aline in agp:
try:
build_seq = build.sequence(dict(chr=aline.object,
start=aline.object_beg, stop=aline.object_end))
if aline.is_gap:
assert build_seq.upper() == aline.gap_length * 'N', \
"gap mismatch: %s" % aline
else:
bac_seq = bacs.sequence(dict(chr=aline.component_id,
start=aline.component_beg, stop=aline.component_end,
strand=aline.orientation))
assert build_seq.upper() == bac_seq.upper(), \
"sequence mismatch: %s" % aline
logging.debug("%s:%d-%d verified" % (aline.object,
aline.object_beg, aline.object_end))
except Exception as e:
logging.error(e) | python | def validate(args):
"""
%prog validate agpfile componentfasta targetfasta
validate consistency between agpfile and targetfasta
"""
p = OptionParser(validate.__doc__)
opts, args = p.parse_args(args)
try:
agpfile, componentfasta, targetfasta = args
except Exception as e:
sys.exit(p.print_help())
agp = AGP(agpfile)
build = Fasta(targetfasta)
bacs = Fasta(componentfasta, index=False)
# go through this line by line
for aline in agp:
try:
build_seq = build.sequence(dict(chr=aline.object,
start=aline.object_beg, stop=aline.object_end))
if aline.is_gap:
assert build_seq.upper() == aline.gap_length * 'N', \
"gap mismatch: %s" % aline
else:
bac_seq = bacs.sequence(dict(chr=aline.component_id,
start=aline.component_beg, stop=aline.component_end,
strand=aline.orientation))
assert build_seq.upper() == bac_seq.upper(), \
"sequence mismatch: %s" % aline
logging.debug("%s:%d-%d verified" % (aline.object,
aline.object_beg, aline.object_end))
except Exception as e:
logging.error(e) | [
"def",
"validate",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"validate",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"try",
":",
"agpfile",
",",
"componentfasta",
",",
"targetfasta",
"=",
"args",... | %prog validate agpfile componentfasta targetfasta
validate consistency between agpfile and targetfasta | [
"%prog",
"validate",
"agpfile",
"componentfasta",
"targetfasta"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/agp.py#L1831-L1871 | train | 200,814 |
tanghaibao/jcvi | jcvi/formats/agp.py | AGP.getNorthSouthClone | def getNorthSouthClone(self, i):
"""
Returns the adjacent clone name from both sides.
"""
north = self.getAdjacentClone(i, south=False)
south = self.getAdjacentClone(i)
return north, south | python | def getNorthSouthClone(self, i):
"""
Returns the adjacent clone name from both sides.
"""
north = self.getAdjacentClone(i, south=False)
south = self.getAdjacentClone(i)
return north, south | [
"def",
"getNorthSouthClone",
"(",
"self",
",",
"i",
")",
":",
"north",
"=",
"self",
".",
"getAdjacentClone",
"(",
"i",
",",
"south",
"=",
"False",
")",
"south",
"=",
"self",
".",
"getAdjacentClone",
"(",
"i",
")",
"return",
"north",
",",
"south"
] | Returns the adjacent clone name from both sides. | [
"Returns",
"the",
"adjacent",
"clone",
"name",
"from",
"both",
"sides",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/agp.py#L269-L275 | train | 200,815 |
tanghaibao/jcvi | jcvi/formats/agp.py | AGP.build_one | def build_one(self, object, lines, fasta, fw, newagp=None):
"""
Construct molecule using component fasta sequence
"""
components = []
total_bp = 0
for line in lines:
if line.is_gap:
seq = 'N' * line.gap_length
if newagp:
print(line, file=newagp)
else:
seq = fasta.sequence(dict(chr=line.component_id,
start=line.component_beg,
stop=line.component_end,
strand=line.orientation))
# Check for dangling N's
if newagp:
trimNs(seq, line, newagp)
components.append(seq)
total_bp += len(seq)
if self.validate:
assert total_bp == line.object_end, \
"cumulative base pairs (%d) does not match (%d)" % \
(total_bp, line.object_end)
if not newagp:
rec = SeqRecord(Seq(''.join(components)), id=object, description="")
SeqIO.write([rec], fw, "fasta")
if len(rec) > 1000000:
logging.debug("Write object %s to `%s`" % (object, fw.name)) | python | def build_one(self, object, lines, fasta, fw, newagp=None):
"""
Construct molecule using component fasta sequence
"""
components = []
total_bp = 0
for line in lines:
if line.is_gap:
seq = 'N' * line.gap_length
if newagp:
print(line, file=newagp)
else:
seq = fasta.sequence(dict(chr=line.component_id,
start=line.component_beg,
stop=line.component_end,
strand=line.orientation))
# Check for dangling N's
if newagp:
trimNs(seq, line, newagp)
components.append(seq)
total_bp += len(seq)
if self.validate:
assert total_bp == line.object_end, \
"cumulative base pairs (%d) does not match (%d)" % \
(total_bp, line.object_end)
if not newagp:
rec = SeqRecord(Seq(''.join(components)), id=object, description="")
SeqIO.write([rec], fw, "fasta")
if len(rec) > 1000000:
logging.debug("Write object %s to `%s`" % (object, fw.name)) | [
"def",
"build_one",
"(",
"self",
",",
"object",
",",
"lines",
",",
"fasta",
",",
"fw",
",",
"newagp",
"=",
"None",
")",
":",
"components",
"=",
"[",
"]",
"total_bp",
"=",
"0",
"for",
"line",
"in",
"lines",
":",
"if",
"line",
".",
"is_gap",
":",
"... | Construct molecule using component fasta sequence | [
"Construct",
"molecule",
"using",
"component",
"fasta",
"sequence"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/agp.py#L393-L427 | train | 200,816 |
tanghaibao/jcvi | jcvi/formats/agp.py | TPF.getAdjacentClone | def getAdjacentClone(self, i, south=True):
"""
Returns adjacent clone name, either the line before or after the current
line.
"""
rr = xrange(i + 1, len(self)) if south else xrange(i - 1, -1, -1)
a = self[i]
for ix in rr:
x = self[ix]
if x.object != a.object:
break
return x
return None | python | def getAdjacentClone(self, i, south=True):
"""
Returns adjacent clone name, either the line before or after the current
line.
"""
rr = xrange(i + 1, len(self)) if south else xrange(i - 1, -1, -1)
a = self[i]
for ix in rr:
x = self[ix]
if x.object != a.object:
break
return x
return None | [
"def",
"getAdjacentClone",
"(",
"self",
",",
"i",
",",
"south",
"=",
"True",
")",
":",
"rr",
"=",
"xrange",
"(",
"i",
"+",
"1",
",",
"len",
"(",
"self",
")",
")",
"if",
"south",
"else",
"xrange",
"(",
"i",
"-",
"1",
",",
"-",
"1",
",",
"-",
... | Returns adjacent clone name, either the line before or after the current
line. | [
"Returns",
"adjacent",
"clone",
"name",
"either",
"the",
"line",
"before",
"or",
"after",
"the",
"current",
"line",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/agp.py#L569-L581 | train | 200,817 |
tanghaibao/jcvi | jcvi/annotation/train.py | genemark | def genemark(args):
"""
%prog genemark species fastafile
Train GENEMARK model given fastafile. GENEMARK self-trains so no trainig
model gff file is needed.
"""
p = OptionParser(genemark.__doc__)
p.add_option("--junctions", help="Path to `junctions.bed` from Tophat2")
p.set_home("gmes")
p.set_cpus(cpus=32)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
species, fastafile = args
junctions = opts.junctions
mhome = opts.gmes_home
license = op.expanduser("~/.gm_key")
assert op.exists(license), "License key ({0}) not found!".format(license)
cmd = "{0}/gmes_petap.pl --sequence {1}".format(mhome, fastafile)
cmd += " --cores {0}".format(opts.cpus)
if junctions:
intronsgff = "introns.gff"
if need_update(junctions, intronsgff):
jcmd = "{0}/bet_to_gff.pl".format(mhome)
jcmd += " --bed {0} --gff {1} --label Tophat2".\
format(junctions, intronsgff)
sh(jcmd)
cmd += " --ET {0} --et_score 10".format(intronsgff)
else:
cmd += " --ES"
sh(cmd)
logging.debug("GENEMARK matrix written to `output/gmhmm.mod") | python | def genemark(args):
"""
%prog genemark species fastafile
Train GENEMARK model given fastafile. GENEMARK self-trains so no trainig
model gff file is needed.
"""
p = OptionParser(genemark.__doc__)
p.add_option("--junctions", help="Path to `junctions.bed` from Tophat2")
p.set_home("gmes")
p.set_cpus(cpus=32)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
species, fastafile = args
junctions = opts.junctions
mhome = opts.gmes_home
license = op.expanduser("~/.gm_key")
assert op.exists(license), "License key ({0}) not found!".format(license)
cmd = "{0}/gmes_petap.pl --sequence {1}".format(mhome, fastafile)
cmd += " --cores {0}".format(opts.cpus)
if junctions:
intronsgff = "introns.gff"
if need_update(junctions, intronsgff):
jcmd = "{0}/bet_to_gff.pl".format(mhome)
jcmd += " --bed {0} --gff {1} --label Tophat2".\
format(junctions, intronsgff)
sh(jcmd)
cmd += " --ET {0} --et_score 10".format(intronsgff)
else:
cmd += " --ES"
sh(cmd)
logging.debug("GENEMARK matrix written to `output/gmhmm.mod") | [
"def",
"genemark",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"genemark",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--junctions\"",
",",
"help",
"=",
"\"Path to `junctions.bed` from Tophat2\"",
")",
"p",
".",
"set_home",
"(",
"\"gmes\"",
... | %prog genemark species fastafile
Train GENEMARK model given fastafile. GENEMARK self-trains so no trainig
model gff file is needed. | [
"%prog",
"genemark",
"species",
"fastafile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/annotation/train.py#L83-L119 | train | 200,818 |
tanghaibao/jcvi | jcvi/annotation/train.py | snap | def snap(args):
"""
%prog snap species gffile fastafile
Train SNAP model given gffile and fastafile. Whole procedure taken from:
<http://gmod.org/wiki/MAKER_Tutorial_2012>
"""
p = OptionParser(snap.__doc__)
p.set_home("maker")
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
species, gffile, fastafile = args
mhome = opts.maker_home
snapdir = "snap"
mkdir(snapdir)
cwd = os.getcwd()
os.chdir(snapdir)
newgffile = "training.gff3"
logging.debug("Construct GFF file combined with sequence ...")
sh("cat ../{0} > {1}".format(gffile, newgffile))
sh('echo "##FASTA" >> {0}'.format(newgffile))
sh("cat ../{0} >> {1}".format(fastafile, newgffile))
logging.debug("Make models ...")
sh("{0}/src/bin/maker2zff training.gff3".format(mhome))
sh("{0}/exe/snap/fathom -categorize 1000 genome.ann genome.dna".format(mhome))
sh("{0}/exe/snap/fathom -export 1000 -plus uni.ann uni.dna".format(mhome))
sh("{0}/exe/snap/forge export.ann export.dna".format(mhome))
sh("{0}/exe/snap/hmm-assembler.pl {1} . > {1}.hmm".format(mhome, species))
os.chdir(cwd)
logging.debug("SNAP matrix written to `{0}/{1}.hmm`".format(snapdir, species)) | python | def snap(args):
"""
%prog snap species gffile fastafile
Train SNAP model given gffile and fastafile. Whole procedure taken from:
<http://gmod.org/wiki/MAKER_Tutorial_2012>
"""
p = OptionParser(snap.__doc__)
p.set_home("maker")
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
species, gffile, fastafile = args
mhome = opts.maker_home
snapdir = "snap"
mkdir(snapdir)
cwd = os.getcwd()
os.chdir(snapdir)
newgffile = "training.gff3"
logging.debug("Construct GFF file combined with sequence ...")
sh("cat ../{0} > {1}".format(gffile, newgffile))
sh('echo "##FASTA" >> {0}'.format(newgffile))
sh("cat ../{0} >> {1}".format(fastafile, newgffile))
logging.debug("Make models ...")
sh("{0}/src/bin/maker2zff training.gff3".format(mhome))
sh("{0}/exe/snap/fathom -categorize 1000 genome.ann genome.dna".format(mhome))
sh("{0}/exe/snap/fathom -export 1000 -plus uni.ann uni.dna".format(mhome))
sh("{0}/exe/snap/forge export.ann export.dna".format(mhome))
sh("{0}/exe/snap/hmm-assembler.pl {1} . > {1}.hmm".format(mhome, species))
os.chdir(cwd)
logging.debug("SNAP matrix written to `{0}/{1}.hmm`".format(snapdir, species)) | [
"def",
"snap",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"snap",
".",
"__doc__",
")",
"p",
".",
"set_home",
"(",
"\"maker\"",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!="... | %prog snap species gffile fastafile
Train SNAP model given gffile and fastafile. Whole procedure taken from:
<http://gmod.org/wiki/MAKER_Tutorial_2012> | [
"%prog",
"snap",
"species",
"gffile",
"fastafile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/annotation/train.py#L122-L158 | train | 200,819 |
tanghaibao/jcvi | jcvi/annotation/train.py | augustus | def augustus(args):
"""
%prog augustus species gffile fastafile
Train AUGUSTUS model given gffile and fastafile. Whole procedure taken from:
<http://www.molecularevolution.org/molevolfiles/exercises/augustus/training.html>
"""
p = OptionParser(augustus.__doc__)
p.add_option("--autotrain", default=False, action="store_true",
help="Run autoAugTrain.pl to iteratively train AUGUSTUS")
p.set_home("augustus")
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
species, gffile, fastafile = args
mhome = opts.augustus_home
augdir = "augustus"
cwd = os.getcwd()
mkdir(augdir)
os.chdir(augdir)
target = "{0}/config/species/{1}".format(mhome, species)
if op.exists(target):
logging.debug("Removing existing target `{0}`".format(target))
sh("rm -rf {0}".format(target))
sh("{0}/scripts/new_species.pl --species={1}".format(mhome, species))
sh("{0}/scripts/gff2gbSmallDNA.pl ../{1} ../{2} 1000 raw.gb".\
format(mhome, gffile, fastafile))
sh("{0}/bin/etraining --species={1} raw.gb 2> train.err".\
format(mhome, species))
sh("cat train.err | perl -pe 's/.*in sequence (\S+): .*/$1/' > badgenes.lst")
sh("{0}/scripts/filterGenes.pl badgenes.lst raw.gb > training.gb".\
format(mhome))
sh("grep -c LOCUS raw.gb training.gb")
# autoAugTrain failed to execute, disable for now
if opts.autotrain:
sh("rm -rf {0}".format(target))
sh("{0}/scripts/autoAugTrain.pl --trainingset=training.gb --species={1}".\
format(mhome, species))
os.chdir(cwd)
sh("cp -r {0} augustus/".format(target)) | python | def augustus(args):
"""
%prog augustus species gffile fastafile
Train AUGUSTUS model given gffile and fastafile. Whole procedure taken from:
<http://www.molecularevolution.org/molevolfiles/exercises/augustus/training.html>
"""
p = OptionParser(augustus.__doc__)
p.add_option("--autotrain", default=False, action="store_true",
help="Run autoAugTrain.pl to iteratively train AUGUSTUS")
p.set_home("augustus")
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
species, gffile, fastafile = args
mhome = opts.augustus_home
augdir = "augustus"
cwd = os.getcwd()
mkdir(augdir)
os.chdir(augdir)
target = "{0}/config/species/{1}".format(mhome, species)
if op.exists(target):
logging.debug("Removing existing target `{0}`".format(target))
sh("rm -rf {0}".format(target))
sh("{0}/scripts/new_species.pl --species={1}".format(mhome, species))
sh("{0}/scripts/gff2gbSmallDNA.pl ../{1} ../{2} 1000 raw.gb".\
format(mhome, gffile, fastafile))
sh("{0}/bin/etraining --species={1} raw.gb 2> train.err".\
format(mhome, species))
sh("cat train.err | perl -pe 's/.*in sequence (\S+): .*/$1/' > badgenes.lst")
sh("{0}/scripts/filterGenes.pl badgenes.lst raw.gb > training.gb".\
format(mhome))
sh("grep -c LOCUS raw.gb training.gb")
# autoAugTrain failed to execute, disable for now
if opts.autotrain:
sh("rm -rf {0}".format(target))
sh("{0}/scripts/autoAugTrain.pl --trainingset=training.gb --species={1}".\
format(mhome, species))
os.chdir(cwd)
sh("cp -r {0} augustus/".format(target)) | [
"def",
"augustus",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"augustus",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--autotrain\"",
",",
"default",
"=",
"False",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Run autoAugTr... | %prog augustus species gffile fastafile
Train AUGUSTUS model given gffile and fastafile. Whole procedure taken from:
<http://www.molecularevolution.org/molevolfiles/exercises/augustus/training.html> | [
"%prog",
"augustus",
"species",
"gffile",
"fastafile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/annotation/train.py#L161-L207 | train | 200,820 |
tanghaibao/jcvi | jcvi/assembly/ca.py | merger | def merger(args):
"""
%prog merger layout gkpStore contigs.fasta
Merge reads into one contig.
"""
p = OptionParser(merger.__doc__)
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
layout, gkpstore, contigs = args
fp = open(layout)
pf = "0"
iidfile = pf + ".iids"
for i, row in enumerate(fp):
logging.debug("Read unitig {0}".format(i))
fw = open(iidfile, "w")
layout = row.split("|")
print("\n".join(layout), file=fw)
fw.close()
cmd = "gatekeeper -iid {0}.iids -dumpfasta {0} {1}".format(pf, gkpstore)
sh(cmd)
fastafile = "{0}.fasta".format(pf)
newfastafile = "{0}.new.fasta".format(pf)
format([fastafile, newfastafile, "--sequential=replace", \
"--sequentialoffset=1", "--nodesc"])
fasta([newfastafile])
sh("rm -rf {0}".format(pf))
cmd = "runCA {0}.frg -p {0} -d {0} consensus=pbutgcns".format(pf)
cmd += " unitigger=bogart doFragmentCorrection=0 doUnitigSplitting=0"
sh(cmd)
outdir = "{0}/9-terminator".format(pf)
cmd = "cat {0}/{1}.ctg.fasta {0}/{1}.deg.fasta {0}/{1}.singleton.fasta"\
.format(outdir, pf)
sh(cmd, outfile=contigs, append=True) | python | def merger(args):
"""
%prog merger layout gkpStore contigs.fasta
Merge reads into one contig.
"""
p = OptionParser(merger.__doc__)
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
layout, gkpstore, contigs = args
fp = open(layout)
pf = "0"
iidfile = pf + ".iids"
for i, row in enumerate(fp):
logging.debug("Read unitig {0}".format(i))
fw = open(iidfile, "w")
layout = row.split("|")
print("\n".join(layout), file=fw)
fw.close()
cmd = "gatekeeper -iid {0}.iids -dumpfasta {0} {1}".format(pf, gkpstore)
sh(cmd)
fastafile = "{0}.fasta".format(pf)
newfastafile = "{0}.new.fasta".format(pf)
format([fastafile, newfastafile, "--sequential=replace", \
"--sequentialoffset=1", "--nodesc"])
fasta([newfastafile])
sh("rm -rf {0}".format(pf))
cmd = "runCA {0}.frg -p {0} -d {0} consensus=pbutgcns".format(pf)
cmd += " unitigger=bogart doFragmentCorrection=0 doUnitigSplitting=0"
sh(cmd)
outdir = "{0}/9-terminator".format(pf)
cmd = "cat {0}/{1}.ctg.fasta {0}/{1}.deg.fasta {0}/{1}.singleton.fasta"\
.format(outdir, pf)
sh(cmd, outfile=contigs, append=True) | [
"def",
"merger",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"merger",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"3",
":",
"sys",
".",
"exit",
"(",
"n... | %prog merger layout gkpStore contigs.fasta
Merge reads into one contig. | [
"%prog",
"merger",
"layout",
"gkpStore",
"contigs",
".",
"fasta"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/ca.py#L455-L494 | train | 200,821 |
tanghaibao/jcvi | jcvi/assembly/ca.py | unitigs | def unitigs(args):
"""
%prog unitigs best.edges
Reads Celera Assembler's "best.edges" and extract all unitigs.
"""
p = OptionParser(unitigs.__doc__)
p.add_option("--maxerr", default=2, type="int", help="Maximum error rate")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
bestedges, = args
G = read_graph(bestedges, maxerr=opts.maxerr, directed=True)
H = nx.Graph()
intconv = lambda x: int(x.split("-")[0])
for k, v in G.iteritems():
if k == G.get(v, None):
H.add_edge(intconv(k), intconv(v))
nunitigs = nreads = 0
for h in nx.connected_component_subgraphs(H, copy=False):
st = [x for x in h if h.degree(x) == 1]
if len(st) != 2:
continue
src, target = st
path = list(nx.all_simple_paths(h, src, target))
assert len(path) == 1
path, = path
print("|".join(str(x) for x in path))
nunitigs += 1
nreads += len(path)
logging.debug("A total of {0} unitigs built from {1} reads."\
.format(nunitigs, nreads)) | python | def unitigs(args):
"""
%prog unitigs best.edges
Reads Celera Assembler's "best.edges" and extract all unitigs.
"""
p = OptionParser(unitigs.__doc__)
p.add_option("--maxerr", default=2, type="int", help="Maximum error rate")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
bestedges, = args
G = read_graph(bestedges, maxerr=opts.maxerr, directed=True)
H = nx.Graph()
intconv = lambda x: int(x.split("-")[0])
for k, v in G.iteritems():
if k == G.get(v, None):
H.add_edge(intconv(k), intconv(v))
nunitigs = nreads = 0
for h in nx.connected_component_subgraphs(H, copy=False):
st = [x for x in h if h.degree(x) == 1]
if len(st) != 2:
continue
src, target = st
path = list(nx.all_simple_paths(h, src, target))
assert len(path) == 1
path, = path
print("|".join(str(x) for x in path))
nunitigs += 1
nreads += len(path)
logging.debug("A total of {0} unitigs built from {1} reads."\
.format(nunitigs, nreads)) | [
"def",
"unitigs",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"unitigs",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--maxerr\"",
",",
"default",
"=",
"2",
",",
"type",
"=",
"\"int\"",
",",
"help",
"=",
"\"Maximum error rate\"",
")",
... | %prog unitigs best.edges
Reads Celera Assembler's "best.edges" and extract all unitigs. | [
"%prog",
"unitigs",
"best",
".",
"edges"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/ca.py#L497-L531 | train | 200,822 |
tanghaibao/jcvi | jcvi/assembly/ca.py | astat | def astat(args):
"""
%prog astat coverage.log
Create coverage-rho scatter plot.
"""
p = OptionParser(astat.__doc__)
p.add_option("--cutoff", default=1000, type="int",
help="Length cutoff [default: %default]")
p.add_option("--genome", default="",
help="Genome name [default: %default]")
p.add_option("--arrDist", default=False, action="store_true",
help="Use arrDist instead [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
covfile, = args
cutoff = opts.cutoff
genome = opts.genome
plot_arrDist = opts.arrDist
suffix = ".{0}".format(cutoff)
small_covfile = covfile + suffix
update_covfile = need_update(covfile, small_covfile)
if update_covfile:
fw = open(small_covfile, "w")
else:
logging.debug("Found `{0}`, will use this one".format(small_covfile))
covfile = small_covfile
fp = open(covfile)
header = next(fp)
if update_covfile:
fw.write(header)
data = []
msg = "{0} tigs scanned ..."
for row in fp:
tigID, rho, covStat, arrDist = row.split()
tigID = int(tigID)
if tigID % 1000000 == 0:
sys.stderr.write(msg.format(tigID) + "\r")
rho, covStat, arrDist = [float(x) for x in (rho, covStat, arrDist)]
if rho < cutoff:
continue
if update_covfile:
fw.write(row)
data.append((tigID, rho, covStat, arrDist))
print(msg.format(tigID), file=sys.stderr)
from jcvi.graphics.base import plt, savefig
logging.debug("Plotting {0} data points.".format(len(data)))
tigID, rho, covStat, arrDist = zip(*data)
y = arrDist if plot_arrDist else covStat
ytag = "arrDist" if plot_arrDist else "covStat"
fig = plt.figure(1, (7, 7))
ax = fig.add_axes([.12, .1, .8, .8])
ax.plot(rho, y, ".", color="lightslategrey")
xtag = "rho"
info = (genome, xtag, ytag)
title = "{0} {1} vs. {2}".format(*info)
ax.set_title(title)
ax.set_xlabel(xtag)
ax.set_ylabel(ytag)
if plot_arrDist:
ax.set_yscale('log')
imagename = "{0}.png".format(".".join(info))
savefig(imagename, dpi=150) | python | def astat(args):
"""
%prog astat coverage.log
Create coverage-rho scatter plot.
"""
p = OptionParser(astat.__doc__)
p.add_option("--cutoff", default=1000, type="int",
help="Length cutoff [default: %default]")
p.add_option("--genome", default="",
help="Genome name [default: %default]")
p.add_option("--arrDist", default=False, action="store_true",
help="Use arrDist instead [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
covfile, = args
cutoff = opts.cutoff
genome = opts.genome
plot_arrDist = opts.arrDist
suffix = ".{0}".format(cutoff)
small_covfile = covfile + suffix
update_covfile = need_update(covfile, small_covfile)
if update_covfile:
fw = open(small_covfile, "w")
else:
logging.debug("Found `{0}`, will use this one".format(small_covfile))
covfile = small_covfile
fp = open(covfile)
header = next(fp)
if update_covfile:
fw.write(header)
data = []
msg = "{0} tigs scanned ..."
for row in fp:
tigID, rho, covStat, arrDist = row.split()
tigID = int(tigID)
if tigID % 1000000 == 0:
sys.stderr.write(msg.format(tigID) + "\r")
rho, covStat, arrDist = [float(x) for x in (rho, covStat, arrDist)]
if rho < cutoff:
continue
if update_covfile:
fw.write(row)
data.append((tigID, rho, covStat, arrDist))
print(msg.format(tigID), file=sys.stderr)
from jcvi.graphics.base import plt, savefig
logging.debug("Plotting {0} data points.".format(len(data)))
tigID, rho, covStat, arrDist = zip(*data)
y = arrDist if plot_arrDist else covStat
ytag = "arrDist" if plot_arrDist else "covStat"
fig = plt.figure(1, (7, 7))
ax = fig.add_axes([.12, .1, .8, .8])
ax.plot(rho, y, ".", color="lightslategrey")
xtag = "rho"
info = (genome, xtag, ytag)
title = "{0} {1} vs. {2}".format(*info)
ax.set_title(title)
ax.set_xlabel(xtag)
ax.set_ylabel(ytag)
if plot_arrDist:
ax.set_yscale('log')
imagename = "{0}.png".format(".".join(info))
savefig(imagename, dpi=150) | [
"def",
"astat",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"astat",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--cutoff\"",
",",
"default",
"=",
"1000",
",",
"type",
"=",
"\"int\"",
",",
"help",
"=",
"\"Length cutoff [default: %default... | %prog astat coverage.log
Create coverage-rho scatter plot. | [
"%prog",
"astat",
"coverage",
".",
"log"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/ca.py#L612-L690 | train | 200,823 |
tanghaibao/jcvi | jcvi/assembly/ca.py | emitFragment | def emitFragment(fw, fragID, libID, shredded_seq, clr=None, qvchar='l', fasta=False):
"""
Print out the shredded sequence.
"""
if fasta:
s = SeqRecord(shredded_seq, id=fragID, description="")
SeqIO.write([s], fw, "fasta")
return
seq = str(shredded_seq)
slen = len(seq)
qvs = qvchar * slen # shredded reads have default low qv
if clr is None:
clr_beg, clr_end = 0, slen
else:
clr_beg, clr_end = clr
print(frgTemplate.format(fragID=fragID, libID=libID,
seq=seq, qvs=qvs, clr_beg=clr_beg, clr_end=clr_end), file=fw) | python | def emitFragment(fw, fragID, libID, shredded_seq, clr=None, qvchar='l', fasta=False):
"""
Print out the shredded sequence.
"""
if fasta:
s = SeqRecord(shredded_seq, id=fragID, description="")
SeqIO.write([s], fw, "fasta")
return
seq = str(shredded_seq)
slen = len(seq)
qvs = qvchar * slen # shredded reads have default low qv
if clr is None:
clr_beg, clr_end = 0, slen
else:
clr_beg, clr_end = clr
print(frgTemplate.format(fragID=fragID, libID=libID,
seq=seq, qvs=qvs, clr_beg=clr_beg, clr_end=clr_end), file=fw) | [
"def",
"emitFragment",
"(",
"fw",
",",
"fragID",
",",
"libID",
",",
"shredded_seq",
",",
"clr",
"=",
"None",
",",
"qvchar",
"=",
"'l'",
",",
"fasta",
"=",
"False",
")",
":",
"if",
"fasta",
":",
"s",
"=",
"SeqRecord",
"(",
"shredded_seq",
",",
"id",
... | Print out the shredded sequence. | [
"Print",
"out",
"the",
"shredded",
"sequence",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/ca.py#L693-L712 | train | 200,824 |
tanghaibao/jcvi | jcvi/assembly/ca.py | make_matepairs | def make_matepairs(fastafile):
"""
Assumes the mates are adjacent sequence records
"""
assert op.exists(fastafile)
matefile = fastafile.rsplit(".", 1)[0] + ".mates"
if op.exists(matefile):
logging.debug("matepairs file `{0}` found".format(matefile))
else:
logging.debug("parsing matepairs from `{0}`".format(fastafile))
matefw = open(matefile, "w")
it = SeqIO.parse(fastafile, "fasta")
for fwd, rev in zip(it, it):
print("{0}\t{1}".format(fwd.id, rev.id), file=matefw)
matefw.close()
return matefile | python | def make_matepairs(fastafile):
"""
Assumes the mates are adjacent sequence records
"""
assert op.exists(fastafile)
matefile = fastafile.rsplit(".", 1)[0] + ".mates"
if op.exists(matefile):
logging.debug("matepairs file `{0}` found".format(matefile))
else:
logging.debug("parsing matepairs from `{0}`".format(fastafile))
matefw = open(matefile, "w")
it = SeqIO.parse(fastafile, "fasta")
for fwd, rev in zip(it, it):
print("{0}\t{1}".format(fwd.id, rev.id), file=matefw)
matefw.close()
return matefile | [
"def",
"make_matepairs",
"(",
"fastafile",
")",
":",
"assert",
"op",
".",
"exists",
"(",
"fastafile",
")",
"matefile",
"=",
"fastafile",
".",
"rsplit",
"(",
"\".\"",
",",
"1",
")",
"[",
"0",
"]",
"+",
"\".mates\"",
"if",
"op",
".",
"exists",
"(",
"ma... | Assumes the mates are adjacent sequence records | [
"Assumes",
"the",
"mates",
"are",
"adjacent",
"sequence",
"records"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/ca.py#L845-L863 | train | 200,825 |
tanghaibao/jcvi | jcvi/assembly/ca.py | sff | def sff(args):
"""
%prog sff sffiles
Convert reads formatted as 454 SFF file, and convert to CA frg file.
Turn --nodedup on if another deduplication mechanism is used (e.g.
CD-HIT-454). See assembly.sff.deduplicate().
"""
p = OptionParser(sff.__doc__)
p.add_option("--prefix", dest="prefix", default=None,
help="Output frg filename prefix")
p.add_option("--nodedup", default=False, action="store_true",
help="Do not remove duplicates [default: %default]")
p.set_size()
opts, args = p.parse_args(args)
if len(args) < 1:
sys.exit(p.print_help())
sffiles = args
plates = [x.split(".")[0].split("_")[-1] for x in sffiles]
mated = (opts.size != 0)
mean, sv = get_mean_sv(opts.size)
if len(plates) > 1:
plate = plates[0][:-1] + 'X'
else:
plate = "_".join(plates)
if mated:
libname = "Titan{0}Kb-".format(opts.size / 1000) + plate
else:
libname = "TitanFrags-" + plate
if opts.prefix:
libname = opts.prefix
cmd = "sffToCA"
cmd += " -libraryname {0} -output {0} ".format(libname)
cmd += " -clear 454 -trim chop "
if mated:
cmd += " -linker titanium -insertsize {0} {1} ".format(mean, sv)
if opts.nodedup:
cmd += " -nodedup "
cmd += " ".join(sffiles)
sh(cmd) | python | def sff(args):
"""
%prog sff sffiles
Convert reads formatted as 454 SFF file, and convert to CA frg file.
Turn --nodedup on if another deduplication mechanism is used (e.g.
CD-HIT-454). See assembly.sff.deduplicate().
"""
p = OptionParser(sff.__doc__)
p.add_option("--prefix", dest="prefix", default=None,
help="Output frg filename prefix")
p.add_option("--nodedup", default=False, action="store_true",
help="Do not remove duplicates [default: %default]")
p.set_size()
opts, args = p.parse_args(args)
if len(args) < 1:
sys.exit(p.print_help())
sffiles = args
plates = [x.split(".")[0].split("_")[-1] for x in sffiles]
mated = (opts.size != 0)
mean, sv = get_mean_sv(opts.size)
if len(plates) > 1:
plate = plates[0][:-1] + 'X'
else:
plate = "_".join(plates)
if mated:
libname = "Titan{0}Kb-".format(opts.size / 1000) + plate
else:
libname = "TitanFrags-" + plate
if opts.prefix:
libname = opts.prefix
cmd = "sffToCA"
cmd += " -libraryname {0} -output {0} ".format(libname)
cmd += " -clear 454 -trim chop "
if mated:
cmd += " -linker titanium -insertsize {0} {1} ".format(mean, sv)
if opts.nodedup:
cmd += " -nodedup "
cmd += " ".join(sffiles)
sh(cmd) | [
"def",
"sff",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"sff",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--prefix\"",
",",
"dest",
"=",
"\"prefix\"",
",",
"default",
"=",
"None",
",",
"help",
"=",
"\"Output frg filename prefix\"",
... | %prog sff sffiles
Convert reads formatted as 454 SFF file, and convert to CA frg file.
Turn --nodedup on if another deduplication mechanism is used (e.g.
CD-HIT-454). See assembly.sff.deduplicate(). | [
"%prog",
"sff",
"sffiles"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/ca.py#L983-L1031 | train | 200,826 |
tanghaibao/jcvi | jcvi/assembly/ca.py | fastq | def fastq(args):
"""
%prog fastq fastqfile
Convert reads formatted as FASTQ file, and convert to CA frg file.
"""
from jcvi.formats.fastq import guessoffset
p = OptionParser(fastq.__doc__)
p.add_option("--outtie", dest="outtie", default=False, action="store_true",
help="Are these outie reads? [default: %default]")
p.set_phred()
p.set_size()
opts, args = p.parse_args(args)
if len(args) < 1:
sys.exit(p.print_help())
fastqfiles = [get_abs_path(x) for x in args]
size = opts.size
outtie = opts.outtie
if size > 1000 and (not outtie):
logging.debug("[warn] long insert size {0} but not outtie".format(size))
mated = (size != 0)
libname = op.basename(args[0]).split(".")[0]
libname = libname.replace("_1_sequence", "")
frgfile = libname + ".frg"
mean, sv = get_mean_sv(opts.size)
cmd = "fastqToCA"
cmd += " -libraryname {0} ".format(libname)
fastqs = " ".join("-reads {0}".format(x) for x in fastqfiles)
if mated:
assert len(args) in (1, 2), "you need one or two fastq files for mated library"
fastqs = "-mates {0}".format(",".join(fastqfiles))
cmd += "-insertsize {0} {1} ".format(mean, sv)
cmd += fastqs
offset = int(opts.phred) if opts.phred else guessoffset([fastqfiles[0]])
illumina = (offset == 64)
if illumina:
cmd += " -type illumina"
if outtie:
cmd += " -outtie"
sh(cmd, outfile=frgfile) | python | def fastq(args):
"""
%prog fastq fastqfile
Convert reads formatted as FASTQ file, and convert to CA frg file.
"""
from jcvi.formats.fastq import guessoffset
p = OptionParser(fastq.__doc__)
p.add_option("--outtie", dest="outtie", default=False, action="store_true",
help="Are these outie reads? [default: %default]")
p.set_phred()
p.set_size()
opts, args = p.parse_args(args)
if len(args) < 1:
sys.exit(p.print_help())
fastqfiles = [get_abs_path(x) for x in args]
size = opts.size
outtie = opts.outtie
if size > 1000 and (not outtie):
logging.debug("[warn] long insert size {0} but not outtie".format(size))
mated = (size != 0)
libname = op.basename(args[0]).split(".")[0]
libname = libname.replace("_1_sequence", "")
frgfile = libname + ".frg"
mean, sv = get_mean_sv(opts.size)
cmd = "fastqToCA"
cmd += " -libraryname {0} ".format(libname)
fastqs = " ".join("-reads {0}".format(x) for x in fastqfiles)
if mated:
assert len(args) in (1, 2), "you need one or two fastq files for mated library"
fastqs = "-mates {0}".format(",".join(fastqfiles))
cmd += "-insertsize {0} {1} ".format(mean, sv)
cmd += fastqs
offset = int(opts.phred) if opts.phred else guessoffset([fastqfiles[0]])
illumina = (offset == 64)
if illumina:
cmd += " -type illumina"
if outtie:
cmd += " -outtie"
sh(cmd, outfile=frgfile) | [
"def",
"fastq",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"fastq",
"import",
"guessoffset",
"p",
"=",
"OptionParser",
"(",
"fastq",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--outtie\"",
",",
"dest",
"=",
"\"outtie\"",
",",
... | %prog fastq fastqfile
Convert reads formatted as FASTQ file, and convert to CA frg file. | [
"%prog",
"fastq",
"fastqfile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/ca.py#L1034-L1082 | train | 200,827 |
tanghaibao/jcvi | jcvi/assembly/ca.py | clr | def clr(args):
"""
%prog blastfile fastafiles
Calculate the vector clear range file based BLAST to the vectors.
"""
p = OptionParser(clr.__doc__)
opts, args = p.parse_args(args)
if len(args) < 2:
sys.exit(not p.print_help())
blastfile = args[0]
fastafiles = args[1:]
sizes = {}
for fa in fastafiles:
f = Fasta(fa)
sizes.update(f.itersizes())
b = Blast(blastfile)
for query, hits in b.iter_hits():
qsize = sizes[query]
vectors = list((x.qstart, x.qstop) for x in hits)
vmin, vmax = range_minmax(vectors)
left_size = vmin - 1
right_size = qsize - vmax
if left_size > right_size:
clr_start, clr_end = 0, vmin
else:
clr_start, clr_end = vmax, qsize
print("\t".join(str(x) for x in (query, clr_start, clr_end)))
del sizes[query]
for q, size in sorted(sizes.items()):
print("\t".join(str(x) for x in (q, 0, size))) | python | def clr(args):
"""
%prog blastfile fastafiles
Calculate the vector clear range file based BLAST to the vectors.
"""
p = OptionParser(clr.__doc__)
opts, args = p.parse_args(args)
if len(args) < 2:
sys.exit(not p.print_help())
blastfile = args[0]
fastafiles = args[1:]
sizes = {}
for fa in fastafiles:
f = Fasta(fa)
sizes.update(f.itersizes())
b = Blast(blastfile)
for query, hits in b.iter_hits():
qsize = sizes[query]
vectors = list((x.qstart, x.qstop) for x in hits)
vmin, vmax = range_minmax(vectors)
left_size = vmin - 1
right_size = qsize - vmax
if left_size > right_size:
clr_start, clr_end = 0, vmin
else:
clr_start, clr_end = vmax, qsize
print("\t".join(str(x) for x in (query, clr_start, clr_end)))
del sizes[query]
for q, size in sorted(sizes.items()):
print("\t".join(str(x) for x in (q, 0, size))) | [
"def",
"clr",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"clr",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"<",
"2",
":",
"sys",
".",
"exit",
"(",
"not",
... | %prog blastfile fastafiles
Calculate the vector clear range file based BLAST to the vectors. | [
"%prog",
"blastfile",
"fastafiles"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/ca.py#L1085-L1124 | train | 200,828 |
tanghaibao/jcvi | jcvi/graphics/tree.py | truncate_name | def truncate_name(name, rule=None):
"""
shorten taxa names for tree display
Options of rule. This only affects tree display.
- headn (eg. head3 truncates first 3 chars)
- oheadn (eg. ohead3 retains only the first 3 chars)
- tailn (eg. tail3 truncates last 3 chars)
- otailn (eg. otail3 retains only the last 3 chars)
n = 1 ~ 99
"""
import re
if rule is None:
return name
k = re.search("(?<=^head)[0-9]{1,2}$", rule)
if k:
k = k.group(0)
tname = name[int(k):]
else:
k = re.search("(?<=^ohead)[0-9]{1,2}$", rule)
if k:
k = k.group(0)
tname = name[:int(k)]
else:
k = re.search("(?<=^tail)[0-9]{1,2}$", rule)
if k:
k = k.group(0)
tname = name[:-int(k)]
else:
k = re.search("(?<=^otail)[0-9]{1,2}$", rule)
if k:
k = k.group(0)
tname = name[-int(k):]
else:
print(truncate_name.__doc__, file=sys.stderr)
raise ValueError('Wrong rule for truncation!')
return tname | python | def truncate_name(name, rule=None):
"""
shorten taxa names for tree display
Options of rule. This only affects tree display.
- headn (eg. head3 truncates first 3 chars)
- oheadn (eg. ohead3 retains only the first 3 chars)
- tailn (eg. tail3 truncates last 3 chars)
- otailn (eg. otail3 retains only the last 3 chars)
n = 1 ~ 99
"""
import re
if rule is None:
return name
k = re.search("(?<=^head)[0-9]{1,2}$", rule)
if k:
k = k.group(0)
tname = name[int(k):]
else:
k = re.search("(?<=^ohead)[0-9]{1,2}$", rule)
if k:
k = k.group(0)
tname = name[:int(k)]
else:
k = re.search("(?<=^tail)[0-9]{1,2}$", rule)
if k:
k = k.group(0)
tname = name[:-int(k)]
else:
k = re.search("(?<=^otail)[0-9]{1,2}$", rule)
if k:
k = k.group(0)
tname = name[-int(k):]
else:
print(truncate_name.__doc__, file=sys.stderr)
raise ValueError('Wrong rule for truncation!')
return tname | [
"def",
"truncate_name",
"(",
"name",
",",
"rule",
"=",
"None",
")",
":",
"import",
"re",
"if",
"rule",
"is",
"None",
":",
"return",
"name",
"k",
"=",
"re",
".",
"search",
"(",
"\"(?<=^head)[0-9]{1,2}$\"",
",",
"rule",
")",
"if",
"k",
":",
"k",
"=",
... | shorten taxa names for tree display
Options of rule. This only affects tree display.
- headn (eg. head3 truncates first 3 chars)
- oheadn (eg. ohead3 retains only the first 3 chars)
- tailn (eg. tail3 truncates last 3 chars)
- otailn (eg. otail3 retains only the last 3 chars)
n = 1 ~ 99 | [
"shorten",
"taxa",
"names",
"for",
"tree",
"display"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/graphics/tree.py#L18-L56 | train | 200,829 |
tanghaibao/jcvi | jcvi/apps/phylo.py | run_treefix | def run_treefix(input, stree_file, smap_file, a_ext=".fasta", \
o_ext=".dnd", n_ext = ".treefix.dnd", **kwargs):
"""
get the ML tree closest to the species tree
"""
cl = TreeFixCommandline(input=input, \
stree_file=stree_file, smap_file=smap_file, a_ext=a_ext, \
o=o_ext, n=n_ext, **kwargs)
outtreefile = input.rsplit(o_ext, 1)[0] + n_ext
print("TreeFix:", cl, file=sys.stderr)
r, e = cl.run()
if e:
print("***TreeFix could not run", file=sys.stderr)
return None
else:
logging.debug("new tree written to {0}".format(outtreefile))
return outtreefile | python | def run_treefix(input, stree_file, smap_file, a_ext=".fasta", \
o_ext=".dnd", n_ext = ".treefix.dnd", **kwargs):
"""
get the ML tree closest to the species tree
"""
cl = TreeFixCommandline(input=input, \
stree_file=stree_file, smap_file=smap_file, a_ext=a_ext, \
o=o_ext, n=n_ext, **kwargs)
outtreefile = input.rsplit(o_ext, 1)[0] + n_ext
print("TreeFix:", cl, file=sys.stderr)
r, e = cl.run()
if e:
print("***TreeFix could not run", file=sys.stderr)
return None
else:
logging.debug("new tree written to {0}".format(outtreefile))
return outtreefile | [
"def",
"run_treefix",
"(",
"input",
",",
"stree_file",
",",
"smap_file",
",",
"a_ext",
"=",
"\".fasta\"",
",",
"o_ext",
"=",
"\".dnd\"",
",",
"n_ext",
"=",
"\".treefix.dnd\"",
",",
"*",
"*",
"kwargs",
")",
":",
"cl",
"=",
"TreeFixCommandline",
"(",
"input"... | get the ML tree closest to the species tree | [
"get",
"the",
"ML",
"tree",
"closest",
"to",
"the",
"species",
"tree"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/phylo.py#L132-L149 | train | 200,830 |
tanghaibao/jcvi | jcvi/apps/phylo.py | run_gblocks | def run_gblocks(align_fasta_file, **kwargs):
"""
remove poorly aligned positions and divergent regions with Gblocks
"""
cl = GblocksCommandline(aln_file=align_fasta_file, **kwargs)
r, e = cl.run()
print("Gblocks:", cl, file=sys.stderr)
if e:
print("***Gblocks could not run", file=sys.stderr)
return None
else:
print(r, file=sys.stderr)
alignp = re.sub(r'.*Gblocks alignment:.*\(([0-9]{1,3}) %\).*', \
r'\1', r, flags=re.DOTALL)
alignp = int(alignp)
if alignp <= 10:
print("** WARNING ** Only %s %% positions retained by Gblocks. " \
"Results aborted. Using original alignment instead.\n" % alignp, file=sys.stderr)
return None
else:
return align_fasta_file+"-gb" | python | def run_gblocks(align_fasta_file, **kwargs):
"""
remove poorly aligned positions and divergent regions with Gblocks
"""
cl = GblocksCommandline(aln_file=align_fasta_file, **kwargs)
r, e = cl.run()
print("Gblocks:", cl, file=sys.stderr)
if e:
print("***Gblocks could not run", file=sys.stderr)
return None
else:
print(r, file=sys.stderr)
alignp = re.sub(r'.*Gblocks alignment:.*\(([0-9]{1,3}) %\).*', \
r'\1', r, flags=re.DOTALL)
alignp = int(alignp)
if alignp <= 10:
print("** WARNING ** Only %s %% positions retained by Gblocks. " \
"Results aborted. Using original alignment instead.\n" % alignp, file=sys.stderr)
return None
else:
return align_fasta_file+"-gb" | [
"def",
"run_gblocks",
"(",
"align_fasta_file",
",",
"*",
"*",
"kwargs",
")",
":",
"cl",
"=",
"GblocksCommandline",
"(",
"aln_file",
"=",
"align_fasta_file",
",",
"*",
"*",
"kwargs",
")",
"r",
",",
"e",
"=",
"cl",
".",
"run",
"(",
")",
"print",
"(",
"... | remove poorly aligned positions and divergent regions with Gblocks | [
"remove",
"poorly",
"aligned",
"positions",
"and",
"divergent",
"regions",
"with",
"Gblocks"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/phylo.py#L152-L174 | train | 200,831 |
tanghaibao/jcvi | jcvi/apps/phylo.py | run_ffitch | def run_ffitch(distfile, outtreefile, intreefile=None, **kwargs):
"""
Infer tree branch lengths using ffitch in EMBOSS PHYLIP
"""
cl = FfitchCommandline(datafile=distfile, outtreefile=outtreefile, \
intreefile=intreefile, **kwargs)
r, e = cl.run()
if e:
print("***ffitch could not run", file=sys.stderr)
return None
else:
print("ffitch:", cl, file=sys.stderr)
return outtreefile | python | def run_ffitch(distfile, outtreefile, intreefile=None, **kwargs):
"""
Infer tree branch lengths using ffitch in EMBOSS PHYLIP
"""
cl = FfitchCommandline(datafile=distfile, outtreefile=outtreefile, \
intreefile=intreefile, **kwargs)
r, e = cl.run()
if e:
print("***ffitch could not run", file=sys.stderr)
return None
else:
print("ffitch:", cl, file=sys.stderr)
return outtreefile | [
"def",
"run_ffitch",
"(",
"distfile",
",",
"outtreefile",
",",
"intreefile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"cl",
"=",
"FfitchCommandline",
"(",
"datafile",
"=",
"distfile",
",",
"outtreefile",
"=",
"outtreefile",
",",
"intreefile",
"=",
"... | Infer tree branch lengths using ffitch in EMBOSS PHYLIP | [
"Infer",
"tree",
"branch",
"lengths",
"using",
"ffitch",
"in",
"EMBOSS",
"PHYLIP"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/phylo.py#L177-L190 | train | 200,832 |
tanghaibao/jcvi | jcvi/apps/phylo.py | smart_reroot | def smart_reroot(treefile, outgroupfile, outfile, format=0):
"""
simple function to reroot Newick format tree using ete2
Tree reading format options see here:
http://packages.python.org/ete2/tutorial/tutorial_trees.html#reading-newick-trees
"""
tree = Tree(treefile, format=format)
leaves = [t.name for t in tree.get_leaves()][::-1]
outgroup = []
for o in must_open(outgroupfile):
o = o.strip()
for leaf in leaves:
if leaf[:len(o)] == o:
outgroup.append(leaf)
if outgroup:
break
if not outgroup:
print("Outgroup not found. Tree {0} cannot be rerooted.".format(treefile), file=sys.stderr)
return treefile
try:
tree.set_outgroup(tree.get_common_ancestor(*outgroup))
except ValueError:
assert type(outgroup) == list
outgroup = outgroup[0]
tree.set_outgroup(outgroup)
tree.write(outfile=outfile, format=format)
logging.debug("Rerooted tree printed to {0}".format(outfile))
return outfile | python | def smart_reroot(treefile, outgroupfile, outfile, format=0):
"""
simple function to reroot Newick format tree using ete2
Tree reading format options see here:
http://packages.python.org/ete2/tutorial/tutorial_trees.html#reading-newick-trees
"""
tree = Tree(treefile, format=format)
leaves = [t.name for t in tree.get_leaves()][::-1]
outgroup = []
for o in must_open(outgroupfile):
o = o.strip()
for leaf in leaves:
if leaf[:len(o)] == o:
outgroup.append(leaf)
if outgroup:
break
if not outgroup:
print("Outgroup not found. Tree {0} cannot be rerooted.".format(treefile), file=sys.stderr)
return treefile
try:
tree.set_outgroup(tree.get_common_ancestor(*outgroup))
except ValueError:
assert type(outgroup) == list
outgroup = outgroup[0]
tree.set_outgroup(outgroup)
tree.write(outfile=outfile, format=format)
logging.debug("Rerooted tree printed to {0}".format(outfile))
return outfile | [
"def",
"smart_reroot",
"(",
"treefile",
",",
"outgroupfile",
",",
"outfile",
",",
"format",
"=",
"0",
")",
":",
"tree",
"=",
"Tree",
"(",
"treefile",
",",
"format",
"=",
"format",
")",
"leaves",
"=",
"[",
"t",
".",
"name",
"for",
"t",
"in",
"tree",
... | simple function to reroot Newick format tree using ete2
Tree reading format options see here:
http://packages.python.org/ete2/tutorial/tutorial_trees.html#reading-newick-trees | [
"simple",
"function",
"to",
"reroot",
"Newick",
"format",
"tree",
"using",
"ete2"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/phylo.py#L193-L224 | train | 200,833 |
tanghaibao/jcvi | jcvi/apps/phylo.py | build_ml_phyml | def build_ml_phyml(alignment, outfile, work_dir=".", **kwargs):
"""
build maximum likelihood tree of DNA seqs with PhyML
"""
phy_file = op.join(work_dir, "work", "aln.phy")
AlignIO.write(alignment, file(phy_file, "w"), "phylip-relaxed")
phyml_cl = PhymlCommandline(cmd=PHYML_BIN("phyml"), input=phy_file, **kwargs)
logging.debug("Building ML tree using PhyML: %s" % phyml_cl)
stdout, stderr = phyml_cl()
tree_file = phy_file + "_phyml_tree.txt"
if not op.exists(tree_file):
print("***PhyML failed.", file=sys.stderr)
return None
sh("cp {0} {1}".format(tree_file, outfile), log=False)
logging.debug("ML tree printed to %s" % outfile)
return outfile, phy_file | python | def build_ml_phyml(alignment, outfile, work_dir=".", **kwargs):
"""
build maximum likelihood tree of DNA seqs with PhyML
"""
phy_file = op.join(work_dir, "work", "aln.phy")
AlignIO.write(alignment, file(phy_file, "w"), "phylip-relaxed")
phyml_cl = PhymlCommandline(cmd=PHYML_BIN("phyml"), input=phy_file, **kwargs)
logging.debug("Building ML tree using PhyML: %s" % phyml_cl)
stdout, stderr = phyml_cl()
tree_file = phy_file + "_phyml_tree.txt"
if not op.exists(tree_file):
print("***PhyML failed.", file=sys.stderr)
return None
sh("cp {0} {1}".format(tree_file, outfile), log=False)
logging.debug("ML tree printed to %s" % outfile)
return outfile, phy_file | [
"def",
"build_ml_phyml",
"(",
"alignment",
",",
"outfile",
",",
"work_dir",
"=",
"\".\"",
",",
"*",
"*",
"kwargs",
")",
":",
"phy_file",
"=",
"op",
".",
"join",
"(",
"work_dir",
",",
"\"work\"",
",",
"\"aln.phy\"",
")",
"AlignIO",
".",
"write",
"(",
"a... | build maximum likelihood tree of DNA seqs with PhyML | [
"build",
"maximum",
"likelihood",
"tree",
"of",
"DNA",
"seqs",
"with",
"PhyML"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/phylo.py#L318-L337 | train | 200,834 |
tanghaibao/jcvi | jcvi/apps/phylo.py | build_ml_raxml | def build_ml_raxml(alignment, outfile, work_dir=".", **kwargs):
"""
build maximum likelihood tree of DNA seqs with RAxML
"""
work_dir = op.join(work_dir, "work")
mkdir(work_dir)
phy_file = op.join(work_dir, "aln.phy")
AlignIO.write(alignment, file(phy_file, "w"), "phylip-relaxed")
raxml_work = op.abspath(op.join(op.dirname(phy_file), "raxml_work"))
mkdir(raxml_work)
raxml_cl = RaxmlCommandline(cmd=RAXML_BIN("raxmlHPC"), \
sequences=phy_file, algorithm="a", model="GTRGAMMA", \
parsimony_seed=12345, rapid_bootstrap_seed=12345, \
num_replicates=100, name="aln", \
working_dir=raxml_work, **kwargs)
logging.debug("Building ML tree using RAxML: %s" % raxml_cl)
stdout, stderr = raxml_cl()
tree_file = "{0}/RAxML_bipartitions.aln".format(raxml_work)
if not op.exists(tree_file):
print("***RAxML failed.", file=sys.stderr)
sh("rm -rf %s" % raxml_work, log=False)
return None
sh("cp {0} {1}".format(tree_file, outfile), log=False)
logging.debug("ML tree printed to %s" % outfile)
sh("rm -rf %s" % raxml_work)
return outfile, phy_file | python | def build_ml_raxml(alignment, outfile, work_dir=".", **kwargs):
"""
build maximum likelihood tree of DNA seqs with RAxML
"""
work_dir = op.join(work_dir, "work")
mkdir(work_dir)
phy_file = op.join(work_dir, "aln.phy")
AlignIO.write(alignment, file(phy_file, "w"), "phylip-relaxed")
raxml_work = op.abspath(op.join(op.dirname(phy_file), "raxml_work"))
mkdir(raxml_work)
raxml_cl = RaxmlCommandline(cmd=RAXML_BIN("raxmlHPC"), \
sequences=phy_file, algorithm="a", model="GTRGAMMA", \
parsimony_seed=12345, rapid_bootstrap_seed=12345, \
num_replicates=100, name="aln", \
working_dir=raxml_work, **kwargs)
logging.debug("Building ML tree using RAxML: %s" % raxml_cl)
stdout, stderr = raxml_cl()
tree_file = "{0}/RAxML_bipartitions.aln".format(raxml_work)
if not op.exists(tree_file):
print("***RAxML failed.", file=sys.stderr)
sh("rm -rf %s" % raxml_work, log=False)
return None
sh("cp {0} {1}".format(tree_file, outfile), log=False)
logging.debug("ML tree printed to %s" % outfile)
sh("rm -rf %s" % raxml_work)
return outfile, phy_file | [
"def",
"build_ml_raxml",
"(",
"alignment",
",",
"outfile",
",",
"work_dir",
"=",
"\".\"",
",",
"*",
"*",
"kwargs",
")",
":",
"work_dir",
"=",
"op",
".",
"join",
"(",
"work_dir",
",",
"\"work\"",
")",
"mkdir",
"(",
"work_dir",
")",
"phy_file",
"=",
"op"... | build maximum likelihood tree of DNA seqs with RAxML | [
"build",
"maximum",
"likelihood",
"tree",
"of",
"DNA",
"seqs",
"with",
"RAxML"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/phylo.py#L340-L370 | train | 200,835 |
tanghaibao/jcvi | jcvi/apps/phylo.py | SH_raxml | def SH_raxml(reftree, querytree, phy_file, shout="SH_out.txt"):
"""
SH test using RAxML
querytree can be a single tree or a bunch of trees (eg. from bootstrapping)
"""
assert op.isfile(reftree)
shout = must_open(shout, "a")
raxml_work = op.abspath(op.join(op.dirname(phy_file), "raxml_work"))
mkdir(raxml_work)
raxml_cl = RaxmlCommandline(cmd=RAXML_BIN("raxmlHPC"), \
sequences=phy_file, algorithm="h", model="GTRGAMMA", \
name="SH", starting_tree=reftree, bipartition_filename=querytree, \
working_dir=raxml_work)
logging.debug("Running SH test in RAxML: %s" % raxml_cl)
o, stderr = raxml_cl()
# hard coded
try:
pval = re.search('(Significantly.*:.*)', o).group(0)
except:
print("SH test failed.", file=sys.stderr)
else:
pval = pval.strip().replace("\t"," ").replace("%","\%")
print("{0}\t{1}".format(op.basename(querytree), pval), file=shout)
logging.debug("SH p-value appended to %s" % shout.name)
shout.close()
return shout.name | python | def SH_raxml(reftree, querytree, phy_file, shout="SH_out.txt"):
"""
SH test using RAxML
querytree can be a single tree or a bunch of trees (eg. from bootstrapping)
"""
assert op.isfile(reftree)
shout = must_open(shout, "a")
raxml_work = op.abspath(op.join(op.dirname(phy_file), "raxml_work"))
mkdir(raxml_work)
raxml_cl = RaxmlCommandline(cmd=RAXML_BIN("raxmlHPC"), \
sequences=phy_file, algorithm="h", model="GTRGAMMA", \
name="SH", starting_tree=reftree, bipartition_filename=querytree, \
working_dir=raxml_work)
logging.debug("Running SH test in RAxML: %s" % raxml_cl)
o, stderr = raxml_cl()
# hard coded
try:
pval = re.search('(Significantly.*:.*)', o).group(0)
except:
print("SH test failed.", file=sys.stderr)
else:
pval = pval.strip().replace("\t"," ").replace("%","\%")
print("{0}\t{1}".format(op.basename(querytree), pval), file=shout)
logging.debug("SH p-value appended to %s" % shout.name)
shout.close()
return shout.name | [
"def",
"SH_raxml",
"(",
"reftree",
",",
"querytree",
",",
"phy_file",
",",
"shout",
"=",
"\"SH_out.txt\"",
")",
":",
"assert",
"op",
".",
"isfile",
"(",
"reftree",
")",
"shout",
"=",
"must_open",
"(",
"shout",
",",
"\"a\"",
")",
"raxml_work",
"=",
"op",
... | SH test using RAxML
querytree can be a single tree or a bunch of trees (eg. from bootstrapping) | [
"SH",
"test",
"using",
"RAxML"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/phylo.py#L373-L402 | train | 200,836 |
tanghaibao/jcvi | jcvi/apps/phylo.py | subalignment | def subalignment(alnfle, subtype, alntype="fasta"):
"""
Subset synonymous or fourfold degenerate sites from an alignment
input should be a codon alignment
"""
aln = AlignIO.read(alnfle, alntype)
alnlen = aln.get_alignment_length()
nseq = len(aln)
subaln = None
subalnfile = alnfle.rsplit(".", 1)[0] + "_{0}.{1}".format(subtype, alntype)
if subtype == "synonymous":
for j in range( 0, alnlen, 3 ):
aa = None
for i in range(nseq):
codon = str(aln[i, j: j + 3].seq)
if codon not in CODON_TRANSLATION:
break
if aa and CODON_TRANSLATION[codon] != aa:
break
else:
aa = CODON_TRANSLATION[codon]
else:
if subaln is None:
subaln = aln[:, j: j + 3]
else:
subaln += aln[:, j: j + 3]
if subtype == "fourfold":
for j in range( 0, alnlen, 3 ):
for i in range(nseq):
codon = str(aln[i, j: j + 3].seq)
if codon not in FOURFOLD:
break
else:
if subaln is None:
subaln = aln[:, j: j + 3]
else:
subaln += aln[:, j: j + 3]
if subaln:
AlignIO.write(subaln, subalnfile, alntype)
return subalnfile
else:
print("No sites {0} selected.".format(subtype), file=sys.stderr)
return None | python | def subalignment(alnfle, subtype, alntype="fasta"):
"""
Subset synonymous or fourfold degenerate sites from an alignment
input should be a codon alignment
"""
aln = AlignIO.read(alnfle, alntype)
alnlen = aln.get_alignment_length()
nseq = len(aln)
subaln = None
subalnfile = alnfle.rsplit(".", 1)[0] + "_{0}.{1}".format(subtype, alntype)
if subtype == "synonymous":
for j in range( 0, alnlen, 3 ):
aa = None
for i in range(nseq):
codon = str(aln[i, j: j + 3].seq)
if codon not in CODON_TRANSLATION:
break
if aa and CODON_TRANSLATION[codon] != aa:
break
else:
aa = CODON_TRANSLATION[codon]
else:
if subaln is None:
subaln = aln[:, j: j + 3]
else:
subaln += aln[:, j: j + 3]
if subtype == "fourfold":
for j in range( 0, alnlen, 3 ):
for i in range(nseq):
codon = str(aln[i, j: j + 3].seq)
if codon not in FOURFOLD:
break
else:
if subaln is None:
subaln = aln[:, j: j + 3]
else:
subaln += aln[:, j: j + 3]
if subaln:
AlignIO.write(subaln, subalnfile, alntype)
return subalnfile
else:
print("No sites {0} selected.".format(subtype), file=sys.stderr)
return None | [
"def",
"subalignment",
"(",
"alnfle",
",",
"subtype",
",",
"alntype",
"=",
"\"fasta\"",
")",
":",
"aln",
"=",
"AlignIO",
".",
"read",
"(",
"alnfle",
",",
"alntype",
")",
"alnlen",
"=",
"aln",
".",
"get_alignment_length",
"(",
")",
"nseq",
"=",
"len",
"... | Subset synonymous or fourfold degenerate sites from an alignment
input should be a codon alignment | [
"Subset",
"synonymous",
"or",
"fourfold",
"degenerate",
"sites",
"from",
"an",
"alignment"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/phylo.py#L414-L460 | train | 200,837 |
tanghaibao/jcvi | jcvi/apps/phylo.py | merge_rows_local | def merge_rows_local(filename, ignore=".", colsep="\t", local=10, \
fieldcheck=True, fsep=","):
"""
merge overlapping rows within given row count distance
"""
fw = must_open(filename+".merged", "w")
rows = file(filename).readlines()
rows = [row.strip().split(colsep) for row in rows]
l = len(rows[0])
for rowi, row in enumerate(rows):
n = len(rows)
i = rowi+1
while i <= min(rowi+local, n-1):
merge = 1
row2 = rows[i]
for j in range(l):
a = row[j]
b = row2[j]
if fieldcheck:
a = set(a.split(fsep))
a = fsep.join(sorted(list(a)))
b = set(b.split(fsep))
b = fsep.join(sorted(list(b)))
if all([a!=ignore, b!=ignore, a not in b, b not in a]):
merge = 0
i += 1
break
if merge:
for x in range(l):
if row[x] == ignore:
rows[rowi][x] = row2[x]
elif row[x] in row2[x]:
rows[rowi][x] = row2[x]
else:
rows[rowi][x] = row[x]
row = rows[rowi]
rows.remove(row2)
print(colsep.join(row), file=fw)
fw.close()
return fw.name | python | def merge_rows_local(filename, ignore=".", colsep="\t", local=10, \
fieldcheck=True, fsep=","):
"""
merge overlapping rows within given row count distance
"""
fw = must_open(filename+".merged", "w")
rows = file(filename).readlines()
rows = [row.strip().split(colsep) for row in rows]
l = len(rows[0])
for rowi, row in enumerate(rows):
n = len(rows)
i = rowi+1
while i <= min(rowi+local, n-1):
merge = 1
row2 = rows[i]
for j in range(l):
a = row[j]
b = row2[j]
if fieldcheck:
a = set(a.split(fsep))
a = fsep.join(sorted(list(a)))
b = set(b.split(fsep))
b = fsep.join(sorted(list(b)))
if all([a!=ignore, b!=ignore, a not in b, b not in a]):
merge = 0
i += 1
break
if merge:
for x in range(l):
if row[x] == ignore:
rows[rowi][x] = row2[x]
elif row[x] in row2[x]:
rows[rowi][x] = row2[x]
else:
rows[rowi][x] = row[x]
row = rows[rowi]
rows.remove(row2)
print(colsep.join(row), file=fw)
fw.close()
return fw.name | [
"def",
"merge_rows_local",
"(",
"filename",
",",
"ignore",
"=",
"\".\"",
",",
"colsep",
"=",
"\"\\t\"",
",",
"local",
"=",
"10",
",",
"fieldcheck",
"=",
"True",
",",
"fsep",
"=",
"\",\"",
")",
":",
"fw",
"=",
"must_open",
"(",
"filename",
"+",
"\".merg... | merge overlapping rows within given row count distance | [
"merge",
"overlapping",
"rows",
"within",
"given",
"row",
"count",
"distance"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/phylo.py#L463-L507 | train | 200,838 |
tanghaibao/jcvi | jcvi/apps/phylo.py | add_tandems | def add_tandems(mcscanfile, tandemfile):
"""
add tandem genes to anchor genes in mcscan file
"""
tandems = [f.strip().split(",") for f in file(tandemfile)]
fw = must_open(mcscanfile+".withtandems", "w")
fp = must_open(mcscanfile)
seen =set()
for i, row in enumerate(fp):
if row[0] == '#':
continue
anchorslist = row.strip().split("\t")
anchors = set([a.split(",")[0] for a in anchorslist])
anchors.remove(".")
if anchors & seen == anchors:
continue
newanchors = []
for a in anchorslist:
if a == ".":
newanchors.append(a)
continue
for t in tandems:
if a in t:
newanchors.append(",".join(t))
seen.update(t)
break
else:
newanchors.append(a)
seen.add(a)
print("\t".join(newanchors), file=fw)
fw.close()
newmcscanfile = merge_rows_local(fw.name)
logging.debug("Tandems added to `{0}`. Results in `{1}`".\
format(mcscanfile, newmcscanfile))
fp.seek(0)
logging.debug("{0} rows merged to {1} rows".\
format(len(fp.readlines()), len(file(newmcscanfile).readlines())))
sh("rm %s" % fw.name)
return newmcscanfile | python | def add_tandems(mcscanfile, tandemfile):
"""
add tandem genes to anchor genes in mcscan file
"""
tandems = [f.strip().split(",") for f in file(tandemfile)]
fw = must_open(mcscanfile+".withtandems", "w")
fp = must_open(mcscanfile)
seen =set()
for i, row in enumerate(fp):
if row[0] == '#':
continue
anchorslist = row.strip().split("\t")
anchors = set([a.split(",")[0] for a in anchorslist])
anchors.remove(".")
if anchors & seen == anchors:
continue
newanchors = []
for a in anchorslist:
if a == ".":
newanchors.append(a)
continue
for t in tandems:
if a in t:
newanchors.append(",".join(t))
seen.update(t)
break
else:
newanchors.append(a)
seen.add(a)
print("\t".join(newanchors), file=fw)
fw.close()
newmcscanfile = merge_rows_local(fw.name)
logging.debug("Tandems added to `{0}`. Results in `{1}`".\
format(mcscanfile, newmcscanfile))
fp.seek(0)
logging.debug("{0} rows merged to {1} rows".\
format(len(fp.readlines()), len(file(newmcscanfile).readlines())))
sh("rm %s" % fw.name)
return newmcscanfile | [
"def",
"add_tandems",
"(",
"mcscanfile",
",",
"tandemfile",
")",
":",
"tandems",
"=",
"[",
"f",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\",\"",
")",
"for",
"f",
"in",
"file",
"(",
"tandemfile",
")",
"]",
"fw",
"=",
"must_open",
"(",
"mcscanfile",... | add tandem genes to anchor genes in mcscan file | [
"add",
"tandem",
"genes",
"to",
"anchor",
"genes",
"in",
"mcscan",
"file"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/phylo.py#L510-L552 | train | 200,839 |
tanghaibao/jcvi | jcvi/apps/phylo.py | _draw_trees | def _draw_trees(trees, nrow=1, ncol=1, rmargin=.3, iopts=None, outdir=".",
shfile=None, **kwargs):
"""
Draw one or multiple trees on one plot.
"""
from jcvi.graphics.tree import draw_tree
if shfile:
SHs = DictFile(shfile, delimiter="\t")
ntrees = len(trees)
n = nrow * ncol
for x in xrange(int(ceil(float(ntrees)/n))):
fig = plt.figure(1, (iopts.w, iopts.h)) if iopts \
else plt.figure(1, (5, 5))
root = fig.add_axes([0, 0, 1, 1])
xiv = 1. / ncol
yiv = 1. / nrow
xstart = list(np.arange(0, 1, xiv)) * nrow
ystart = list(chain(*zip(*[list(np.arange(0, 1, yiv))[::-1]] * ncol)))
for i in xrange(n*x, n*(x+1)):
if i == ntrees:
break
ax = fig.add_axes([xstart[i%n], ystart[i%n], xiv, yiv])
f = trees.keys()[i]
tree = trees[f]
try:
SH = SHs[f]
except:
SH = None
draw_tree(ax, tree, rmargin=rmargin, reroot=False, \
supportcolor="r", SH=SH, **kwargs)
root.set_xlim(0, 1)
root.set_ylim(0, 1)
root.set_axis_off()
format = iopts.format if iopts else "pdf"
dpi = iopts.dpi if iopts else 300
if n == 1:
image_name = f.rsplit(".", 1)[0] + "." + format
else:
image_name = "trees{0}.{1}".format(x, format)
image_name = op.join(outdir, image_name)
savefig(image_name, dpi=dpi, iopts=iopts)
plt.clf() | python | def _draw_trees(trees, nrow=1, ncol=1, rmargin=.3, iopts=None, outdir=".",
shfile=None, **kwargs):
"""
Draw one or multiple trees on one plot.
"""
from jcvi.graphics.tree import draw_tree
if shfile:
SHs = DictFile(shfile, delimiter="\t")
ntrees = len(trees)
n = nrow * ncol
for x in xrange(int(ceil(float(ntrees)/n))):
fig = plt.figure(1, (iopts.w, iopts.h)) if iopts \
else plt.figure(1, (5, 5))
root = fig.add_axes([0, 0, 1, 1])
xiv = 1. / ncol
yiv = 1. / nrow
xstart = list(np.arange(0, 1, xiv)) * nrow
ystart = list(chain(*zip(*[list(np.arange(0, 1, yiv))[::-1]] * ncol)))
for i in xrange(n*x, n*(x+1)):
if i == ntrees:
break
ax = fig.add_axes([xstart[i%n], ystart[i%n], xiv, yiv])
f = trees.keys()[i]
tree = trees[f]
try:
SH = SHs[f]
except:
SH = None
draw_tree(ax, tree, rmargin=rmargin, reroot=False, \
supportcolor="r", SH=SH, **kwargs)
root.set_xlim(0, 1)
root.set_ylim(0, 1)
root.set_axis_off()
format = iopts.format if iopts else "pdf"
dpi = iopts.dpi if iopts else 300
if n == 1:
image_name = f.rsplit(".", 1)[0] + "." + format
else:
image_name = "trees{0}.{1}".format(x, format)
image_name = op.join(outdir, image_name)
savefig(image_name, dpi=dpi, iopts=iopts)
plt.clf() | [
"def",
"_draw_trees",
"(",
"trees",
",",
"nrow",
"=",
"1",
",",
"ncol",
"=",
"1",
",",
"rmargin",
"=",
".3",
",",
"iopts",
"=",
"None",
",",
"outdir",
"=",
"\".\"",
",",
"shfile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"jcvi",
... | Draw one or multiple trees on one plot. | [
"Draw",
"one",
"or",
"multiple",
"trees",
"on",
"one",
"plot",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/phylo.py#L845-L891 | train | 200,840 |
tanghaibao/jcvi | jcvi/compara/catalog.py | sort_layout | def sort_layout(thread, listfile, column=0):
"""
Sort the syntelog table according to chromomomal positions. First orient the
contents against threadbed, then for contents not in threadbed, insert to
the nearest neighbor.
"""
from jcvi.formats.base import DictFile
outfile = listfile.rsplit(".", 1)[0] + ".sorted.list"
threadorder = thread.order
fw = open(outfile, "w")
lt = DictFile(listfile, keypos=column, valuepos=None)
threaded = []
imported = set()
for t in thread:
accn = t.accn
if accn not in lt:
continue
imported.add(accn)
atoms = lt[accn]
threaded.append(atoms)
assert len(threaded) == len(imported)
total = sum(1 for x in open(listfile))
logging.debug("Total: {0}, currently threaded: {1}".format(total, len(threaded)))
fp = open(listfile)
for row in fp:
atoms = row.split()
accn = atoms[0]
if accn in imported:
continue
insert_into_threaded(atoms, threaded, threadorder)
for atoms in threaded:
print("\t".join(atoms), file=fw)
fw.close()
logging.debug("File `{0}` sorted to `{1}`.".format(outfile, thread.filename)) | python | def sort_layout(thread, listfile, column=0):
"""
Sort the syntelog table according to chromomomal positions. First orient the
contents against threadbed, then for contents not in threadbed, insert to
the nearest neighbor.
"""
from jcvi.formats.base import DictFile
outfile = listfile.rsplit(".", 1)[0] + ".sorted.list"
threadorder = thread.order
fw = open(outfile, "w")
lt = DictFile(listfile, keypos=column, valuepos=None)
threaded = []
imported = set()
for t in thread:
accn = t.accn
if accn not in lt:
continue
imported.add(accn)
atoms = lt[accn]
threaded.append(atoms)
assert len(threaded) == len(imported)
total = sum(1 for x in open(listfile))
logging.debug("Total: {0}, currently threaded: {1}".format(total, len(threaded)))
fp = open(listfile)
for row in fp:
atoms = row.split()
accn = atoms[0]
if accn in imported:
continue
insert_into_threaded(atoms, threaded, threadorder)
for atoms in threaded:
print("\t".join(atoms), file=fw)
fw.close()
logging.debug("File `{0}` sorted to `{1}`.".format(outfile, thread.filename)) | [
"def",
"sort_layout",
"(",
"thread",
",",
"listfile",
",",
"column",
"=",
"0",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"base",
"import",
"DictFile",
"outfile",
"=",
"listfile",
".",
"rsplit",
"(",
"\".\"",
",",
"1",
")",
"[",
"0",
"]",
"+",
... | Sort the syntelog table according to chromomomal positions. First orient the
contents against threadbed, then for contents not in threadbed, insert to
the nearest neighbor. | [
"Sort",
"the",
"syntelog",
"table",
"according",
"to",
"chromomomal",
"positions",
".",
"First",
"orient",
"the",
"contents",
"against",
"threadbed",
"then",
"for",
"contents",
"not",
"in",
"threadbed",
"insert",
"to",
"the",
"nearest",
"neighbor",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/compara/catalog.py#L253-L292 | train | 200,841 |
tanghaibao/jcvi | jcvi/compara/catalog.py | layout | def layout(args):
"""
%prog layout omgfile taxa
Build column formatted gene lists after omgparse(). Use species list
separated by comma in place of taxa, e.g. "BR,BO,AN,CN"
"""
p = OptionParser(layout.__doc__)
p.add_option("--sort",
help="Sort layout file based on bedfile [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
omgfile, taxa = args
listfile = omgfile.rsplit(".", 1)[0] + ".list"
taxa = taxa.split(",")
ntaxa = len(taxa)
fw = open(listfile, "w")
data = []
fp = open(omgfile)
for row in fp:
genes, idxs = row.split()
row = ["."] * ntaxa
genes = genes.split(",")
ixs = [int(x) for x in idxs.split(",")]
for gene, idx in zip(genes, ixs):
row[idx] = gene
txs = ",".join(taxa[x] for x in ixs)
print("\t".join(("\t".join(row), txs)), file=fw)
data.append(row)
coldata = zip(*data)
ngenes = []
for i, tx in enumerate(taxa):
genes = [x for x in coldata[i] if x != '.']
genes = set(x.strip("|") for x in genes)
ngenes.append((len(genes), tx))
details = ", ".join("{0} {1}".format(a, b) for a, b in ngenes)
total = sum(a for a, b in ngenes)
s = "A list of {0} orthologous families that collectively".format(len(data))
s += " contain a total of {0} genes ({1})".format(total, details)
print(s, file=sys.stderr)
fw.close()
lastcolumn = ntaxa + 1
cmd = "sort -k{0},{0} {1} -o {1}".format(lastcolumn, listfile)
sh(cmd)
logging.debug("List file written to `{0}`.".format(listfile))
sort = opts.sort
if sort:
thread = Bed(sort)
sort_layout(thread, listfile) | python | def layout(args):
"""
%prog layout omgfile taxa
Build column formatted gene lists after omgparse(). Use species list
separated by comma in place of taxa, e.g. "BR,BO,AN,CN"
"""
p = OptionParser(layout.__doc__)
p.add_option("--sort",
help="Sort layout file based on bedfile [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
omgfile, taxa = args
listfile = omgfile.rsplit(".", 1)[0] + ".list"
taxa = taxa.split(",")
ntaxa = len(taxa)
fw = open(listfile, "w")
data = []
fp = open(omgfile)
for row in fp:
genes, idxs = row.split()
row = ["."] * ntaxa
genes = genes.split(",")
ixs = [int(x) for x in idxs.split(",")]
for gene, idx in zip(genes, ixs):
row[idx] = gene
txs = ",".join(taxa[x] for x in ixs)
print("\t".join(("\t".join(row), txs)), file=fw)
data.append(row)
coldata = zip(*data)
ngenes = []
for i, tx in enumerate(taxa):
genes = [x for x in coldata[i] if x != '.']
genes = set(x.strip("|") for x in genes)
ngenes.append((len(genes), tx))
details = ", ".join("{0} {1}".format(a, b) for a, b in ngenes)
total = sum(a for a, b in ngenes)
s = "A list of {0} orthologous families that collectively".format(len(data))
s += " contain a total of {0} genes ({1})".format(total, details)
print(s, file=sys.stderr)
fw.close()
lastcolumn = ntaxa + 1
cmd = "sort -k{0},{0} {1} -o {1}".format(lastcolumn, listfile)
sh(cmd)
logging.debug("List file written to `{0}`.".format(listfile))
sort = opts.sort
if sort:
thread = Bed(sort)
sort_layout(thread, listfile) | [
"def",
"layout",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"layout",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--sort\"",
",",
"help",
"=",
"\"Sort layout file based on bedfile [default: %default]\"",
")",
"opts",
",",
"args",
"=",
"p",
... | %prog layout omgfile taxa
Build column formatted gene lists after omgparse(). Use species list
separated by comma in place of taxa, e.g. "BR,BO,AN,CN" | [
"%prog",
"layout",
"omgfile",
"taxa"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/compara/catalog.py#L295-L351 | train | 200,842 |
tanghaibao/jcvi | jcvi/compara/catalog.py | omgparse | def omgparse(args):
"""
%prog omgparse work
Parse the OMG outputs to get gene lists.
"""
p = OptionParser(omgparse.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
work, = args
omgfiles = glob(op.join(work, "gf*.out"))
for omgfile in omgfiles:
omg = OMGFile(omgfile)
best = omg.best()
for bb in best:
genes, taxa = zip(*bb)
print("\t".join((",".join(genes), ",".join(taxa)))) | python | def omgparse(args):
"""
%prog omgparse work
Parse the OMG outputs to get gene lists.
"""
p = OptionParser(omgparse.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
work, = args
omgfiles = glob(op.join(work, "gf*.out"))
for omgfile in omgfiles:
omg = OMGFile(omgfile)
best = omg.best()
for bb in best:
genes, taxa = zip(*bb)
print("\t".join((",".join(genes), ",".join(taxa)))) | [
"def",
"omgparse",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"omgparse",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
":",
"sys",
".",
"exit",
"(",
... | %prog omgparse work
Parse the OMG outputs to get gene lists. | [
"%prog",
"omgparse",
"work"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/compara/catalog.py#L354-L373 | train | 200,843 |
tanghaibao/jcvi | jcvi/compara/catalog.py | group | def group(args):
"""
%prog group anchorfiles
Group the anchors into ortho-groups. Can input multiple anchor files.
"""
p = OptionParser(group.__doc__)
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) < 1:
sys.exit(not p.print_help())
anchorfiles = args
groups = Grouper()
for anchorfile in anchorfiles:
ac = AnchorFile(anchorfile)
for a, b, idx in ac.iter_pairs():
groups.join(a, b)
logging.debug("Created {0} groups with {1} members.".\
format(len(groups), groups.num_members))
outfile = opts.outfile
fw = must_open(outfile, "w")
for g in groups:
print(",".join(sorted(g)), file=fw)
fw.close()
return outfile | python | def group(args):
"""
%prog group anchorfiles
Group the anchors into ortho-groups. Can input multiple anchor files.
"""
p = OptionParser(group.__doc__)
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) < 1:
sys.exit(not p.print_help())
anchorfiles = args
groups = Grouper()
for anchorfile in anchorfiles:
ac = AnchorFile(anchorfile)
for a, b, idx in ac.iter_pairs():
groups.join(a, b)
logging.debug("Created {0} groups with {1} members.".\
format(len(groups), groups.num_members))
outfile = opts.outfile
fw = must_open(outfile, "w")
for g in groups:
print(",".join(sorted(g)), file=fw)
fw.close()
return outfile | [
"def",
"group",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"group",
".",
"__doc__",
")",
"p",
".",
"set_outfile",
"(",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"<",
"1",
... | %prog group anchorfiles
Group the anchors into ortho-groups. Can input multiple anchor files. | [
"%prog",
"group",
"anchorfiles"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/compara/catalog.py#L376-L406 | train | 200,844 |
tanghaibao/jcvi | jcvi/compara/catalog.py | omg | def omg(args):
"""
%prog omg weightsfile
Run Sankoff's OMG algorithm to get orthologs. Download OMG code at:
<http://137.122.149.195/IsbraSoftware/OMGMec.html>
This script only writes the partitions, but not launch OMGMec. You may need to:
$ parallel "java -cp ~/code/OMGMec TestOMGMec {} 4 > {}.out" ::: work/gf?????
Then followed by omgparse() to get the gene lists.
"""
p = OptionParser(omg.__doc__)
opts, args = p.parse_args(args)
if len(args) < 1:
sys.exit(not p.print_help())
weightsfiles = args
groupfile = group(weightsfiles + ["--outfile=groups"])
weights = get_weights(weightsfiles)
info = get_info()
fp = open(groupfile)
work = "work"
mkdir(work)
for i, row in enumerate(fp):
gf = op.join(work, "gf{0:05d}".format(i))
genes = row.rstrip().split(",")
fw = open(gf, "w")
contents = ""
npairs = 0
for gene in genes:
gene_pairs = weights[gene]
for a, b, c in gene_pairs:
if b not in genes:
continue
contents += "weight {0}".format(c) + '\n'
contents += info[a] + '\n'
contents += info[b] + '\n\n'
npairs += 1
header = "a group of genes :length ={0}".format(npairs)
print(header, file=fw)
print(contents, file=fw)
fw.close() | python | def omg(args):
"""
%prog omg weightsfile
Run Sankoff's OMG algorithm to get orthologs. Download OMG code at:
<http://137.122.149.195/IsbraSoftware/OMGMec.html>
This script only writes the partitions, but not launch OMGMec. You may need to:
$ parallel "java -cp ~/code/OMGMec TestOMGMec {} 4 > {}.out" ::: work/gf?????
Then followed by omgparse() to get the gene lists.
"""
p = OptionParser(omg.__doc__)
opts, args = p.parse_args(args)
if len(args) < 1:
sys.exit(not p.print_help())
weightsfiles = args
groupfile = group(weightsfiles + ["--outfile=groups"])
weights = get_weights(weightsfiles)
info = get_info()
fp = open(groupfile)
work = "work"
mkdir(work)
for i, row in enumerate(fp):
gf = op.join(work, "gf{0:05d}".format(i))
genes = row.rstrip().split(",")
fw = open(gf, "w")
contents = ""
npairs = 0
for gene in genes:
gene_pairs = weights[gene]
for a, b, c in gene_pairs:
if b not in genes:
continue
contents += "weight {0}".format(c) + '\n'
contents += info[a] + '\n'
contents += info[b] + '\n\n'
npairs += 1
header = "a group of genes :length ={0}".format(npairs)
print(header, file=fw)
print(contents, file=fw)
fw.close() | [
"def",
"omg",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"omg",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"<",
"1",
":",
"sys",
".",
"exit",
"(",
"not",
... | %prog omg weightsfile
Run Sankoff's OMG algorithm to get orthologs. Download OMG code at:
<http://137.122.149.195/IsbraSoftware/OMGMec.html>
This script only writes the partitions, but not launch OMGMec. You may need to:
$ parallel "java -cp ~/code/OMGMec TestOMGMec {} 4 > {}.out" ::: work/gf?????
Then followed by omgparse() to get the gene lists. | [
"%prog",
"omg",
"weightsfile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/compara/catalog.py#L409-L461 | train | 200,845 |
tanghaibao/jcvi | jcvi/compara/catalog.py | omgprepare | def omgprepare(args):
"""
%prog omgprepare ploidy anchorsfile blastfile
Prepare to run Sankoff's OMG algorithm to get orthologs.
"""
from jcvi.formats.blast import cscore
from jcvi.formats.base import DictFile
p = OptionParser(omgprepare.__doc__)
p.add_option("--norbh", action="store_true",
help="Disable RBH hits [default: %default]")
p.add_option("--pctid", default=0, type="int",
help="Percent id cutoff for RBH hits [default: %default]")
p.add_option("--cscore", default=90, type="int",
help="C-score cutoff for RBH hits [default: %default]")
p.set_stripnames()
p.set_beds()
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
ploidy, anchorfile, blastfile = args
norbh = opts.norbh
pctid = opts.pctid
cs = opts.cscore
qbed, sbed, qorder, sorder, is_self = check_beds(anchorfile, p, opts)
fp = open(ploidy)
genomeidx = dict((x.split()[0], i) for i, x in enumerate(fp))
fp.close()
ploidy = DictFile(ploidy)
geneinfo(qbed, qorder, genomeidx, ploidy)
geneinfo(sbed, sorder, genomeidx, ploidy)
pf = blastfile.rsplit(".", 1)[0]
cscorefile = pf + ".cscore"
cscore([blastfile, "-o", cscorefile, "--cutoff=0", "--pct"])
ac = AnchorFile(anchorfile)
pairs = set((a, b) for a, b, i in ac.iter_pairs())
logging.debug("Imported {0} pairs from `{1}`.".format(len(pairs), anchorfile))
weightsfile = pf + ".weights"
fp = open(cscorefile)
fw = open(weightsfile, "w")
npairs = 0
for row in fp:
a, b, c, pct = row.split()
c, pct = float(c), float(pct)
c = int(c * 100)
if (a, b) not in pairs:
if norbh:
continue
if c < cs:
continue
if pct < pctid:
continue
c /= 10 # This severely penalizes RBH against synteny
print("\t".join((a, b, str(c))), file=fw)
npairs += 1
fw.close()
logging.debug("Write {0} pairs to `{1}`.".format(npairs, weightsfile)) | python | def omgprepare(args):
"""
%prog omgprepare ploidy anchorsfile blastfile
Prepare to run Sankoff's OMG algorithm to get orthologs.
"""
from jcvi.formats.blast import cscore
from jcvi.formats.base import DictFile
p = OptionParser(omgprepare.__doc__)
p.add_option("--norbh", action="store_true",
help="Disable RBH hits [default: %default]")
p.add_option("--pctid", default=0, type="int",
help="Percent id cutoff for RBH hits [default: %default]")
p.add_option("--cscore", default=90, type="int",
help="C-score cutoff for RBH hits [default: %default]")
p.set_stripnames()
p.set_beds()
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
ploidy, anchorfile, blastfile = args
norbh = opts.norbh
pctid = opts.pctid
cs = opts.cscore
qbed, sbed, qorder, sorder, is_self = check_beds(anchorfile, p, opts)
fp = open(ploidy)
genomeidx = dict((x.split()[0], i) for i, x in enumerate(fp))
fp.close()
ploidy = DictFile(ploidy)
geneinfo(qbed, qorder, genomeidx, ploidy)
geneinfo(sbed, sorder, genomeidx, ploidy)
pf = blastfile.rsplit(".", 1)[0]
cscorefile = pf + ".cscore"
cscore([blastfile, "-o", cscorefile, "--cutoff=0", "--pct"])
ac = AnchorFile(anchorfile)
pairs = set((a, b) for a, b, i in ac.iter_pairs())
logging.debug("Imported {0} pairs from `{1}`.".format(len(pairs), anchorfile))
weightsfile = pf + ".weights"
fp = open(cscorefile)
fw = open(weightsfile, "w")
npairs = 0
for row in fp:
a, b, c, pct = row.split()
c, pct = float(c), float(pct)
c = int(c * 100)
if (a, b) not in pairs:
if norbh:
continue
if c < cs:
continue
if pct < pctid:
continue
c /= 10 # This severely penalizes RBH against synteny
print("\t".join((a, b, str(c))), file=fw)
npairs += 1
fw.close()
logging.debug("Write {0} pairs to `{1}`.".format(npairs, weightsfile)) | [
"def",
"omgprepare",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"blast",
"import",
"cscore",
"from",
"jcvi",
".",
"formats",
".",
"base",
"import",
"DictFile",
"p",
"=",
"OptionParser",
"(",
"omgprepare",
".",
"__doc__",
")",
"p",
".",
... | %prog omgprepare ploidy anchorsfile blastfile
Prepare to run Sankoff's OMG algorithm to get orthologs. | [
"%prog",
"omgprepare",
"ploidy",
"anchorsfile",
"blastfile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/compara/catalog.py#L492-L559 | train | 200,846 |
tanghaibao/jcvi | jcvi/utils/orderedcollections.py | parse_qs | def parse_qs(qs, keep_blank_values=0, strict_parsing=0, keep_attr_order=True):
"""
Kind of like urlparse.parse_qs, except returns an ordered dict.
Also avoids replicating that function's bad habit of overriding the
built-in 'dict' type.
Taken from below with modification:
<https://bitbucket.org/btubbs/thumpy/raw/8cdece404f15/thumpy.py>
"""
od = DefaultOrderedDict(list) if keep_attr_order else defaultdict(list)
for name, value in parse_qsl(qs, keep_blank_values, strict_parsing):
od[name].append(value)
return od | python | def parse_qs(qs, keep_blank_values=0, strict_parsing=0, keep_attr_order=True):
"""
Kind of like urlparse.parse_qs, except returns an ordered dict.
Also avoids replicating that function's bad habit of overriding the
built-in 'dict' type.
Taken from below with modification:
<https://bitbucket.org/btubbs/thumpy/raw/8cdece404f15/thumpy.py>
"""
od = DefaultOrderedDict(list) if keep_attr_order else defaultdict(list)
for name, value in parse_qsl(qs, keep_blank_values, strict_parsing):
od[name].append(value)
return od | [
"def",
"parse_qs",
"(",
"qs",
",",
"keep_blank_values",
"=",
"0",
",",
"strict_parsing",
"=",
"0",
",",
"keep_attr_order",
"=",
"True",
")",
":",
"od",
"=",
"DefaultOrderedDict",
"(",
"list",
")",
"if",
"keep_attr_order",
"else",
"defaultdict",
"(",
"list",
... | Kind of like urlparse.parse_qs, except returns an ordered dict.
Also avoids replicating that function's bad habit of overriding the
built-in 'dict' type.
Taken from below with modification:
<https://bitbucket.org/btubbs/thumpy/raw/8cdece404f15/thumpy.py> | [
"Kind",
"of",
"like",
"urlparse",
".",
"parse_qs",
"except",
"returns",
"an",
"ordered",
"dict",
".",
"Also",
"avoids",
"replicating",
"that",
"function",
"s",
"bad",
"habit",
"of",
"overriding",
"the",
"built",
"-",
"in",
"dict",
"type",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/utils/orderedcollections.py#L184-L197 | train | 200,847 |
tanghaibao/jcvi | jcvi/utils/orderedcollections.py | SortedCollection.index | def index(self, item):
'Find the position of an item. Raise ValueError if not found.'
k = self._key(item)
i = bisect_left(self._keys, k)
j = bisect_right(self._keys, k)
return self._items[i:j].index(item) + i | python | def index(self, item):
'Find the position of an item. Raise ValueError if not found.'
k = self._key(item)
i = bisect_left(self._keys, k)
j = bisect_right(self._keys, k)
return self._items[i:j].index(item) + i | [
"def",
"index",
"(",
"self",
",",
"item",
")",
":",
"k",
"=",
"self",
".",
"_key",
"(",
"item",
")",
"i",
"=",
"bisect_left",
"(",
"self",
".",
"_keys",
",",
"k",
")",
"j",
"=",
"bisect_right",
"(",
"self",
".",
"_keys",
",",
"k",
")",
"return"... | Find the position of an item. Raise ValueError if not found. | [
"Find",
"the",
"position",
"of",
"an",
"item",
".",
"Raise",
"ValueError",
"if",
"not",
"found",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/utils/orderedcollections.py#L328-L333 | train | 200,848 |
tanghaibao/jcvi | jcvi/utils/orderedcollections.py | SortedCollection.insert | def insert(self, item):
'Insert a new item. If equal keys are found, add to the left'
k = self._key(item)
i = bisect_left(self._keys, k)
self._keys.insert(i, k)
self._items.insert(i, item) | python | def insert(self, item):
'Insert a new item. If equal keys are found, add to the left'
k = self._key(item)
i = bisect_left(self._keys, k)
self._keys.insert(i, k)
self._items.insert(i, item) | [
"def",
"insert",
"(",
"self",
",",
"item",
")",
":",
"k",
"=",
"self",
".",
"_key",
"(",
"item",
")",
"i",
"=",
"bisect_left",
"(",
"self",
".",
"_keys",
",",
"k",
")",
"self",
".",
"_keys",
".",
"insert",
"(",
"i",
",",
"k",
")",
"self",
"."... | Insert a new item. If equal keys are found, add to the left | [
"Insert",
"a",
"new",
"item",
".",
"If",
"equal",
"keys",
"are",
"found",
"add",
"to",
"the",
"left"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/utils/orderedcollections.py#L342-L347 | train | 200,849 |
tanghaibao/jcvi | jcvi/utils/orderedcollections.py | SortedCollection.insert_right | def insert_right(self, item):
'Insert a new item. If equal keys are found, add to the right'
k = self._key(item)
i = bisect_right(self._keys, k)
self._keys.insert(i, k)
self._items.insert(i, item) | python | def insert_right(self, item):
'Insert a new item. If equal keys are found, add to the right'
k = self._key(item)
i = bisect_right(self._keys, k)
self._keys.insert(i, k)
self._items.insert(i, item) | [
"def",
"insert_right",
"(",
"self",
",",
"item",
")",
":",
"k",
"=",
"self",
".",
"_key",
"(",
"item",
")",
"i",
"=",
"bisect_right",
"(",
"self",
".",
"_keys",
",",
"k",
")",
"self",
".",
"_keys",
".",
"insert",
"(",
"i",
",",
"k",
")",
"self"... | Insert a new item. If equal keys are found, add to the right | [
"Insert",
"a",
"new",
"item",
".",
"If",
"equal",
"keys",
"are",
"found",
"add",
"to",
"the",
"right"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/utils/orderedcollections.py#L349-L354 | train | 200,850 |
tanghaibao/jcvi | jcvi/utils/orderedcollections.py | SortedCollection.remove | def remove(self, item):
'Remove first occurence of item. Raise ValueError if not found'
i = self.index(item)
del self._keys[i]
del self._items[i] | python | def remove(self, item):
'Remove first occurence of item. Raise ValueError if not found'
i = self.index(item)
del self._keys[i]
del self._items[i] | [
"def",
"remove",
"(",
"self",
",",
"item",
")",
":",
"i",
"=",
"self",
".",
"index",
"(",
"item",
")",
"del",
"self",
".",
"_keys",
"[",
"i",
"]",
"del",
"self",
".",
"_items",
"[",
"i",
"]"
] | Remove first occurence of item. Raise ValueError if not found | [
"Remove",
"first",
"occurence",
"of",
"item",
".",
"Raise",
"ValueError",
"if",
"not",
"found"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/utils/orderedcollections.py#L356-L360 | train | 200,851 |
tanghaibao/jcvi | jcvi/utils/orderedcollections.py | SortedCollection.find_ge | def find_ge(self, item):
'Return first item with a key >= equal to item. Raise ValueError if not found'
k = self._key(item)
i = bisect_left(self._keys, k)
if i != len(self):
return self._items[i]
raise ValueError('No item found with key at or above: %r' % (k,)) | python | def find_ge(self, item):
'Return first item with a key >= equal to item. Raise ValueError if not found'
k = self._key(item)
i = bisect_left(self._keys, k)
if i != len(self):
return self._items[i]
raise ValueError('No item found with key at or above: %r' % (k,)) | [
"def",
"find_ge",
"(",
"self",
",",
"item",
")",
":",
"k",
"=",
"self",
".",
"_key",
"(",
"item",
")",
"i",
"=",
"bisect_left",
"(",
"self",
".",
"_keys",
",",
"k",
")",
"if",
"i",
"!=",
"len",
"(",
"self",
")",
":",
"return",
"self",
".",
"_... | Return first item with a key >= equal to item. Raise ValueError if not found | [
"Return",
"first",
"item",
"with",
"a",
"key",
">",
"=",
"equal",
"to",
"item",
".",
"Raise",
"ValueError",
"if",
"not",
"found"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/utils/orderedcollections.py#L386-L392 | train | 200,852 |
tanghaibao/jcvi | jcvi/utils/orderedcollections.py | SortedCollection.find_gt | def find_gt(self, item):
'Return first item with a key > item. Raise ValueError if not found'
k = self._key(item)
i = bisect_right(self._keys, k)
if i != len(self):
return self._items[i]
raise ValueError('No item found with key above: %r' % (k,)) | python | def find_gt(self, item):
'Return first item with a key > item. Raise ValueError if not found'
k = self._key(item)
i = bisect_right(self._keys, k)
if i != len(self):
return self._items[i]
raise ValueError('No item found with key above: %r' % (k,)) | [
"def",
"find_gt",
"(",
"self",
",",
"item",
")",
":",
"k",
"=",
"self",
".",
"_key",
"(",
"item",
")",
"i",
"=",
"bisect_right",
"(",
"self",
".",
"_keys",
",",
"k",
")",
"if",
"i",
"!=",
"len",
"(",
"self",
")",
":",
"return",
"self",
".",
"... | Return first item with a key > item. Raise ValueError if not found | [
"Return",
"first",
"item",
"with",
"a",
"key",
">",
"item",
".",
"Raise",
"ValueError",
"if",
"not",
"found"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/utils/orderedcollections.py#L394-L400 | train | 200,853 |
tanghaibao/jcvi | jcvi/apps/ks.py | multireport | def multireport(args):
"""
%prog multireport layoutfile
Generate several Ks value distributions in the same figure. If the layout
file is missing then a template file listing all ks files will be written.
The layout file contains the Ks file, number of components, colors, and labels:
# Ks file, ncomponents, label, color, marker
LAP.sorghum.ks, 1, LAP-sorghum, r, o
SES.sorghum.ks, 1, SES-sorghum, g, +
MOL.sorghum.ks, 1, MOL-sorghum, m, ^
If color or marker is missing, then a random one will be assigned.
"""
p = OptionParser(multireport.__doc__)
p.set_outfile(outfile="Ks_plot.pdf")
add_plot_options(p)
opts, args, iopts = p.set_image_options(args, figsize="5x5")
if len(args) != 1:
sys.exit(not p.print_help())
layoutfile, = args
ks_min = opts.vmin
ks_max = opts.vmax
bins = opts.bins
fill = opts.fill
layout = Layout(layoutfile)
print(layout, file=sys.stderr)
fig = plt.figure(1, (iopts.w, iopts.h))
ax = fig.add_axes([.12, .1, .8, .8])
kp = KsPlot(ax, ks_max, bins, legendp=opts.legendp)
for lo in layout:
data = KsFile(lo.ksfile)
data = [x.ng_ks for x in data]
data = [x for x in data if ks_min <= x <= ks_max]
kp.add_data(data, lo.components, label=lo.label, \
color=lo.color, marker=lo.marker,
fill=fill, fitted=opts.fit)
kp.draw(title=opts.title, filename=opts.outfile) | python | def multireport(args):
"""
%prog multireport layoutfile
Generate several Ks value distributions in the same figure. If the layout
file is missing then a template file listing all ks files will be written.
The layout file contains the Ks file, number of components, colors, and labels:
# Ks file, ncomponents, label, color, marker
LAP.sorghum.ks, 1, LAP-sorghum, r, o
SES.sorghum.ks, 1, SES-sorghum, g, +
MOL.sorghum.ks, 1, MOL-sorghum, m, ^
If color or marker is missing, then a random one will be assigned.
"""
p = OptionParser(multireport.__doc__)
p.set_outfile(outfile="Ks_plot.pdf")
add_plot_options(p)
opts, args, iopts = p.set_image_options(args, figsize="5x5")
if len(args) != 1:
sys.exit(not p.print_help())
layoutfile, = args
ks_min = opts.vmin
ks_max = opts.vmax
bins = opts.bins
fill = opts.fill
layout = Layout(layoutfile)
print(layout, file=sys.stderr)
fig = plt.figure(1, (iopts.w, iopts.h))
ax = fig.add_axes([.12, .1, .8, .8])
kp = KsPlot(ax, ks_max, bins, legendp=opts.legendp)
for lo in layout:
data = KsFile(lo.ksfile)
data = [x.ng_ks for x in data]
data = [x for x in data if ks_min <= x <= ks_max]
kp.add_data(data, lo.components, label=lo.label, \
color=lo.color, marker=lo.marker,
fill=fill, fitted=opts.fit)
kp.draw(title=opts.title, filename=opts.outfile) | [
"def",
"multireport",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"multireport",
".",
"__doc__",
")",
"p",
".",
"set_outfile",
"(",
"outfile",
"=",
"\"Ks_plot.pdf\"",
")",
"add_plot_options",
"(",
"p",
")",
"opts",
",",
"args",
",",
"iopts",
"=... | %prog multireport layoutfile
Generate several Ks value distributions in the same figure. If the layout
file is missing then a template file listing all ks files will be written.
The layout file contains the Ks file, number of components, colors, and labels:
# Ks file, ncomponents, label, color, marker
LAP.sorghum.ks, 1, LAP-sorghum, r, o
SES.sorghum.ks, 1, SES-sorghum, g, +
MOL.sorghum.ks, 1, MOL-sorghum, m, ^
If color or marker is missing, then a random one will be assigned. | [
"%prog",
"multireport",
"layoutfile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/ks.py#L219-L262 | train | 200,854 |
tanghaibao/jcvi | jcvi/apps/ks.py | fromgroups | def fromgroups(args):
"""
%prog fromgroups groupsfile a.bed b.bed ...
Flatten the gene familes into pairs, the groupsfile is a file with each line
containing the members, separated by comma. The commands also require
several bed files in order to sort the pairs into different piles (e.g.
pairs of species in comparison.
"""
from jcvi.formats.bed import Bed
p = OptionParser(fromgroups.__doc__)
opts, args = p.parse_args(args)
if len(args) < 2:
sys.exit(not p.print_help())
groupsfile = args[0]
bedfiles = args[1:]
beds = [Bed(x) for x in bedfiles]
fp = open(groupsfile)
groups = [row.strip().split(",") for row in fp]
for b1, b2 in product(beds, repeat=2):
extract_pairs(b1, b2, groups) | python | def fromgroups(args):
"""
%prog fromgroups groupsfile a.bed b.bed ...
Flatten the gene familes into pairs, the groupsfile is a file with each line
containing the members, separated by comma. The commands also require
several bed files in order to sort the pairs into different piles (e.g.
pairs of species in comparison.
"""
from jcvi.formats.bed import Bed
p = OptionParser(fromgroups.__doc__)
opts, args = p.parse_args(args)
if len(args) < 2:
sys.exit(not p.print_help())
groupsfile = args[0]
bedfiles = args[1:]
beds = [Bed(x) for x in bedfiles]
fp = open(groupsfile)
groups = [row.strip().split(",") for row in fp]
for b1, b2 in product(beds, repeat=2):
extract_pairs(b1, b2, groups) | [
"def",
"fromgroups",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"bed",
"import",
"Bed",
"p",
"=",
"OptionParser",
"(",
"fromgroups",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len"... | %prog fromgroups groupsfile a.bed b.bed ...
Flatten the gene familes into pairs, the groupsfile is a file with each line
containing the members, separated by comma. The commands also require
several bed files in order to sort the pairs into different piles (e.g.
pairs of species in comparison. | [
"%prog",
"fromgroups",
"groupsfile",
"a",
".",
"bed",
"b",
".",
"bed",
"..."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/ks.py#L376-L399 | train | 200,855 |
tanghaibao/jcvi | jcvi/apps/ks.py | find_synonymous | def find_synonymous(input_file, work_dir):
"""Run yn00 to find the synonymous subsitution rate for the alignment.
"""
cwd = os.getcwd()
os.chdir(work_dir)
# create the .ctl file
ctl_file = "yn-input.ctl"
output_file = "nuc-subs.yn"
ctl_h = open(ctl_file, "w")
ctl_h.write("seqfile = %s\noutfile = %s\nverbose = 0\n" %
(op.basename(input_file), output_file))
ctl_h.write("icode = 0\nweighting = 0\ncommonf3x4 = 0\n")
ctl_h.close()
cl = YnCommandline(ctl_file)
print("\tyn00:", cl, file=sys.stderr)
r, e = cl.run()
ds_value_yn = None
ds_value_ng = None
dn_value_yn = None
dn_value_ng = None
# Nei-Gojobori
output_h = open(output_file)
row = output_h.readline()
while row:
if row.find("Nei & Gojobori") >=0:
for x in xrange(5):
row = next(output_h)
dn_value_ng, ds_value_ng = row.split('(')[1].split(')')[0].split()
break
row = output_h.readline()
output_h.close()
# Yang
output_h = open(output_file)
for line in output_h:
if line.find("+-") >= 0 and line.find("dS") == -1:
parts = line.split(" +-")
ds_value_yn = extract_subs_value(parts[1])
dn_value_yn = extract_subs_value(parts[0])
if ds_value_yn is None or ds_value_ng is None:
h = open(output_file)
print("yn00 didn't work: \n%s" % h.read(), file=sys.stderr)
os.chdir(cwd)
return ds_value_yn, dn_value_yn, ds_value_ng, dn_value_ng | python | def find_synonymous(input_file, work_dir):
"""Run yn00 to find the synonymous subsitution rate for the alignment.
"""
cwd = os.getcwd()
os.chdir(work_dir)
# create the .ctl file
ctl_file = "yn-input.ctl"
output_file = "nuc-subs.yn"
ctl_h = open(ctl_file, "w")
ctl_h.write("seqfile = %s\noutfile = %s\nverbose = 0\n" %
(op.basename(input_file), output_file))
ctl_h.write("icode = 0\nweighting = 0\ncommonf3x4 = 0\n")
ctl_h.close()
cl = YnCommandline(ctl_file)
print("\tyn00:", cl, file=sys.stderr)
r, e = cl.run()
ds_value_yn = None
ds_value_ng = None
dn_value_yn = None
dn_value_ng = None
# Nei-Gojobori
output_h = open(output_file)
row = output_h.readline()
while row:
if row.find("Nei & Gojobori") >=0:
for x in xrange(5):
row = next(output_h)
dn_value_ng, ds_value_ng = row.split('(')[1].split(')')[0].split()
break
row = output_h.readline()
output_h.close()
# Yang
output_h = open(output_file)
for line in output_h:
if line.find("+-") >= 0 and line.find("dS") == -1:
parts = line.split(" +-")
ds_value_yn = extract_subs_value(parts[1])
dn_value_yn = extract_subs_value(parts[0])
if ds_value_yn is None or ds_value_ng is None:
h = open(output_file)
print("yn00 didn't work: \n%s" % h.read(), file=sys.stderr)
os.chdir(cwd)
return ds_value_yn, dn_value_yn, ds_value_ng, dn_value_ng | [
"def",
"find_synonymous",
"(",
"input_file",
",",
"work_dir",
")",
":",
"cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"os",
".",
"chdir",
"(",
"work_dir",
")",
"# create the .ctl file",
"ctl_file",
"=",
"\"yn-input.ctl\"",
"output_file",
"=",
"\"nuc-subs.yn\"",
"... | Run yn00 to find the synonymous subsitution rate for the alignment. | [
"Run",
"yn00",
"to",
"find",
"the",
"synonymous",
"subsitution",
"rate",
"for",
"the",
"alignment",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/ks.py#L546-L593 | train | 200,856 |
tanghaibao/jcvi | jcvi/apps/ks.py | run_mrtrans | def run_mrtrans(align_fasta, recs, work_dir, outfmt="paml"):
"""Align nucleotide sequences with mrtrans and the protein alignment.
"""
align_file = op.join(work_dir, "prot-align.fasta")
nuc_file = op.join(work_dir, "nuc.fasta")
output_file = op.join(work_dir, "nuc-align.mrtrans")
# make the prot_align file and nucleotide file
align_h0 = open(align_file + "0", "w")
align_h0.write(str(align_fasta))
align_h0.close()
prot_seqs = {}
i = 0
for rec in SeqIO.parse(align_h0.name, "fasta"):
prot_seqs[i] = rec.seq
i += 1
align_h = open(align_file, "w")
for i, rec in enumerate(recs):
if len(rec.id) > 30:
rec.id = rec.id[:28] + "_" + str(i)
rec.description = ""
print(">{0}\n{1}".format(rec.id, prot_seqs[i]), file=align_h)
align_h.close()
SeqIO.write(recs, file(nuc_file, "w"), "fasta")
# run the program
cl = MrTransCommandline(align_file, nuc_file, output_file, outfmt=outfmt)
r, e = cl.run()
if e is None:
print("\tpal2nal:", cl, file=sys.stderr)
return output_file
elif e.read().find("could not translate") >= 0:
print("***pal2nal could not translate", file=sys.stderr)
return None | python | def run_mrtrans(align_fasta, recs, work_dir, outfmt="paml"):
"""Align nucleotide sequences with mrtrans and the protein alignment.
"""
align_file = op.join(work_dir, "prot-align.fasta")
nuc_file = op.join(work_dir, "nuc.fasta")
output_file = op.join(work_dir, "nuc-align.mrtrans")
# make the prot_align file and nucleotide file
align_h0 = open(align_file + "0", "w")
align_h0.write(str(align_fasta))
align_h0.close()
prot_seqs = {}
i = 0
for rec in SeqIO.parse(align_h0.name, "fasta"):
prot_seqs[i] = rec.seq
i += 1
align_h = open(align_file, "w")
for i, rec in enumerate(recs):
if len(rec.id) > 30:
rec.id = rec.id[:28] + "_" + str(i)
rec.description = ""
print(">{0}\n{1}".format(rec.id, prot_seqs[i]), file=align_h)
align_h.close()
SeqIO.write(recs, file(nuc_file, "w"), "fasta")
# run the program
cl = MrTransCommandline(align_file, nuc_file, output_file, outfmt=outfmt)
r, e = cl.run()
if e is None:
print("\tpal2nal:", cl, file=sys.stderr)
return output_file
elif e.read().find("could not translate") >= 0:
print("***pal2nal could not translate", file=sys.stderr)
return None | [
"def",
"run_mrtrans",
"(",
"align_fasta",
",",
"recs",
",",
"work_dir",
",",
"outfmt",
"=",
"\"paml\"",
")",
":",
"align_file",
"=",
"op",
".",
"join",
"(",
"work_dir",
",",
"\"prot-align.fasta\"",
")",
"nuc_file",
"=",
"op",
".",
"join",
"(",
"work_dir",
... | Align nucleotide sequences with mrtrans and the protein alignment. | [
"Align",
"nucleotide",
"sequences",
"with",
"mrtrans",
"and",
"the",
"protein",
"alignment",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/ks.py#L618-L651 | train | 200,857 |
tanghaibao/jcvi | jcvi/apps/ks.py | clustal_align_protein | def clustal_align_protein(recs, work_dir, outfmt="fasta"):
"""
Align given proteins with clustalw.
recs are iterable of Biopython SeqIO objects
"""
fasta_file = op.join(work_dir, "prot-start.fasta")
align_file = op.join(work_dir, "prot.aln")
SeqIO.write(recs, file(fasta_file, "w"), "fasta")
clustal_cl = ClustalwCommandline(cmd=CLUSTALW_BIN("clustalw2"),
infile=fasta_file, outfile=align_file, outorder="INPUT",
type="PROTEIN")
stdout, stderr = clustal_cl()
aln_file = file(clustal_cl.outfile)
alignment = AlignIO.read(aln_file, "clustal")
print("\tDoing clustalw alignment: %s" % clustal_cl, file=sys.stderr)
if outfmt == "fasta":
return alignment.format("fasta")
if outfmt == "clustal":
return alignment | python | def clustal_align_protein(recs, work_dir, outfmt="fasta"):
"""
Align given proteins with clustalw.
recs are iterable of Biopython SeqIO objects
"""
fasta_file = op.join(work_dir, "prot-start.fasta")
align_file = op.join(work_dir, "prot.aln")
SeqIO.write(recs, file(fasta_file, "w"), "fasta")
clustal_cl = ClustalwCommandline(cmd=CLUSTALW_BIN("clustalw2"),
infile=fasta_file, outfile=align_file, outorder="INPUT",
type="PROTEIN")
stdout, stderr = clustal_cl()
aln_file = file(clustal_cl.outfile)
alignment = AlignIO.read(aln_file, "clustal")
print("\tDoing clustalw alignment: %s" % clustal_cl, file=sys.stderr)
if outfmt == "fasta":
return alignment.format("fasta")
if outfmt == "clustal":
return alignment | [
"def",
"clustal_align_protein",
"(",
"recs",
",",
"work_dir",
",",
"outfmt",
"=",
"\"fasta\"",
")",
":",
"fasta_file",
"=",
"op",
".",
"join",
"(",
"work_dir",
",",
"\"prot-start.fasta\"",
")",
"align_file",
"=",
"op",
".",
"join",
"(",
"work_dir",
",",
"\... | Align given proteins with clustalw.
recs are iterable of Biopython SeqIO objects | [
"Align",
"given",
"proteins",
"with",
"clustalw",
".",
"recs",
"are",
"iterable",
"of",
"Biopython",
"SeqIO",
"objects"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/ks.py#L654-L674 | train | 200,858 |
tanghaibao/jcvi | jcvi/apps/ks.py | muscle_align_protein | def muscle_align_protein(recs, work_dir, outfmt="fasta", inputorder=True):
"""
Align given proteins with muscle.
recs are iterable of Biopython SeqIO objects
"""
fasta_file = op.join(work_dir, "prot-start.fasta")
align_file = op.join(work_dir, "prot.aln")
SeqIO.write(recs, file(fasta_file, "w"), "fasta")
muscle_cl = MuscleCommandline(cmd=MUSCLE_BIN("muscle"),
input=fasta_file, out=align_file, seqtype="protein",
clwstrict=True)
stdout, stderr = muscle_cl()
alignment = AlignIO.read(muscle_cl.out, "clustal")
if inputorder:
try:
muscle_inputorder(muscle_cl.input, muscle_cl.out)
except ValueError:
return ""
alignment = AlignIO.read(muscle_cl.out, "fasta")
print("\tDoing muscle alignment: %s" % muscle_cl, file=sys.stderr)
if outfmt == "fasta":
return alignment.format("fasta")
if outfmt == "clustal":
return alignment.format("clustal") | python | def muscle_align_protein(recs, work_dir, outfmt="fasta", inputorder=True):
"""
Align given proteins with muscle.
recs are iterable of Biopython SeqIO objects
"""
fasta_file = op.join(work_dir, "prot-start.fasta")
align_file = op.join(work_dir, "prot.aln")
SeqIO.write(recs, file(fasta_file, "w"), "fasta")
muscle_cl = MuscleCommandline(cmd=MUSCLE_BIN("muscle"),
input=fasta_file, out=align_file, seqtype="protein",
clwstrict=True)
stdout, stderr = muscle_cl()
alignment = AlignIO.read(muscle_cl.out, "clustal")
if inputorder:
try:
muscle_inputorder(muscle_cl.input, muscle_cl.out)
except ValueError:
return ""
alignment = AlignIO.read(muscle_cl.out, "fasta")
print("\tDoing muscle alignment: %s" % muscle_cl, file=sys.stderr)
if outfmt == "fasta":
return alignment.format("fasta")
if outfmt == "clustal":
return alignment.format("clustal") | [
"def",
"muscle_align_protein",
"(",
"recs",
",",
"work_dir",
",",
"outfmt",
"=",
"\"fasta\"",
",",
"inputorder",
"=",
"True",
")",
":",
"fasta_file",
"=",
"op",
".",
"join",
"(",
"work_dir",
",",
"\"prot-start.fasta\"",
")",
"align_file",
"=",
"op",
".",
"... | Align given proteins with muscle.
recs are iterable of Biopython SeqIO objects | [
"Align",
"given",
"proteins",
"with",
"muscle",
".",
"recs",
"are",
"iterable",
"of",
"Biopython",
"SeqIO",
"objects"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/ks.py#L677-L703 | train | 200,859 |
tanghaibao/jcvi | jcvi/apps/ks.py | subset | def subset(args):
"""
%prog subset pairsfile ksfile1 ksfile2 ... -o pairs.ks
Subset some pre-calculated ks ka values (in ksfile) according to pairs
in tab delimited pairsfile/anchorfile.
"""
p = OptionParser(subset.__doc__)
p.add_option("--noheader", action="store_true",
help="don't write ksfile header line [default: %default]")
p.add_option("--block", action="store_true",
help="preserve block structure in input [default: %default]")
p.set_stripnames()
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
pairsfile, ksfiles = args[0], args[1:]
noheader = opts.noheader
block = opts.block
if block:
noheader = True
outfile = opts.outfile
ksvals = {}
for ksfile in ksfiles:
ksvals.update(dict((line.name, line) for line in \
KsFile(ksfile, strip_names=opts.strip_names)))
fp = open(pairsfile)
fw = must_open(outfile, "w")
if not noheader:
print(fields, file=fw)
i = j = 0
for row in fp:
if row[0] == '#':
if block:
print(row.strip(), file=fw)
continue
a, b = row.split()[:2]
name = ";".join((a, b))
if name not in ksvals:
name = ";".join((b, a))
if name not in ksvals:
j += 1
print("\t".join((a, b, ".", ".")), file=fw)
continue
ksline = ksvals[name]
if block:
print("\t".join(str(x) for x in (a, b, ksline.ks)), file=fw)
else:
ksline.name = ";".join((a, b))
print(ksline, file=fw)
i += 1
fw.close()
logging.debug("{0} pairs not found in ksfiles".format(j))
logging.debug("{0} ks records written to `{1}`".format(i, outfile))
return outfile | python | def subset(args):
"""
%prog subset pairsfile ksfile1 ksfile2 ... -o pairs.ks
Subset some pre-calculated ks ka values (in ksfile) according to pairs
in tab delimited pairsfile/anchorfile.
"""
p = OptionParser(subset.__doc__)
p.add_option("--noheader", action="store_true",
help="don't write ksfile header line [default: %default]")
p.add_option("--block", action="store_true",
help="preserve block structure in input [default: %default]")
p.set_stripnames()
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
pairsfile, ksfiles = args[0], args[1:]
noheader = opts.noheader
block = opts.block
if block:
noheader = True
outfile = opts.outfile
ksvals = {}
for ksfile in ksfiles:
ksvals.update(dict((line.name, line) for line in \
KsFile(ksfile, strip_names=opts.strip_names)))
fp = open(pairsfile)
fw = must_open(outfile, "w")
if not noheader:
print(fields, file=fw)
i = j = 0
for row in fp:
if row[0] == '#':
if block:
print(row.strip(), file=fw)
continue
a, b = row.split()[:2]
name = ";".join((a, b))
if name not in ksvals:
name = ";".join((b, a))
if name not in ksvals:
j += 1
print("\t".join((a, b, ".", ".")), file=fw)
continue
ksline = ksvals[name]
if block:
print("\t".join(str(x) for x in (a, b, ksline.ks)), file=fw)
else:
ksline.name = ";".join((a, b))
print(ksline, file=fw)
i += 1
fw.close()
logging.debug("{0} pairs not found in ksfiles".format(j))
logging.debug("{0} ks records written to `{1}`".format(i, outfile))
return outfile | [
"def",
"subset",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"subset",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--noheader\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"don't write ksfile header line [default: %default]\"",
... | %prog subset pairsfile ksfile1 ksfile2 ... -o pairs.ks
Subset some pre-calculated ks ka values (in ksfile) according to pairs
in tab delimited pairsfile/anchorfile. | [
"%prog",
"subset",
"pairsfile",
"ksfile1",
"ksfile2",
"...",
"-",
"o",
"pairs",
".",
"ks"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/ks.py#L729-L792 | train | 200,860 |
tanghaibao/jcvi | jcvi/apps/ks.py | report | def report(args):
'''
%prog report ksfile
generate a report given a Ks result file (as produced by synonymous_calc.py).
describe the median Ks, Ka values, as well as the distribution in stem-leaf plot
'''
from jcvi.utils.cbook import SummaryStats
from jcvi.graphics.histogram import stem_leaf_plot
p = OptionParser(report.__doc__)
p.add_option("--pdf", default=False, action="store_true",
help="Generate graphic output for the histogram [default: %default]")
p.add_option("--components", default=1, type="int",
help="Number of components to decompose peaks [default: %default]")
add_plot_options(p)
opts, args, iopts = p.set_image_options(args, figsize="5x5")
if len(args) != 1:
sys.exit(not p.print_help())
ks_file, = args
data = KsFile(ks_file)
ks_min = opts.vmin
ks_max = opts.vmax
bins = opts.bins
for f in fields.split(",")[1:]:
columndata = [getattr(x, f) for x in data]
ks = ("ks" in f)
if not ks:
continue
columndata = [x for x in columndata if ks_min <= x <= ks_max]
st = SummaryStats(columndata)
title = "{0} ({1}): ".format(descriptions[f], ks_file)
title += "Median:{0:.3f} (1Q:{1:.3f}|3Q:{2:.3f}||".\
format(st.median, st.firstq, st.thirdq)
title += "Mean:{0:.3f}|Std:{1:.3f}||N:{2})".\
format(st.mean, st.sd, st.size)
tbins = (0, ks_max, bins) if ks else (0, .6, 10)
digit = 2 if (ks_max * 1. / bins) < .1 else 1
stem_leaf_plot(columndata, *tbins, digit=digit, title=title)
if not opts.pdf:
return
components = opts.components
data = [x.ng_ks for x in data]
data = [x for x in data if ks_min <= x <= ks_max]
fig = plt.figure(1, (iopts.w, iopts.h))
ax = fig.add_axes([.12, .1, .8, .8])
kp = KsPlot(ax, ks_max, opts.bins, legendp=opts.legendp)
kp.add_data(data, components, fill=opts.fill, fitted=opts.fit)
kp.draw(title=opts.title) | python | def report(args):
'''
%prog report ksfile
generate a report given a Ks result file (as produced by synonymous_calc.py).
describe the median Ks, Ka values, as well as the distribution in stem-leaf plot
'''
from jcvi.utils.cbook import SummaryStats
from jcvi.graphics.histogram import stem_leaf_plot
p = OptionParser(report.__doc__)
p.add_option("--pdf", default=False, action="store_true",
help="Generate graphic output for the histogram [default: %default]")
p.add_option("--components", default=1, type="int",
help="Number of components to decompose peaks [default: %default]")
add_plot_options(p)
opts, args, iopts = p.set_image_options(args, figsize="5x5")
if len(args) != 1:
sys.exit(not p.print_help())
ks_file, = args
data = KsFile(ks_file)
ks_min = opts.vmin
ks_max = opts.vmax
bins = opts.bins
for f in fields.split(",")[1:]:
columndata = [getattr(x, f) for x in data]
ks = ("ks" in f)
if not ks:
continue
columndata = [x for x in columndata if ks_min <= x <= ks_max]
st = SummaryStats(columndata)
title = "{0} ({1}): ".format(descriptions[f], ks_file)
title += "Median:{0:.3f} (1Q:{1:.3f}|3Q:{2:.3f}||".\
format(st.median, st.firstq, st.thirdq)
title += "Mean:{0:.3f}|Std:{1:.3f}||N:{2})".\
format(st.mean, st.sd, st.size)
tbins = (0, ks_max, bins) if ks else (0, .6, 10)
digit = 2 if (ks_max * 1. / bins) < .1 else 1
stem_leaf_plot(columndata, *tbins, digit=digit, title=title)
if not opts.pdf:
return
components = opts.components
data = [x.ng_ks for x in data]
data = [x for x in data if ks_min <= x <= ks_max]
fig = plt.figure(1, (iopts.w, iopts.h))
ax = fig.add_axes([.12, .1, .8, .8])
kp = KsPlot(ax, ks_max, opts.bins, legendp=opts.legendp)
kp.add_data(data, components, fill=opts.fill, fitted=opts.fit)
kp.draw(title=opts.title) | [
"def",
"report",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"utils",
".",
"cbook",
"import",
"SummaryStats",
"from",
"jcvi",
".",
"graphics",
".",
"histogram",
"import",
"stem_leaf_plot",
"p",
"=",
"OptionParser",
"(",
"report",
".",
"__doc__",
")",
"p",
... | %prog report ksfile
generate a report given a Ks result file (as produced by synonymous_calc.py).
describe the median Ks, Ka values, as well as the distribution in stem-leaf plot | [
"%prog",
"report",
"ksfile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/ks.py#L978-L1035 | train | 200,861 |
tanghaibao/jcvi | jcvi/variation/impute.py | passthrough | def passthrough(args):
"""
%prog passthrough chrY.vcf chrY.new.vcf
Pass through Y and MT vcf.
"""
p = OptionParser(passthrough.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
vcffile, newvcffile = args
fp = open(vcffile)
fw = open(newvcffile, "w")
gg = ["0/0", "0/1", "1/1"]
for row in fp:
if row[0] == "#":
print(row.strip(), file=fw)
continue
v = VcfLine(row)
v.filter = "PASS"
v.format = "GT:GP"
probs = [0] * 3
probs[gg.index(v.genotype)] = 1
v.genotype = v.genotype.replace("/", "|") + \
":{0}".format(",".join("{0:.3f}".format(x) for x in probs))
print(v, file=fw)
fw.close() | python | def passthrough(args):
"""
%prog passthrough chrY.vcf chrY.new.vcf
Pass through Y and MT vcf.
"""
p = OptionParser(passthrough.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
vcffile, newvcffile = args
fp = open(vcffile)
fw = open(newvcffile, "w")
gg = ["0/0", "0/1", "1/1"]
for row in fp:
if row[0] == "#":
print(row.strip(), file=fw)
continue
v = VcfLine(row)
v.filter = "PASS"
v.format = "GT:GP"
probs = [0] * 3
probs[gg.index(v.genotype)] = 1
v.genotype = v.genotype.replace("/", "|") + \
":{0}".format(",".join("{0:.3f}".format(x) for x in probs))
print(v, file=fw)
fw.close() | [
"def",
"passthrough",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"passthrough",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"2",
":",
"sys",
".",
"exit",
... | %prog passthrough chrY.vcf chrY.new.vcf
Pass through Y and MT vcf. | [
"%prog",
"passthrough",
"chrY",
".",
"vcf",
"chrY",
".",
"new",
".",
"vcf"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/impute.py#L33-L62 | train | 200,862 |
tanghaibao/jcvi | jcvi/variation/impute.py | validate | def validate(args):
"""
%prog validate imputed.vcf withheld.vcf
Validate imputation against withheld variants.
"""
p = OptionParser(validate.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
imputed, withheld = args
register = {}
fp = open(withheld)
for row in fp:
if row[0] == "#":
continue
v = VcfLine(row)
register[(v.seqid, v.pos)] = v.genotype
logging.debug("Imported {0} records from `{1}`".\
format(len(register), withheld))
fp = must_open(imputed)
hit = concordant = 0
seen = set()
for row in fp:
if row[0] == "#":
continue
v = VcfLine(row)
chr, pos, genotype = v.seqid, v.pos, v.genotype
if (chr, pos) in seen:
continue
seen.add((chr, pos))
if (chr, pos) not in register:
continue
truth = register[(chr, pos)]
imputed = genotype.split(":")[0]
if "|" in imputed:
imputed = "/".join(sorted(genotype.split(":")[0].split("|")))
#probs = [float(x) for x in genotype.split(":")[-1].split(",")]
#imputed = max(zip(probs, ["0/0", "0/1", "1/1"]))[-1]
hit += 1
if truth == imputed:
concordant += 1
else:
print(row.strip(), "truth={0}".format(truth), file=sys.stderr)
logging.debug("Total concordant: {0}".\
format(percentage(concordant, hit))) | python | def validate(args):
"""
%prog validate imputed.vcf withheld.vcf
Validate imputation against withheld variants.
"""
p = OptionParser(validate.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
imputed, withheld = args
register = {}
fp = open(withheld)
for row in fp:
if row[0] == "#":
continue
v = VcfLine(row)
register[(v.seqid, v.pos)] = v.genotype
logging.debug("Imported {0} records from `{1}`".\
format(len(register), withheld))
fp = must_open(imputed)
hit = concordant = 0
seen = set()
for row in fp:
if row[0] == "#":
continue
v = VcfLine(row)
chr, pos, genotype = v.seqid, v.pos, v.genotype
if (chr, pos) in seen:
continue
seen.add((chr, pos))
if (chr, pos) not in register:
continue
truth = register[(chr, pos)]
imputed = genotype.split(":")[0]
if "|" in imputed:
imputed = "/".join(sorted(genotype.split(":")[0].split("|")))
#probs = [float(x) for x in genotype.split(":")[-1].split(",")]
#imputed = max(zip(probs, ["0/0", "0/1", "1/1"]))[-1]
hit += 1
if truth == imputed:
concordant += 1
else:
print(row.strip(), "truth={0}".format(truth), file=sys.stderr)
logging.debug("Total concordant: {0}".\
format(percentage(concordant, hit))) | [
"def",
"validate",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"validate",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"2",
":",
"sys",
".",
"exit",
"(",
... | %prog validate imputed.vcf withheld.vcf
Validate imputation against withheld variants. | [
"%prog",
"validate",
"imputed",
".",
"vcf",
"withheld",
".",
"vcf"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/impute.py#L65-L115 | train | 200,863 |
tanghaibao/jcvi | jcvi/variation/impute.py | minimac | def minimac(args):
"""
%prog batchminimac input.txt
Use MINIMAC3 to impute vcf on all chromosomes.
"""
p = OptionParser(minimac.__doc__)
p.set_home("shapeit")
p.set_home("minimac")
p.set_outfile()
p.set_chr()
p.set_ref()
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
txtfile, = args
ref = opts.ref
mm = MakeManager()
pf = txtfile.split(".")[0]
allrawvcf = []
alloutvcf = []
chrs = opts.chr.split(",")
for x in chrs:
px = CM[x]
chrvcf = pf + ".{0}.vcf".format(px)
if txtfile.endswith(".vcf"):
cmd = "vcftools --vcf {0} --chr {1}".format(txtfile, x)
cmd += " --out {0}.{1} --recode".format(pf, px)
cmd += " && mv {0}.{1}.recode.vcf {2}".format(pf, px, chrvcf)
else: # 23andme
cmd = "python -m jcvi.formats.vcf from23andme {0} {1}".format(txtfile, x)
cmd += " --ref {0}".format(ref)
mm.add(txtfile, chrvcf, cmd)
chrvcf_hg38 = pf + ".{0}.23andme.hg38.vcf".format(px)
minimac_liftover(mm, chrvcf, chrvcf_hg38, opts)
allrawvcf.append(chrvcf_hg38)
minimacvcf = "{0}.{1}.minimac.dose.vcf".format(pf, px)
if x == "X":
minimac_X(mm, x, chrvcf, opts)
elif x in ["Y", "MT"]:
cmd = "python -m jcvi.variation.impute passthrough"
cmd += " {0} {1}".format(chrvcf, minimacvcf)
mm.add(chrvcf, minimacvcf, cmd)
else:
minimac_autosome(mm, x, chrvcf, opts)
# keep the best line for multi-allelic markers
uniqvcf= "{0}.{1}.minimac.uniq.vcf".format(pf, px)
cmd = "python -m jcvi.formats.vcf uniq {0} > {1}".\
format(minimacvcf, uniqvcf)
mm.add(minimacvcf, uniqvcf, cmd)
minimacvcf_hg38 = "{0}.{1}.minimac.hg38.vcf".format(pf, px)
minimac_liftover(mm, uniqvcf, minimacvcf_hg38, opts)
alloutvcf.append(minimacvcf_hg38)
if len(allrawvcf) > 1:
rawhg38vcfgz = pf + ".all.23andme.hg38.vcf.gz"
cmd = "vcf-concat {0} | bgzip > {1}".format(" ".join(allrawvcf), rawhg38vcfgz)
mm.add(allrawvcf, rawhg38vcfgz, cmd)
if len(alloutvcf) > 1:
outhg38vcfgz = pf + ".all.minimac.hg38.vcf.gz"
cmd = "vcf-concat {0} | bgzip > {1}".format(" ".join(alloutvcf), outhg38vcfgz)
mm.add(alloutvcf, outhg38vcfgz, cmd)
mm.write() | python | def minimac(args):
"""
%prog batchminimac input.txt
Use MINIMAC3 to impute vcf on all chromosomes.
"""
p = OptionParser(minimac.__doc__)
p.set_home("shapeit")
p.set_home("minimac")
p.set_outfile()
p.set_chr()
p.set_ref()
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
txtfile, = args
ref = opts.ref
mm = MakeManager()
pf = txtfile.split(".")[0]
allrawvcf = []
alloutvcf = []
chrs = opts.chr.split(",")
for x in chrs:
px = CM[x]
chrvcf = pf + ".{0}.vcf".format(px)
if txtfile.endswith(".vcf"):
cmd = "vcftools --vcf {0} --chr {1}".format(txtfile, x)
cmd += " --out {0}.{1} --recode".format(pf, px)
cmd += " && mv {0}.{1}.recode.vcf {2}".format(pf, px, chrvcf)
else: # 23andme
cmd = "python -m jcvi.formats.vcf from23andme {0} {1}".format(txtfile, x)
cmd += " --ref {0}".format(ref)
mm.add(txtfile, chrvcf, cmd)
chrvcf_hg38 = pf + ".{0}.23andme.hg38.vcf".format(px)
minimac_liftover(mm, chrvcf, chrvcf_hg38, opts)
allrawvcf.append(chrvcf_hg38)
minimacvcf = "{0}.{1}.minimac.dose.vcf".format(pf, px)
if x == "X":
minimac_X(mm, x, chrvcf, opts)
elif x in ["Y", "MT"]:
cmd = "python -m jcvi.variation.impute passthrough"
cmd += " {0} {1}".format(chrvcf, minimacvcf)
mm.add(chrvcf, minimacvcf, cmd)
else:
minimac_autosome(mm, x, chrvcf, opts)
# keep the best line for multi-allelic markers
uniqvcf= "{0}.{1}.minimac.uniq.vcf".format(pf, px)
cmd = "python -m jcvi.formats.vcf uniq {0} > {1}".\
format(minimacvcf, uniqvcf)
mm.add(minimacvcf, uniqvcf, cmd)
minimacvcf_hg38 = "{0}.{1}.minimac.hg38.vcf".format(pf, px)
minimac_liftover(mm, uniqvcf, minimacvcf_hg38, opts)
alloutvcf.append(minimacvcf_hg38)
if len(allrawvcf) > 1:
rawhg38vcfgz = pf + ".all.23andme.hg38.vcf.gz"
cmd = "vcf-concat {0} | bgzip > {1}".format(" ".join(allrawvcf), rawhg38vcfgz)
mm.add(allrawvcf, rawhg38vcfgz, cmd)
if len(alloutvcf) > 1:
outhg38vcfgz = pf + ".all.minimac.hg38.vcf.gz"
cmd = "vcf-concat {0} | bgzip > {1}".format(" ".join(alloutvcf), outhg38vcfgz)
mm.add(alloutvcf, outhg38vcfgz, cmd)
mm.write() | [
"def",
"minimac",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"minimac",
".",
"__doc__",
")",
"p",
".",
"set_home",
"(",
"\"shapeit\"",
")",
"p",
".",
"set_home",
"(",
"\"minimac\"",
")",
"p",
".",
"set_outfile",
"(",
")",
"p",
".",
"set_ch... | %prog batchminimac input.txt
Use MINIMAC3 to impute vcf on all chromosomes. | [
"%prog",
"batchminimac",
"input",
".",
"txt"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/impute.py#L118-L189 | train | 200,864 |
tanghaibao/jcvi | jcvi/variation/impute.py | beagle | def beagle(args):
"""
%prog beagle input.vcf 1
Use BEAGLE4.1 to impute vcf on chromosome 1.
"""
p = OptionParser(beagle.__doc__)
p.set_home("beagle")
p.set_ref()
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
vcffile, chr = args
pf = vcffile.rsplit(".", 1)[0]
outpf = pf + ".beagle"
outfile = outpf + ".vcf.gz"
mm = MakeManager()
beagle_cmd = opts.beagle_home
kg = op.join(opts.ref, "1000GP_Phase3")
cmd = beagle_cmd + " gt={0}".format(vcffile)
cmd += " ref={0}/chr{1}.1kg.phase3.v5a.bref".format(kg, chr)
cmd += " map={0}/plink.chr{1}.GRCh37.map".format(kg, chr)
cmd += " out={0}".format(outpf)
cmd += " nthreads=16 gprobs=true"
mm.add(vcffile, outfile, cmd)
mm.write() | python | def beagle(args):
"""
%prog beagle input.vcf 1
Use BEAGLE4.1 to impute vcf on chromosome 1.
"""
p = OptionParser(beagle.__doc__)
p.set_home("beagle")
p.set_ref()
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
vcffile, chr = args
pf = vcffile.rsplit(".", 1)[0]
outpf = pf + ".beagle"
outfile = outpf + ".vcf.gz"
mm = MakeManager()
beagle_cmd = opts.beagle_home
kg = op.join(opts.ref, "1000GP_Phase3")
cmd = beagle_cmd + " gt={0}".format(vcffile)
cmd += " ref={0}/chr{1}.1kg.phase3.v5a.bref".format(kg, chr)
cmd += " map={0}/plink.chr{1}.GRCh37.map".format(kg, chr)
cmd += " out={0}".format(outpf)
cmd += " nthreads=16 gprobs=true"
mm.add(vcffile, outfile, cmd)
mm.write() | [
"def",
"beagle",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"beagle",
".",
"__doc__",
")",
"p",
".",
"set_home",
"(",
"\"beagle\"",
")",
"p",
".",
"set_ref",
"(",
")",
"p",
".",
"set_cpus",
"(",
")",
"opts",
",",
"args",
"=",
"p",
".",... | %prog beagle input.vcf 1
Use BEAGLE4.1 to impute vcf on chromosome 1. | [
"%prog",
"beagle",
"input",
".",
"vcf",
"1"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/impute.py#L257-L287 | train | 200,865 |
tanghaibao/jcvi | jcvi/variation/impute.py | impute | def impute(args):
"""
%prog impute input.vcf hs37d5.fa 1
Use IMPUTE2 to impute vcf on chromosome 1.
"""
from pyfaidx import Fasta
p = OptionParser(impute.__doc__)
p.set_home("shapeit")
p.set_home("impute")
p.set_ref()
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
vcffile, fastafile, chr = args
mm = MakeManager()
pf = vcffile.rsplit(".", 1)[0]
hapsfile = pf + ".haps"
kg = op.join(opts.ref, "1000GP_Phase3")
shapeit_phasing(mm, chr, vcffile, opts)
fasta = Fasta(fastafile)
size = len(fasta[chr])
binsize = 5000000
bins = size / binsize # 5Mb bins
if size % binsize:
bins += 1
impute_cmd = op.join(opts.impute_home, "impute2")
chunks = []
for x in xrange(bins + 1):
chunk_start = x * binsize + 1
chunk_end = min(chunk_start + binsize - 1, size)
outfile = pf + ".chunk{0:02d}.impute2".format(x)
mapfile = "{0}/genetic_map_chr{1}_combined_b37.txt".format(kg, chr)
rpf = "{0}/1000GP_Phase3_chr{1}".format(kg, chr)
cmd = impute_cmd + " -m {0}".format(mapfile)
cmd += " -known_haps_g {0}".format(hapsfile)
cmd += " -h {0}.hap.gz -l {0}.legend.gz".format(rpf)
cmd += " -Ne 20000 -int {0} {1}".format(chunk_start, chunk_end)
cmd += " -o {0} -allow_large_regions -seed 367946".format(outfile)
cmd += " && touch {0}".format(outfile)
mm.add(hapsfile, outfile, cmd)
chunks.append(outfile)
# Combine all the files
imputefile = pf + ".impute2"
cmd = "cat {0} > {1}".format(" ".join(chunks), imputefile)
mm.add(chunks, imputefile, cmd)
# Convert to vcf
vcffile = pf + ".impute2.vcf"
cmd = "python -m jcvi.formats.vcf fromimpute2 {0} {1} {2} > {3}".\
format(imputefile, fastafile, chr, vcffile)
mm.add(imputefile, vcffile, cmd)
mm.write() | python | def impute(args):
"""
%prog impute input.vcf hs37d5.fa 1
Use IMPUTE2 to impute vcf on chromosome 1.
"""
from pyfaidx import Fasta
p = OptionParser(impute.__doc__)
p.set_home("shapeit")
p.set_home("impute")
p.set_ref()
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
vcffile, fastafile, chr = args
mm = MakeManager()
pf = vcffile.rsplit(".", 1)[0]
hapsfile = pf + ".haps"
kg = op.join(opts.ref, "1000GP_Phase3")
shapeit_phasing(mm, chr, vcffile, opts)
fasta = Fasta(fastafile)
size = len(fasta[chr])
binsize = 5000000
bins = size / binsize # 5Mb bins
if size % binsize:
bins += 1
impute_cmd = op.join(opts.impute_home, "impute2")
chunks = []
for x in xrange(bins + 1):
chunk_start = x * binsize + 1
chunk_end = min(chunk_start + binsize - 1, size)
outfile = pf + ".chunk{0:02d}.impute2".format(x)
mapfile = "{0}/genetic_map_chr{1}_combined_b37.txt".format(kg, chr)
rpf = "{0}/1000GP_Phase3_chr{1}".format(kg, chr)
cmd = impute_cmd + " -m {0}".format(mapfile)
cmd += " -known_haps_g {0}".format(hapsfile)
cmd += " -h {0}.hap.gz -l {0}.legend.gz".format(rpf)
cmd += " -Ne 20000 -int {0} {1}".format(chunk_start, chunk_end)
cmd += " -o {0} -allow_large_regions -seed 367946".format(outfile)
cmd += " && touch {0}".format(outfile)
mm.add(hapsfile, outfile, cmd)
chunks.append(outfile)
# Combine all the files
imputefile = pf + ".impute2"
cmd = "cat {0} > {1}".format(" ".join(chunks), imputefile)
mm.add(chunks, imputefile, cmd)
# Convert to vcf
vcffile = pf + ".impute2.vcf"
cmd = "python -m jcvi.formats.vcf fromimpute2 {0} {1} {2} > {3}".\
format(imputefile, fastafile, chr, vcffile)
mm.add(imputefile, vcffile, cmd)
mm.write() | [
"def",
"impute",
"(",
"args",
")",
":",
"from",
"pyfaidx",
"import",
"Fasta",
"p",
"=",
"OptionParser",
"(",
"impute",
".",
"__doc__",
")",
"p",
".",
"set_home",
"(",
"\"shapeit\"",
")",
"p",
".",
"set_home",
"(",
"\"impute\"",
")",
"p",
".",
"set_ref"... | %prog impute input.vcf hs37d5.fa 1
Use IMPUTE2 to impute vcf on chromosome 1. | [
"%prog",
"impute",
"input",
".",
"vcf",
"hs37d5",
".",
"fa",
"1"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/impute.py#L321-L379 | train | 200,866 |
tanghaibao/jcvi | jcvi/annotation/stats.py | summary | def summary(args):
"""
%prog summary gffile fastafile
Print summary stats, including:
- Gene/Exon/Intron
- Number
- Average size (bp)
- Median size (bp)
- Total length (Mb)
- % of genome
- % GC
"""
p = OptionParser(summary.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
gff_file, ref = args
s = Fasta(ref)
g = make_index(gff_file)
geneseqs, exonseqs, intronseqs = [], [], [] # Calc % GC
for f in g.features_of_type("gene"):
fid = f.id
fseq = s.sequence({'chr': f.chrom, 'start': f.start, 'stop': f.stop})
geneseqs.append(fseq)
exons = set((c.chrom, c.start, c.stop) for c in g.children(fid, 2) \
if c.featuretype == "exon")
exons = list(exons)
for chrom, start, stop in exons:
fseq = s.sequence({'chr': chrom, 'start': start, 'stop': stop})
exonseqs.append(fseq)
introns = range_interleave(exons)
for chrom, start, stop in introns:
fseq = s.sequence({'chr': chrom, 'start': start, 'stop': stop})
intronseqs.append(fseq)
r = {} # Report
for t, tseqs in zip(("Gene", "Exon", "Intron"), (geneseqs, exonseqs, intronseqs)):
tsizes = [len(x) for x in tseqs]
tsummary = SummaryStats(tsizes, dtype="int")
r[t, "Number"] = tsummary.size
r[t, "Average size (bp)"] = tsummary.mean
r[t, "Median size (bp)"] = tsummary.median
r[t, "Total length (Mb)"] = human_size(tsummary.sum, precision=0, target="Mb")
r[t, "% of genome"] = percentage(tsummary.sum, s.totalsize, precision=0, mode=-1)
r[t, "% GC"] = gc(tseqs)
print(tabulate(r), file=sys.stderr) | python | def summary(args):
"""
%prog summary gffile fastafile
Print summary stats, including:
- Gene/Exon/Intron
- Number
- Average size (bp)
- Median size (bp)
- Total length (Mb)
- % of genome
- % GC
"""
p = OptionParser(summary.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
gff_file, ref = args
s = Fasta(ref)
g = make_index(gff_file)
geneseqs, exonseqs, intronseqs = [], [], [] # Calc % GC
for f in g.features_of_type("gene"):
fid = f.id
fseq = s.sequence({'chr': f.chrom, 'start': f.start, 'stop': f.stop})
geneseqs.append(fseq)
exons = set((c.chrom, c.start, c.stop) for c in g.children(fid, 2) \
if c.featuretype == "exon")
exons = list(exons)
for chrom, start, stop in exons:
fseq = s.sequence({'chr': chrom, 'start': start, 'stop': stop})
exonseqs.append(fseq)
introns = range_interleave(exons)
for chrom, start, stop in introns:
fseq = s.sequence({'chr': chrom, 'start': start, 'stop': stop})
intronseqs.append(fseq)
r = {} # Report
for t, tseqs in zip(("Gene", "Exon", "Intron"), (geneseqs, exonseqs, intronseqs)):
tsizes = [len(x) for x in tseqs]
tsummary = SummaryStats(tsizes, dtype="int")
r[t, "Number"] = tsummary.size
r[t, "Average size (bp)"] = tsummary.mean
r[t, "Median size (bp)"] = tsummary.median
r[t, "Total length (Mb)"] = human_size(tsummary.sum, precision=0, target="Mb")
r[t, "% of genome"] = percentage(tsummary.sum, s.totalsize, precision=0, mode=-1)
r[t, "% GC"] = gc(tseqs)
print(tabulate(r), file=sys.stderr) | [
"def",
"summary",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"summary",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"2",
":",
"sys",
".",
"exit",
"(",
... | %prog summary gffile fastafile
Print summary stats, including:
- Gene/Exon/Intron
- Number
- Average size (bp)
- Median size (bp)
- Total length (Mb)
- % of genome
- % GC | [
"%prog",
"summary",
"gffile",
"fastafile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/annotation/stats.py#L69-L118 | train | 200,867 |
tanghaibao/jcvi | jcvi/apps/r.py | RTemplate.run | def run(self, clean=True):
"""
Create a temporary file and run it
"""
template = self.template
parameters = self.parameters
# write to a temporary R script
fw = must_open("tmp", "w")
path = fw.name
fw.write(template.safe_substitute(**parameters))
fw.close()
sh("Rscript %s" % path)
if clean:
os.remove(path)
# I have no idea why using ggsave, there is one extra image
# generated, but here I remove it
rplotspdf = "Rplots.pdf"
if op.exists(rplotspdf):
os.remove(rplotspdf) | python | def run(self, clean=True):
"""
Create a temporary file and run it
"""
template = self.template
parameters = self.parameters
# write to a temporary R script
fw = must_open("tmp", "w")
path = fw.name
fw.write(template.safe_substitute(**parameters))
fw.close()
sh("Rscript %s" % path)
if clean:
os.remove(path)
# I have no idea why using ggsave, there is one extra image
# generated, but here I remove it
rplotspdf = "Rplots.pdf"
if op.exists(rplotspdf):
os.remove(rplotspdf) | [
"def",
"run",
"(",
"self",
",",
"clean",
"=",
"True",
")",
":",
"template",
"=",
"self",
".",
"template",
"parameters",
"=",
"self",
".",
"parameters",
"# write to a temporary R script",
"fw",
"=",
"must_open",
"(",
"\"tmp\"",
",",
"\"w\"",
")",
"path",
"=... | Create a temporary file and run it | [
"Create",
"a",
"temporary",
"file",
"and",
"run",
"it"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/r.py#L24-L44 | train | 200,868 |
tanghaibao/jcvi | jcvi/algorithms/graph.py | transitive_reduction | def transitive_reduction(G):
"""
Returns a transitive reduction of a graph. The original graph
is not modified.
A transitive reduction H of G has a path from x to y if and
only if there was a path from x to y in G. Deleting any edge
of H destroys this property. A transitive reduction is not
unique in general. A transitive reduction has the same
transitive closure as the original graph.
A transitive reduction of a complete graph is a tree. A
transitive reduction of a tree is itself.
>>> G = nx.DiGraph([(1, 2), (1, 3), (2, 3), (2, 4), (3, 4)])
>>> H = transitive_reduction(G)
>>> H.edges()
[(1, 2), (2, 3), (3, 4)]
"""
H = G.copy()
for a, b, w in G.edges_iter(data=True):
# Try deleting the edge, see if we still have a path
# between the vertices
H.remove_edge(a, b)
if not nx.has_path(H, a, b): # we shouldn't have deleted it
H.add_edge(a, b, w)
return H | python | def transitive_reduction(G):
"""
Returns a transitive reduction of a graph. The original graph
is not modified.
A transitive reduction H of G has a path from x to y if and
only if there was a path from x to y in G. Deleting any edge
of H destroys this property. A transitive reduction is not
unique in general. A transitive reduction has the same
transitive closure as the original graph.
A transitive reduction of a complete graph is a tree. A
transitive reduction of a tree is itself.
>>> G = nx.DiGraph([(1, 2), (1, 3), (2, 3), (2, 4), (3, 4)])
>>> H = transitive_reduction(G)
>>> H.edges()
[(1, 2), (2, 3), (3, 4)]
"""
H = G.copy()
for a, b, w in G.edges_iter(data=True):
# Try deleting the edge, see if we still have a path
# between the vertices
H.remove_edge(a, b)
if not nx.has_path(H, a, b): # we shouldn't have deleted it
H.add_edge(a, b, w)
return H | [
"def",
"transitive_reduction",
"(",
"G",
")",
":",
"H",
"=",
"G",
".",
"copy",
"(",
")",
"for",
"a",
",",
"b",
",",
"w",
"in",
"G",
".",
"edges_iter",
"(",
"data",
"=",
"True",
")",
":",
"# Try deleting the edge, see if we still have a path",
"# between th... | Returns a transitive reduction of a graph. The original graph
is not modified.
A transitive reduction H of G has a path from x to y if and
only if there was a path from x to y in G. Deleting any edge
of H destroys this property. A transitive reduction is not
unique in general. A transitive reduction has the same
transitive closure as the original graph.
A transitive reduction of a complete graph is a tree. A
transitive reduction of a tree is itself.
>>> G = nx.DiGraph([(1, 2), (1, 3), (2, 3), (2, 4), (3, 4)])
>>> H = transitive_reduction(G)
>>> H.edges()
[(1, 2), (2, 3), (3, 4)] | [
"Returns",
"a",
"transitive",
"reduction",
"of",
"a",
"graph",
".",
"The",
"original",
"graph",
"is",
"not",
"modified",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/algorithms/graph.py#L411-L437 | train | 200,869 |
tanghaibao/jcvi | jcvi/algorithms/graph.py | merge_paths | def merge_paths(paths, weights=None):
"""
Zip together sorted lists.
>>> paths = [[1, 2, 3], [1, 3, 4], [2, 4, 5]]
>>> G = merge_paths(paths)
>>> nx.topological_sort(G)
[1, 2, 3, 4, 5]
>>> paths = [[1, 2, 3, 4], [1, 2, 3, 2, 4]]
>>> G = merge_paths(paths, weights=(1, 2))
>>> nx.topological_sort(G)
[1, 2, 3, 4]
"""
G = make_paths(paths, weights=weights)
G = reduce_paths(G)
return G | python | def merge_paths(paths, weights=None):
"""
Zip together sorted lists.
>>> paths = [[1, 2, 3], [1, 3, 4], [2, 4, 5]]
>>> G = merge_paths(paths)
>>> nx.topological_sort(G)
[1, 2, 3, 4, 5]
>>> paths = [[1, 2, 3, 4], [1, 2, 3, 2, 4]]
>>> G = merge_paths(paths, weights=(1, 2))
>>> nx.topological_sort(G)
[1, 2, 3, 4]
"""
G = make_paths(paths, weights=weights)
G = reduce_paths(G)
return G | [
"def",
"merge_paths",
"(",
"paths",
",",
"weights",
"=",
"None",
")",
":",
"G",
"=",
"make_paths",
"(",
"paths",
",",
"weights",
"=",
"weights",
")",
"G",
"=",
"reduce_paths",
"(",
"G",
")",
"return",
"G"
] | Zip together sorted lists.
>>> paths = [[1, 2, 3], [1, 3, 4], [2, 4, 5]]
>>> G = merge_paths(paths)
>>> nx.topological_sort(G)
[1, 2, 3, 4, 5]
>>> paths = [[1, 2, 3, 4], [1, 2, 3, 2, 4]]
>>> G = merge_paths(paths, weights=(1, 2))
>>> nx.topological_sort(G)
[1, 2, 3, 4] | [
"Zip",
"together",
"sorted",
"lists",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/algorithms/graph.py#L440-L455 | train | 200,870 |
tanghaibao/jcvi | jcvi/algorithms/graph.py | BiNode.get_next | def get_next(self, tag="<"):
"""
This function is tricky and took me a while to figure out.
The tag specifies the direction where the current edge came from.
tag ntag
---> V >----> U
cur next
This means the next vertex should follow the outs since this tag is
inward '<'. Check if there are multiple branches if len(L) == 1, and
also check if the next it finds has multiple incoming edges though if
len(B) == 1.
"""
next, ntag = None, None
L = self.outs if tag == "<" else self.ins
if len(L) == 1:
e, = L
if e.v1.v == self.v:
next, ntag = e.v2, e.o2
ntag = "<" if ntag == ">" else ">" # Flip tag if on other end
else:
next, ntag = e.v1, e.o1
if next: # Validate the next vertex
B = next.ins if ntag == "<" else next.outs
if len(B) > 1:
return None, None
return next, ntag | python | def get_next(self, tag="<"):
"""
This function is tricky and took me a while to figure out.
The tag specifies the direction where the current edge came from.
tag ntag
---> V >----> U
cur next
This means the next vertex should follow the outs since this tag is
inward '<'. Check if there are multiple branches if len(L) == 1, and
also check if the next it finds has multiple incoming edges though if
len(B) == 1.
"""
next, ntag = None, None
L = self.outs if tag == "<" else self.ins
if len(L) == 1:
e, = L
if e.v1.v == self.v:
next, ntag = e.v2, e.o2
ntag = "<" if ntag == ">" else ">" # Flip tag if on other end
else:
next, ntag = e.v1, e.o1
if next: # Validate the next vertex
B = next.ins if ntag == "<" else next.outs
if len(B) > 1:
return None, None
return next, ntag | [
"def",
"get_next",
"(",
"self",
",",
"tag",
"=",
"\"<\"",
")",
":",
"next",
",",
"ntag",
"=",
"None",
",",
"None",
"L",
"=",
"self",
".",
"outs",
"if",
"tag",
"==",
"\"<\"",
"else",
"self",
".",
"ins",
"if",
"len",
"(",
"L",
")",
"==",
"1",
"... | This function is tricky and took me a while to figure out.
The tag specifies the direction where the current edge came from.
tag ntag
---> V >----> U
cur next
This means the next vertex should follow the outs since this tag is
inward '<'. Check if there are multiple branches if len(L) == 1, and
also check if the next it finds has multiple incoming edges though if
len(B) == 1. | [
"This",
"function",
"is",
"tricky",
"and",
"took",
"me",
"a",
"while",
"to",
"figure",
"out",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/algorithms/graph.py#L34-L66 | train | 200,871 |
tanghaibao/jcvi | jcvi/assembly/postprocess.py | dust2bed | def dust2bed(args):
"""
%prog dust2bed fastafile
Use dustmasker to find low-complexity regions (LCRs) in the genome.
"""
from jcvi.formats.base import read_block
p = OptionParser(dust2bed.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
fastafile, = args
interval = fastafile + ".iv"
if need_update(fastafile, interval):
cmd = "dustmasker -in {0}".format(fastafile)
sh(cmd, outfile=interval)
fp = open(interval)
bedfile = fastafile.rsplit(".", 1)[0] + ".dust.bed"
fw = must_open(bedfile, "w")
nlines = 0
nbases = 0
for header, block in read_block(fp, ">"):
header = header.strip(">")
for b in block:
start, end = b.split(" - ")
start, end = int(start), int(end)
print("\t".join(str(x) for x in (header, start, end)), file=fw)
nlines += 1
nbases += end - start
logging.debug("A total of {0} DUST intervals ({1} bp) exported to `{2}`".\
format(nlines, nbases, bedfile)) | python | def dust2bed(args):
"""
%prog dust2bed fastafile
Use dustmasker to find low-complexity regions (LCRs) in the genome.
"""
from jcvi.formats.base import read_block
p = OptionParser(dust2bed.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
fastafile, = args
interval = fastafile + ".iv"
if need_update(fastafile, interval):
cmd = "dustmasker -in {0}".format(fastafile)
sh(cmd, outfile=interval)
fp = open(interval)
bedfile = fastafile.rsplit(".", 1)[0] + ".dust.bed"
fw = must_open(bedfile, "w")
nlines = 0
nbases = 0
for header, block in read_block(fp, ">"):
header = header.strip(">")
for b in block:
start, end = b.split(" - ")
start, end = int(start), int(end)
print("\t".join(str(x) for x in (header, start, end)), file=fw)
nlines += 1
nbases += end - start
logging.debug("A total of {0} DUST intervals ({1} bp) exported to `{2}`".\
format(nlines, nbases, bedfile)) | [
"def",
"dust2bed",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"base",
"import",
"read_block",
"p",
"=",
"OptionParser",
"(",
"dust2bed",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"... | %prog dust2bed fastafile
Use dustmasker to find low-complexity regions (LCRs) in the genome. | [
"%prog",
"dust2bed",
"fastafile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/postprocess.py#L50-L84 | train | 200,872 |
tanghaibao/jcvi | jcvi/assembly/postprocess.py | fasta2bed | def fasta2bed(fastafile):
"""
Alternative BED generation from FASTA file. Used for sanity check.
"""
dustfasta = fastafile.rsplit(".", 1)[0] + ".dust.fasta"
for name, seq in parse_fasta(dustfasta):
for islower, ss in groupby(enumerate(seq), key=lambda x: x[-1].islower()):
if not islower:
continue
ss = list(ss)
ms, mn = min(ss)
xs, xn = max(ss)
print("\t".join(str(x) for x in (name, ms, xs))) | python | def fasta2bed(fastafile):
"""
Alternative BED generation from FASTA file. Used for sanity check.
"""
dustfasta = fastafile.rsplit(".", 1)[0] + ".dust.fasta"
for name, seq in parse_fasta(dustfasta):
for islower, ss in groupby(enumerate(seq), key=lambda x: x[-1].islower()):
if not islower:
continue
ss = list(ss)
ms, mn = min(ss)
xs, xn = max(ss)
print("\t".join(str(x) for x in (name, ms, xs))) | [
"def",
"fasta2bed",
"(",
"fastafile",
")",
":",
"dustfasta",
"=",
"fastafile",
".",
"rsplit",
"(",
"\".\"",
",",
"1",
")",
"[",
"0",
"]",
"+",
"\".dust.fasta\"",
"for",
"name",
",",
"seq",
"in",
"parse_fasta",
"(",
"dustfasta",
")",
":",
"for",
"islowe... | Alternative BED generation from FASTA file. Used for sanity check. | [
"Alternative",
"BED",
"generation",
"from",
"FASTA",
"file",
".",
"Used",
"for",
"sanity",
"check",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/postprocess.py#L87-L99 | train | 200,873 |
tanghaibao/jcvi | jcvi/assembly/postprocess.py | circular | def circular(args):
"""
%prog circular fastafile startpos
Make circular genome, startpos is the place to start the sequence. This can
be determined by mapping to a reference. Self overlaps are then resolved.
Startpos is 1-based.
"""
from jcvi.assembly.goldenpath import overlap
p = OptionParser(circular.__doc__)
p.add_option("--flip", default=False, action="store_true",
help="Reverse complement the sequence")
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
fastafile, startpos = args
startpos = int(startpos)
key, seq = next(parse_fasta(fastafile))
aseq = seq[startpos:]
bseq = seq[:startpos]
aseqfile, bseqfile = "a.seq", "b.seq"
for f, s in zip((aseqfile, bseqfile), (aseq, bseq)):
fw = must_open(f, "w")
print(">{0}\n{1}".format(f, s), file=fw)
fw.close()
o = overlap([aseqfile, bseqfile])
seq = aseq[:o.qstop] + bseq[o.sstop:]
seq = Seq(seq)
if opts.flip:
seq = seq.reverse_complement()
for f in (aseqfile, bseqfile):
os.remove(f)
fw = must_open(opts.outfile, "w")
rec = SeqRecord(seq, id=key, description="")
SeqIO.write([rec], fw, "fasta")
fw.close() | python | def circular(args):
"""
%prog circular fastafile startpos
Make circular genome, startpos is the place to start the sequence. This can
be determined by mapping to a reference. Self overlaps are then resolved.
Startpos is 1-based.
"""
from jcvi.assembly.goldenpath import overlap
p = OptionParser(circular.__doc__)
p.add_option("--flip", default=False, action="store_true",
help="Reverse complement the sequence")
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
fastafile, startpos = args
startpos = int(startpos)
key, seq = next(parse_fasta(fastafile))
aseq = seq[startpos:]
bseq = seq[:startpos]
aseqfile, bseqfile = "a.seq", "b.seq"
for f, s in zip((aseqfile, bseqfile), (aseq, bseq)):
fw = must_open(f, "w")
print(">{0}\n{1}".format(f, s), file=fw)
fw.close()
o = overlap([aseqfile, bseqfile])
seq = aseq[:o.qstop] + bseq[o.sstop:]
seq = Seq(seq)
if opts.flip:
seq = seq.reverse_complement()
for f in (aseqfile, bseqfile):
os.remove(f)
fw = must_open(opts.outfile, "w")
rec = SeqRecord(seq, id=key, description="")
SeqIO.write([rec], fw, "fasta")
fw.close() | [
"def",
"circular",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"assembly",
".",
"goldenpath",
"import",
"overlap",
"p",
"=",
"OptionParser",
"(",
"circular",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--flip\"",
",",
"default",
"=",
"False",
",... | %prog circular fastafile startpos
Make circular genome, startpos is the place to start the sequence. This can
be determined by mapping to a reference. Self overlaps are then resolved.
Startpos is 1-based. | [
"%prog",
"circular",
"fastafile",
"startpos"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/postprocess.py#L102-L146 | train | 200,874 |
tanghaibao/jcvi | jcvi/assembly/postprocess.py | dust | def dust(args):
"""
%prog dust assembly.fasta
Remove low-complexity contigs within assembly.
"""
p = OptionParser(dust.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
fastafile, = args
dustfastafile = fastafile.rsplit(".", 1)[0] + ".dust.fasta"
if need_update(fastafile, dustfastafile):
cmd = "dustmasker -in {0}".format(fastafile)
cmd += " -out {0} -outfmt fasta".format(dustfastafile)
sh(cmd)
for name, seq in parse_fasta(dustfastafile):
nlow = sum(1 for x in seq if x in "acgtnN")
pctlow = nlow * 100. / len(seq)
if pctlow < 98:
continue
#print "{0}\t{1:.1f}".format(name, pctlow)
print(name) | python | def dust(args):
"""
%prog dust assembly.fasta
Remove low-complexity contigs within assembly.
"""
p = OptionParser(dust.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
fastafile, = args
dustfastafile = fastafile.rsplit(".", 1)[0] + ".dust.fasta"
if need_update(fastafile, dustfastafile):
cmd = "dustmasker -in {0}".format(fastafile)
cmd += " -out {0} -outfmt fasta".format(dustfastafile)
sh(cmd)
for name, seq in parse_fasta(dustfastafile):
nlow = sum(1 for x in seq if x in "acgtnN")
pctlow = nlow * 100. / len(seq)
if pctlow < 98:
continue
#print "{0}\t{1:.1f}".format(name, pctlow)
print(name) | [
"def",
"dust",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"dust",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
":",
"sys",
".",
"exit",
"(",
"not",... | %prog dust assembly.fasta
Remove low-complexity contigs within assembly. | [
"%prog",
"dust",
"assembly",
".",
"fasta"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/postprocess.py#L149-L174 | train | 200,875 |
tanghaibao/jcvi | jcvi/assembly/postprocess.py | dedup | def dedup(args):
"""
%prog dedup assembly.assembly.blast assembly.fasta
Remove duplicate contigs within assembly.
"""
from jcvi.formats.blast import BlastLine
p = OptionParser(dedup.__doc__)
p.set_align(pctid=0, pctcov=98)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
blastfile, fastafile = args
cov = opts.pctcov / 100.
sizes = Sizes(fastafile).mapping
fp = open(blastfile)
removed = set()
for row in fp:
b = BlastLine(row)
query, subject = b.query, b.subject
if query == subject:
continue
qsize, ssize = sizes[query], sizes[subject]
qspan = abs(b.qstop - b.qstart)
if qspan < qsize * cov:
continue
if (qsize, query) < (ssize, subject):
removed.add(query)
print("\n".join(sorted(removed))) | python | def dedup(args):
"""
%prog dedup assembly.assembly.blast assembly.fasta
Remove duplicate contigs within assembly.
"""
from jcvi.formats.blast import BlastLine
p = OptionParser(dedup.__doc__)
p.set_align(pctid=0, pctcov=98)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
blastfile, fastafile = args
cov = opts.pctcov / 100.
sizes = Sizes(fastafile).mapping
fp = open(blastfile)
removed = set()
for row in fp:
b = BlastLine(row)
query, subject = b.query, b.subject
if query == subject:
continue
qsize, ssize = sizes[query], sizes[subject]
qspan = abs(b.qstop - b.qstart)
if qspan < qsize * cov:
continue
if (qsize, query) < (ssize, subject):
removed.add(query)
print("\n".join(sorted(removed))) | [
"def",
"dedup",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"blast",
"import",
"BlastLine",
"p",
"=",
"OptionParser",
"(",
"dedup",
".",
"__doc__",
")",
"p",
".",
"set_align",
"(",
"pctid",
"=",
"0",
",",
"pctcov",
"=",
"98",
")",
"... | %prog dedup assembly.assembly.blast assembly.fasta
Remove duplicate contigs within assembly. | [
"%prog",
"dedup",
"assembly",
".",
"assembly",
".",
"blast",
"assembly",
".",
"fasta"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/postprocess.py#L177-L209 | train | 200,876 |
tanghaibao/jcvi | jcvi/assembly/postprocess.py | build | def build(args):
"""
%prog build current.fasta Bacteria_Virus.fasta prefix
Build assembly files after a set of clean-ups:
1. Use cdhit (100%) to remove duplicate scaffolds
2. Screen against the bacteria and virus database (remove scaffolds 95% id, 50% cov)
3. Mask matches to UniVec_Core
4. Sort by decreasing scaffold sizes
5. Rename the scaffolds sequentially
6. Build the contigs by splitting scaffolds at gaps
7. Rename the contigs sequentially
"""
from jcvi.apps.cdhit import deduplicate
from jcvi.apps.vecscreen import mask
from jcvi.formats.fasta import sort
p = OptionParser(build.__doc__)
p.add_option("--nodedup", default=False, action="store_true",
help="Do not deduplicate [default: deduplicate]")
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
fastafile, bacteria, pf = args
dd = deduplicate([fastafile, "--pctid=100"]) \
if not opts.nodedup else fastafile
screenfasta = screen([dd, bacteria])
tidyfasta = mask([screenfasta])
sortedfasta = sort([tidyfasta, "--sizes"])
scaffoldfasta = pf + ".assembly.fasta"
format([sortedfasta, scaffoldfasta, "--prefix=scaffold_", "--sequential"])
gapsplitfasta = pf + ".gapSplit.fasta"
cmd = "gapSplit -minGap=10 {0} {1}".format(scaffoldfasta, gapsplitfasta)
sh(cmd)
contigsfasta = pf + ".contigs.fasta"
format([gapsplitfasta, contigsfasta, "--prefix=contig_", "--sequential"]) | python | def build(args):
"""
%prog build current.fasta Bacteria_Virus.fasta prefix
Build assembly files after a set of clean-ups:
1. Use cdhit (100%) to remove duplicate scaffolds
2. Screen against the bacteria and virus database (remove scaffolds 95% id, 50% cov)
3. Mask matches to UniVec_Core
4. Sort by decreasing scaffold sizes
5. Rename the scaffolds sequentially
6. Build the contigs by splitting scaffolds at gaps
7. Rename the contigs sequentially
"""
from jcvi.apps.cdhit import deduplicate
from jcvi.apps.vecscreen import mask
from jcvi.formats.fasta import sort
p = OptionParser(build.__doc__)
p.add_option("--nodedup", default=False, action="store_true",
help="Do not deduplicate [default: deduplicate]")
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
fastafile, bacteria, pf = args
dd = deduplicate([fastafile, "--pctid=100"]) \
if not opts.nodedup else fastafile
screenfasta = screen([dd, bacteria])
tidyfasta = mask([screenfasta])
sortedfasta = sort([tidyfasta, "--sizes"])
scaffoldfasta = pf + ".assembly.fasta"
format([sortedfasta, scaffoldfasta, "--prefix=scaffold_", "--sequential"])
gapsplitfasta = pf + ".gapSplit.fasta"
cmd = "gapSplit -minGap=10 {0} {1}".format(scaffoldfasta, gapsplitfasta)
sh(cmd)
contigsfasta = pf + ".contigs.fasta"
format([gapsplitfasta, contigsfasta, "--prefix=contig_", "--sequential"]) | [
"def",
"build",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"apps",
".",
"cdhit",
"import",
"deduplicate",
"from",
"jcvi",
".",
"apps",
".",
"vecscreen",
"import",
"mask",
"from",
"jcvi",
".",
"formats",
".",
"fasta",
"import",
"sort",
"p",
"=",
"Optio... | %prog build current.fasta Bacteria_Virus.fasta prefix
Build assembly files after a set of clean-ups:
1. Use cdhit (100%) to remove duplicate scaffolds
2. Screen against the bacteria and virus database (remove scaffolds 95% id, 50% cov)
3. Mask matches to UniVec_Core
4. Sort by decreasing scaffold sizes
5. Rename the scaffolds sequentially
6. Build the contigs by splitting scaffolds at gaps
7. Rename the contigs sequentially | [
"%prog",
"build",
"current",
".",
"fasta",
"Bacteria_Virus",
".",
"fasta",
"prefix"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/postprocess.py#L212-L249 | train | 200,877 |
tanghaibao/jcvi | jcvi/assembly/postprocess.py | screen | def screen(args):
"""
%prog screen scaffolds.fasta library.fasta
Screen sequences against FASTA library. Sequences that have 95% id and 50%
cov will be removed by default.
"""
from jcvi.apps.align import blast
from jcvi.formats.blast import covfilter
p = OptionParser(screen.__doc__)
p.set_align(pctid=95, pctcov=50)
p.add_option("--best", default=1, type="int",
help="Get the best N hit [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
scaffolds, library = args
pctidflag = "--pctid={0}".format(opts.pctid)
blastfile = blast([library, scaffolds, pctidflag,
"--best={0}".format(opts.best)])
idsfile = blastfile.rsplit(".", 1)[0] + ".ids"
covfilter([blastfile, scaffolds, "--ids=" + idsfile,
pctidflag, "--pctcov={0}".format(opts.pctcov)])
pf = scaffolds.rsplit(".", 1)[0]
nf = pf + ".screen.fasta"
cmd = "faSomeRecords {0} -exclude {1} {2}".format(scaffolds, idsfile, nf)
sh(cmd)
logging.debug("Screened FASTA written to `{0}`.".format(nf))
return nf | python | def screen(args):
"""
%prog screen scaffolds.fasta library.fasta
Screen sequences against FASTA library. Sequences that have 95% id and 50%
cov will be removed by default.
"""
from jcvi.apps.align import blast
from jcvi.formats.blast import covfilter
p = OptionParser(screen.__doc__)
p.set_align(pctid=95, pctcov=50)
p.add_option("--best", default=1, type="int",
help="Get the best N hit [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
scaffolds, library = args
pctidflag = "--pctid={0}".format(opts.pctid)
blastfile = blast([library, scaffolds, pctidflag,
"--best={0}".format(opts.best)])
idsfile = blastfile.rsplit(".", 1)[0] + ".ids"
covfilter([blastfile, scaffolds, "--ids=" + idsfile,
pctidflag, "--pctcov={0}".format(opts.pctcov)])
pf = scaffolds.rsplit(".", 1)[0]
nf = pf + ".screen.fasta"
cmd = "faSomeRecords {0} -exclude {1} {2}".format(scaffolds, idsfile, nf)
sh(cmd)
logging.debug("Screened FASTA written to `{0}`.".format(nf))
return nf | [
"def",
"screen",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"apps",
".",
"align",
"import",
"blast",
"from",
"jcvi",
".",
"formats",
".",
"blast",
"import",
"covfilter",
"p",
"=",
"OptionParser",
"(",
"screen",
".",
"__doc__",
")",
"p",
".",
"set_alig... | %prog screen scaffolds.fasta library.fasta
Screen sequences against FASTA library. Sequences that have 95% id and 50%
cov will be removed by default. | [
"%prog",
"screen",
"scaffolds",
".",
"fasta",
"library",
".",
"fasta"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/postprocess.py#L252-L287 | train | 200,878 |
tanghaibao/jcvi | jcvi/assembly/postprocess.py | scaffold | def scaffold(args):
"""
%prog scaffold ctgfasta agpfile
Build scaffolds based on ordering in the AGP file.
"""
from jcvi.formats.agp import bed, order_to_agp, build
from jcvi.formats.bed import Bed
p = OptionParser(scaffold.__doc__)
p.add_option("--prefix", default=False, action="store_true",
help="Keep IDs with same prefix together [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
ctgfasta, agpfile = args
sizes = Sizes(ctgfasta).mapping
pf = ctgfasta.rsplit(".", 1)[0]
phasefile = pf + ".phases"
fwphase = open(phasefile, "w")
newagpfile = pf + ".new.agp"
fwagp = open(newagpfile, "w")
scaffoldbuckets = defaultdict(list)
bedfile = bed([agpfile, "--nogaps", "--outfile=tmp"])
bb = Bed(bedfile)
for s, partialorder in bb.sub_beds():
name = partialorder[0].accn
bname = name.rsplit("_", 1)[0] if opts.prefix else s
scaffoldbuckets[bname].append([(b.accn, b.strand) for b in partialorder])
# Now the buckets contain a mixture of singletons and partially resolved
# scaffolds. Print the scaffolds first then remaining singletons.
for bname, scaffolds in sorted(scaffoldbuckets.items()):
ctgorder = []
singletons = set()
for scaf in sorted(scaffolds):
for node, orientation in scaf:
ctgorder.append((node, orientation))
if len(scaf) == 1:
singletons.add(node)
nscaffolds = len(scaffolds)
nsingletons = len(singletons)
if nsingletons == 1 and nscaffolds == 0:
phase = 3
elif nsingletons == 0 and nscaffolds == 1:
phase = 2
else:
phase = 1
msg = "{0}: Scaffolds={1} Singletons={2} Phase={3}".\
format(bname, nscaffolds, nsingletons, phase)
print(msg, file=sys.stderr)
print("\t".join((bname, str(phase))), file=fwphase)
order_to_agp(bname, ctgorder, sizes, fwagp)
fwagp.close()
os.remove(bedfile)
fastafile = "final.fasta"
build([newagpfile, ctgfasta, fastafile])
tidy([fastafile]) | python | def scaffold(args):
"""
%prog scaffold ctgfasta agpfile
Build scaffolds based on ordering in the AGP file.
"""
from jcvi.formats.agp import bed, order_to_agp, build
from jcvi.formats.bed import Bed
p = OptionParser(scaffold.__doc__)
p.add_option("--prefix", default=False, action="store_true",
help="Keep IDs with same prefix together [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
ctgfasta, agpfile = args
sizes = Sizes(ctgfasta).mapping
pf = ctgfasta.rsplit(".", 1)[0]
phasefile = pf + ".phases"
fwphase = open(phasefile, "w")
newagpfile = pf + ".new.agp"
fwagp = open(newagpfile, "w")
scaffoldbuckets = defaultdict(list)
bedfile = bed([agpfile, "--nogaps", "--outfile=tmp"])
bb = Bed(bedfile)
for s, partialorder in bb.sub_beds():
name = partialorder[0].accn
bname = name.rsplit("_", 1)[0] if opts.prefix else s
scaffoldbuckets[bname].append([(b.accn, b.strand) for b in partialorder])
# Now the buckets contain a mixture of singletons and partially resolved
# scaffolds. Print the scaffolds first then remaining singletons.
for bname, scaffolds in sorted(scaffoldbuckets.items()):
ctgorder = []
singletons = set()
for scaf in sorted(scaffolds):
for node, orientation in scaf:
ctgorder.append((node, orientation))
if len(scaf) == 1:
singletons.add(node)
nscaffolds = len(scaffolds)
nsingletons = len(singletons)
if nsingletons == 1 and nscaffolds == 0:
phase = 3
elif nsingletons == 0 and nscaffolds == 1:
phase = 2
else:
phase = 1
msg = "{0}: Scaffolds={1} Singletons={2} Phase={3}".\
format(bname, nscaffolds, nsingletons, phase)
print(msg, file=sys.stderr)
print("\t".join((bname, str(phase))), file=fwphase)
order_to_agp(bname, ctgorder, sizes, fwagp)
fwagp.close()
os.remove(bedfile)
fastafile = "final.fasta"
build([newagpfile, ctgfasta, fastafile])
tidy([fastafile]) | [
"def",
"scaffold",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"agp",
"import",
"bed",
",",
"order_to_agp",
",",
"build",
"from",
"jcvi",
".",
"formats",
".",
"bed",
"import",
"Bed",
"p",
"=",
"OptionParser",
"(",
"scaffold",
".",
"__do... | %prog scaffold ctgfasta agpfile
Build scaffolds based on ordering in the AGP file. | [
"%prog",
"scaffold",
"ctgfasta",
"agpfile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/postprocess.py#L290-L356 | train | 200,879 |
tanghaibao/jcvi | jcvi/assembly/postprocess.py | overlapbatch | def overlapbatch(args):
"""
%prog overlapbatch ctgfasta poolfasta
Fish out the sequences in `poolfasta` that overlap with `ctgfasta`.
Mix and combine using `minimus2`.
"""
p = OptionParser(overlap.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
ctgfasta, poolfasta = args
f = Fasta(ctgfasta)
for k, rec in f.iteritems_ordered():
fastafile = k + ".fasta"
fw = open(fastafile, "w")
SeqIO.write([rec], fw, "fasta")
fw.close()
overlap([fastafile, poolfasta]) | python | def overlapbatch(args):
"""
%prog overlapbatch ctgfasta poolfasta
Fish out the sequences in `poolfasta` that overlap with `ctgfasta`.
Mix and combine using `minimus2`.
"""
p = OptionParser(overlap.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
ctgfasta, poolfasta = args
f = Fasta(ctgfasta)
for k, rec in f.iteritems_ordered():
fastafile = k + ".fasta"
fw = open(fastafile, "w")
SeqIO.write([rec], fw, "fasta")
fw.close()
overlap([fastafile, poolfasta]) | [
"def",
"overlapbatch",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"overlap",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"2",
":",
"sys",
".",
"exit",
"(... | %prog overlapbatch ctgfasta poolfasta
Fish out the sequences in `poolfasta` that overlap with `ctgfasta`.
Mix and combine using `minimus2`. | [
"%prog",
"overlapbatch",
"ctgfasta",
"poolfasta"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/postprocess.py#L365-L385 | train | 200,880 |
tanghaibao/jcvi | jcvi/apps/grid.py | array | def array(args):
"""
%prog array commands.list
Parallelize a set of commands on grid using array jobs.
"""
p = OptionParser(array.__doc__)
p.set_grid_opts(array=True)
p.set_params(prog="grid")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
cmds, = args
fp = open(cmds)
N = sum(1 for x in fp)
fp.close()
pf = cmds.rsplit(".", 1)[0]
runfile = pf + ".sh"
assert runfile != cmds, \
"Commands list file should not have a `.sh` extension"
engine = get_grid_engine()
threaded = opts.threaded or 1
contents = arraysh.format(cmds) if engine == "SGE" \
else arraysh_ua.format(N, threaded, cmds)
write_file(runfile, contents)
if engine == "PBS":
return
outfile = "{0}.{1}.out".format(pf, "\$TASK_ID")
errfile = "{0}.{1}.err".format(pf, "\$TASK_ID")
p = GridProcess("sh {0}".format(runfile), outfile=outfile, errfile=errfile,
arr=N, extra_opts=opts.extra, grid_opts=opts)
p.start() | python | def array(args):
"""
%prog array commands.list
Parallelize a set of commands on grid using array jobs.
"""
p = OptionParser(array.__doc__)
p.set_grid_opts(array=True)
p.set_params(prog="grid")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
cmds, = args
fp = open(cmds)
N = sum(1 for x in fp)
fp.close()
pf = cmds.rsplit(".", 1)[0]
runfile = pf + ".sh"
assert runfile != cmds, \
"Commands list file should not have a `.sh` extension"
engine = get_grid_engine()
threaded = opts.threaded or 1
contents = arraysh.format(cmds) if engine == "SGE" \
else arraysh_ua.format(N, threaded, cmds)
write_file(runfile, contents)
if engine == "PBS":
return
outfile = "{0}.{1}.out".format(pf, "\$TASK_ID")
errfile = "{0}.{1}.err".format(pf, "\$TASK_ID")
p = GridProcess("sh {0}".format(runfile), outfile=outfile, errfile=errfile,
arr=N, extra_opts=opts.extra, grid_opts=opts)
p.start() | [
"def",
"array",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"array",
".",
"__doc__",
")",
"p",
".",
"set_grid_opts",
"(",
"array",
"=",
"True",
")",
"p",
".",
"set_params",
"(",
"prog",
"=",
"\"grid\"",
")",
"opts",
",",
"args",
"=",
"p",... | %prog array commands.list
Parallelize a set of commands on grid using array jobs. | [
"%prog",
"array",
"commands",
".",
"list"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/grid.py#L358-L395 | train | 200,881 |
tanghaibao/jcvi | jcvi/graphics/assembly.py | covlen | def covlen(args):
"""
%prog covlen covfile fastafile
Plot coverage vs length. `covfile` is two-column listing contig id and
depth of coverage.
"""
import numpy as np
import pandas as pd
import seaborn as sns
from jcvi.formats.base import DictFile
p = OptionParser(covlen.__doc__)
p.add_option("--maxsize", default=1000000, type="int", help="Max contig size")
p.add_option("--maxcov", default=100, type="int", help="Max contig size")
p.add_option("--color", default='m', help="Color of the data points")
p.add_option("--kind", default="scatter",
choices=("scatter", "reg", "resid", "kde", "hex"),
help="Kind of plot to draw")
opts, args, iopts = p.set_image_options(args, figsize="8x8")
if len(args) != 2:
sys.exit(not p.print_help())
covfile, fastafile = args
cov = DictFile(covfile, cast=float)
s = Sizes(fastafile)
data = []
maxsize, maxcov = opts.maxsize, opts.maxcov
for ctg, size in s.iter_sizes():
c = cov.get(ctg, 0)
if size > maxsize:
continue
if c > maxcov:
continue
data.append((size, c))
x, y = zip(*data)
x = np.array(x)
y = np.array(y)
logging.debug("X size {0}, Y size {1}".format(x.size, y.size))
df = pd.DataFrame()
xlab, ylab = "Length", "Coverage of depth (X)"
df[xlab] = x
df[ylab] = y
sns.jointplot(xlab, ylab, kind=opts.kind, data=df,
xlim=(0, maxsize), ylim=(0, maxcov),
stat_func=None, edgecolor="w", color=opts.color)
figname = covfile + ".pdf"
savefig(figname, dpi=iopts.dpi, iopts=iopts) | python | def covlen(args):
"""
%prog covlen covfile fastafile
Plot coverage vs length. `covfile` is two-column listing contig id and
depth of coverage.
"""
import numpy as np
import pandas as pd
import seaborn as sns
from jcvi.formats.base import DictFile
p = OptionParser(covlen.__doc__)
p.add_option("--maxsize", default=1000000, type="int", help="Max contig size")
p.add_option("--maxcov", default=100, type="int", help="Max contig size")
p.add_option("--color", default='m', help="Color of the data points")
p.add_option("--kind", default="scatter",
choices=("scatter", "reg", "resid", "kde", "hex"),
help="Kind of plot to draw")
opts, args, iopts = p.set_image_options(args, figsize="8x8")
if len(args) != 2:
sys.exit(not p.print_help())
covfile, fastafile = args
cov = DictFile(covfile, cast=float)
s = Sizes(fastafile)
data = []
maxsize, maxcov = opts.maxsize, opts.maxcov
for ctg, size in s.iter_sizes():
c = cov.get(ctg, 0)
if size > maxsize:
continue
if c > maxcov:
continue
data.append((size, c))
x, y = zip(*data)
x = np.array(x)
y = np.array(y)
logging.debug("X size {0}, Y size {1}".format(x.size, y.size))
df = pd.DataFrame()
xlab, ylab = "Length", "Coverage of depth (X)"
df[xlab] = x
df[ylab] = y
sns.jointplot(xlab, ylab, kind=opts.kind, data=df,
xlim=(0, maxsize), ylim=(0, maxcov),
stat_func=None, edgecolor="w", color=opts.color)
figname = covfile + ".pdf"
savefig(figname, dpi=iopts.dpi, iopts=iopts) | [
"def",
"covlen",
"(",
"args",
")",
":",
"import",
"numpy",
"as",
"np",
"import",
"pandas",
"as",
"pd",
"import",
"seaborn",
"as",
"sns",
"from",
"jcvi",
".",
"formats",
".",
"base",
"import",
"DictFile",
"p",
"=",
"OptionParser",
"(",
"covlen",
".",
"_... | %prog covlen covfile fastafile
Plot coverage vs length. `covfile` is two-column listing contig id and
depth of coverage. | [
"%prog",
"covlen",
"covfile",
"fastafile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/graphics/assembly.py#L36-L87 | train | 200,882 |
tanghaibao/jcvi | jcvi/graphics/assembly.py | scaffold | def scaffold(args):
"""
%prog scaffold scaffold.fasta synteny.blast synteny.sizes synteny.bed
physicalmap.blast physicalmap.sizes physicalmap.bed
As evaluation of scaffolding, visualize external line of evidences:
* Plot synteny to an external genome
* Plot alignments to physical map
* Plot alignments to genetic map (TODO)
Each trio defines one panel to be plotted. blastfile defines the matchings
between the evidences vs scaffolds. Then the evidence sizes, and evidence
bed to plot dot plots.
This script will plot a dot in the dot plot in the corresponding location
the plots are one contig/scaffold per plot.
"""
from jcvi.utils.iter import grouper
p = OptionParser(scaffold.__doc__)
p.add_option("--cutoff", type="int", default=1000000,
help="Plot scaffolds with size larger than [default: %default]")
p.add_option("--highlights",
help="A set of regions in BED format to highlight [default: %default]")
opts, args, iopts = p.set_image_options(args, figsize="14x8", dpi=150)
if len(args) < 4 or len(args) % 3 != 1:
sys.exit(not p.print_help())
highlights = opts.highlights
scafsizes = Sizes(args[0])
trios = list(grouper(args[1:], 3))
trios = [(a, Sizes(b), Bed(c)) for a, b, c in trios]
if highlights:
hlbed = Bed(highlights)
for scaffoldID, scafsize in scafsizes.iter_sizes():
if scafsize < opts.cutoff:
continue
logging.debug("Loading {0} (size={1})".format(scaffoldID,
thousands(scafsize)))
tmpname = scaffoldID + ".sizes"
tmp = open(tmpname, "w")
tmp.write("{0}\t{1}".format(scaffoldID, scafsize))
tmp.close()
tmpsizes = Sizes(tmpname)
tmpsizes.close(clean=True)
if highlights:
subhighlights = list(hlbed.sub_bed(scaffoldID))
imagename = ".".join((scaffoldID, opts.format))
plot_one_scaffold(scaffoldID, tmpsizes, None, trios, imagename, iopts,
highlights=subhighlights) | python | def scaffold(args):
"""
%prog scaffold scaffold.fasta synteny.blast synteny.sizes synteny.bed
physicalmap.blast physicalmap.sizes physicalmap.bed
As evaluation of scaffolding, visualize external line of evidences:
* Plot synteny to an external genome
* Plot alignments to physical map
* Plot alignments to genetic map (TODO)
Each trio defines one panel to be plotted. blastfile defines the matchings
between the evidences vs scaffolds. Then the evidence sizes, and evidence
bed to plot dot plots.
This script will plot a dot in the dot plot in the corresponding location
the plots are one contig/scaffold per plot.
"""
from jcvi.utils.iter import grouper
p = OptionParser(scaffold.__doc__)
p.add_option("--cutoff", type="int", default=1000000,
help="Plot scaffolds with size larger than [default: %default]")
p.add_option("--highlights",
help="A set of regions in BED format to highlight [default: %default]")
opts, args, iopts = p.set_image_options(args, figsize="14x8", dpi=150)
if len(args) < 4 or len(args) % 3 != 1:
sys.exit(not p.print_help())
highlights = opts.highlights
scafsizes = Sizes(args[0])
trios = list(grouper(args[1:], 3))
trios = [(a, Sizes(b), Bed(c)) for a, b, c in trios]
if highlights:
hlbed = Bed(highlights)
for scaffoldID, scafsize in scafsizes.iter_sizes():
if scafsize < opts.cutoff:
continue
logging.debug("Loading {0} (size={1})".format(scaffoldID,
thousands(scafsize)))
tmpname = scaffoldID + ".sizes"
tmp = open(tmpname, "w")
tmp.write("{0}\t{1}".format(scaffoldID, scafsize))
tmp.close()
tmpsizes = Sizes(tmpname)
tmpsizes.close(clean=True)
if highlights:
subhighlights = list(hlbed.sub_bed(scaffoldID))
imagename = ".".join((scaffoldID, opts.format))
plot_one_scaffold(scaffoldID, tmpsizes, None, trios, imagename, iopts,
highlights=subhighlights) | [
"def",
"scaffold",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"utils",
".",
"iter",
"import",
"grouper",
"p",
"=",
"OptionParser",
"(",
"scaffold",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--cutoff\"",
",",
"type",
"=",
"\"int\"",
",",
"de... | %prog scaffold scaffold.fasta synteny.blast synteny.sizes synteny.bed
physicalmap.blast physicalmap.sizes physicalmap.bed
As evaluation of scaffolding, visualize external line of evidences:
* Plot synteny to an external genome
* Plot alignments to physical map
* Plot alignments to genetic map (TODO)
Each trio defines one panel to be plotted. blastfile defines the matchings
between the evidences vs scaffolds. Then the evidence sizes, and evidence
bed to plot dot plots.
This script will plot a dot in the dot plot in the corresponding location
the plots are one contig/scaffold per plot. | [
"%prog",
"scaffold",
"scaffold",
".",
"fasta",
"synteny",
".",
"blast",
"synteny",
".",
"sizes",
"synteny",
".",
"bed",
"physicalmap",
".",
"blast",
"physicalmap",
".",
"sizes",
"physicalmap",
".",
"bed"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/graphics/assembly.py#L214-L269 | train | 200,883 |
tanghaibao/jcvi | jcvi/graphics/assembly.py | A50 | def A50(args):
"""
%prog A50 contigs_A.fasta contigs_B.fasta ...
Plots A50 graphics, see blog post (http://blog.malde.org/index.php/a50/)
"""
p = OptionParser(A50.__doc__)
p.add_option("--overwrite", default=False, action="store_true",
help="overwrite .rplot file if exists [default: %default]")
p.add_option("--cutoff", default=0, type="int", dest="cutoff",
help="use contigs above certain size [default: %default]")
p.add_option("--stepsize", default=10, type="int", dest="stepsize",
help="stepsize for the distribution [default: %default]")
opts, args = p.parse_args(args)
if not args:
sys.exit(p.print_help())
import numpy as np
from jcvi.utils.table import loadtable
stepsize = opts.stepsize # use stepsize to speed up drawing
rplot = "A50.rplot"
if not op.exists(rplot) or opts.overwrite:
fw = open(rplot, "w")
header = "\t".join(("index", "cumsize", "fasta"))
statsheader = ("Fasta", "L50", "N50", "Min", "Max", "Average", "Sum",
"Counts")
statsrows = []
print(header, file=fw)
for fastafile in args:
f = Fasta(fastafile, index=False)
ctgsizes = [length for k, length in f.itersizes()]
ctgsizes = np.array(ctgsizes)
a50, l50, n50 = calculate_A50(ctgsizes, cutoff=opts.cutoff)
cmin, cmax, cmean = min(ctgsizes), max(ctgsizes), np.mean(ctgsizes)
csum, counts = np.sum(ctgsizes), len(ctgsizes)
cmean = int(round(cmean))
statsrows.append((fastafile, l50, n50, cmin, cmax, cmean, csum,
counts))
logging.debug("`{0}` ctgsizes: {1}".format(fastafile, ctgsizes))
tag = "{0} (L50={1})".format(\
op.basename(fastafile).rsplit(".", 1)[0], l50)
logging.debug(tag)
for i, s in zip(xrange(0, len(a50), stepsize), a50[::stepsize]):
print("\t".join((str(i), str(s / 1000000.), tag)), file=fw)
fw.close()
table = loadtable(statsheader, statsrows)
print(table, file=sys.stderr)
generate_plot(rplot) | python | def A50(args):
"""
%prog A50 contigs_A.fasta contigs_B.fasta ...
Plots A50 graphics, see blog post (http://blog.malde.org/index.php/a50/)
"""
p = OptionParser(A50.__doc__)
p.add_option("--overwrite", default=False, action="store_true",
help="overwrite .rplot file if exists [default: %default]")
p.add_option("--cutoff", default=0, type="int", dest="cutoff",
help="use contigs above certain size [default: %default]")
p.add_option("--stepsize", default=10, type="int", dest="stepsize",
help="stepsize for the distribution [default: %default]")
opts, args = p.parse_args(args)
if not args:
sys.exit(p.print_help())
import numpy as np
from jcvi.utils.table import loadtable
stepsize = opts.stepsize # use stepsize to speed up drawing
rplot = "A50.rplot"
if not op.exists(rplot) or opts.overwrite:
fw = open(rplot, "w")
header = "\t".join(("index", "cumsize", "fasta"))
statsheader = ("Fasta", "L50", "N50", "Min", "Max", "Average", "Sum",
"Counts")
statsrows = []
print(header, file=fw)
for fastafile in args:
f = Fasta(fastafile, index=False)
ctgsizes = [length for k, length in f.itersizes()]
ctgsizes = np.array(ctgsizes)
a50, l50, n50 = calculate_A50(ctgsizes, cutoff=opts.cutoff)
cmin, cmax, cmean = min(ctgsizes), max(ctgsizes), np.mean(ctgsizes)
csum, counts = np.sum(ctgsizes), len(ctgsizes)
cmean = int(round(cmean))
statsrows.append((fastafile, l50, n50, cmin, cmax, cmean, csum,
counts))
logging.debug("`{0}` ctgsizes: {1}".format(fastafile, ctgsizes))
tag = "{0} (L50={1})".format(\
op.basename(fastafile).rsplit(".", 1)[0], l50)
logging.debug(tag)
for i, s in zip(xrange(0, len(a50), stepsize), a50[::stepsize]):
print("\t".join((str(i), str(s / 1000000.), tag)), file=fw)
fw.close()
table = loadtable(statsheader, statsrows)
print(table, file=sys.stderr)
generate_plot(rplot) | [
"def",
"A50",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"A50",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--overwrite\"",
",",
"default",
"=",
"False",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"overwrite .rplot file i... | %prog A50 contigs_A.fasta contigs_B.fasta ...
Plots A50 graphics, see blog post (http://blog.malde.org/index.php/a50/) | [
"%prog",
"A50",
"contigs_A",
".",
"fasta",
"contigs_B",
".",
"fasta",
"..."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/graphics/assembly.py#L406-L461 | train | 200,884 |
tanghaibao/jcvi | jcvi/formats/coords.py | fromdelta | def fromdelta(args):
"""
%prog fromdelta deltafile
Convert deltafile to coordsfile.
"""
p = OptionParser(fromdelta.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
deltafile, = args
coordsfile = deltafile.rsplit(".", 1)[0] + ".coords"
cmd = "show-coords -rclH {0}".format(deltafile)
sh(cmd, outfile=coordsfile)
return coordsfile | python | def fromdelta(args):
"""
%prog fromdelta deltafile
Convert deltafile to coordsfile.
"""
p = OptionParser(fromdelta.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
deltafile, = args
coordsfile = deltafile.rsplit(".", 1)[0] + ".coords"
cmd = "show-coords -rclH {0}".format(deltafile)
sh(cmd, outfile=coordsfile)
return coordsfile | [
"def",
"fromdelta",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"fromdelta",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
":",
"sys",
".",
"exit",
"("... | %prog fromdelta deltafile
Convert deltafile to coordsfile. | [
"%prog",
"fromdelta",
"deltafile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/coords.py#L316-L333 | train | 200,885 |
tanghaibao/jcvi | jcvi/formats/coords.py | sort | def sort(args):
"""
%prog sort coordsfile
Sort coordsfile based on query or ref.
"""
import jcvi.formats.blast
return jcvi.formats.blast.sort(args + ["--coords"]) | python | def sort(args):
"""
%prog sort coordsfile
Sort coordsfile based on query or ref.
"""
import jcvi.formats.blast
return jcvi.formats.blast.sort(args + ["--coords"]) | [
"def",
"sort",
"(",
"args",
")",
":",
"import",
"jcvi",
".",
"formats",
".",
"blast",
"return",
"jcvi",
".",
"formats",
".",
"blast",
".",
"sort",
"(",
"args",
"+",
"[",
"\"--coords\"",
"]",
")"
] | %prog sort coordsfile
Sort coordsfile based on query or ref. | [
"%prog",
"sort",
"coordsfile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/coords.py#L336-L344 | train | 200,886 |
tanghaibao/jcvi | jcvi/formats/coords.py | coverage | def coverage(args):
"""
%prog coverage coordsfile
Report the coverage per query record, useful to see which query matches
reference. The coords file MUST be filtered with supermap::
jcvi.algorithms.supermap --filter query
"""
p = OptionParser(coverage.__doc__)
p.add_option("-c", dest="cutoff", default=0.5, type="float",
help="only report query with coverage greater than [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
coordsfile, = args
fp = open(coordsfile)
coords = []
for row in fp:
try:
c = CoordsLine(row)
except AssertionError:
continue
coords.append(c)
coords.sort(key=lambda x: x.query)
coverages = []
for query, lines in groupby(coords, key=lambda x: x.query):
cumulative_cutoff = sum(x.querycov for x in lines)
coverages.append((query, cumulative_cutoff))
coverages.sort(key=lambda x: (-x[1], x[0]))
for query, cumulative_cutoff in coverages:
if cumulative_cutoff < opts.cutoff:
break
print("{0}\t{1:.2f}".format(query, cumulative_cutoff)) | python | def coverage(args):
"""
%prog coverage coordsfile
Report the coverage per query record, useful to see which query matches
reference. The coords file MUST be filtered with supermap::
jcvi.algorithms.supermap --filter query
"""
p = OptionParser(coverage.__doc__)
p.add_option("-c", dest="cutoff", default=0.5, type="float",
help="only report query with coverage greater than [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
coordsfile, = args
fp = open(coordsfile)
coords = []
for row in fp:
try:
c = CoordsLine(row)
except AssertionError:
continue
coords.append(c)
coords.sort(key=lambda x: x.query)
coverages = []
for query, lines in groupby(coords, key=lambda x: x.query):
cumulative_cutoff = sum(x.querycov for x in lines)
coverages.append((query, cumulative_cutoff))
coverages.sort(key=lambda x: (-x[1], x[0]))
for query, cumulative_cutoff in coverages:
if cumulative_cutoff < opts.cutoff:
break
print("{0}\t{1:.2f}".format(query, cumulative_cutoff)) | [
"def",
"coverage",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"coverage",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"-c\"",
",",
"dest",
"=",
"\"cutoff\"",
",",
"default",
"=",
"0.5",
",",
"type",
"=",
"\"float\"",
",",
"help",
"... | %prog coverage coordsfile
Report the coverage per query record, useful to see which query matches
reference. The coords file MUST be filtered with supermap::
jcvi.algorithms.supermap --filter query | [
"%prog",
"coverage",
"coordsfile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/coords.py#L347-L387 | train | 200,887 |
tanghaibao/jcvi | jcvi/formats/coords.py | annotate | def annotate(args):
"""
%prog annotate coordsfile
Annotate coordsfile to append an additional column, with the following
overlaps: {0}.
"""
p = OptionParser(annotate.__doc__.format(", ".join(Overlap_types)))
p.add_option("--maxhang", default=100, type="int",
help="Max hang to call dovetail overlap [default: %default]")
p.add_option("--all", default=False, action="store_true",
help="Output all lines [default: terminal/containment]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
coordsfile, = args
fp = open(coordsfile)
for row in fp:
try:
c = CoordsLine(row)
except AssertionError:
continue
ov = c.overlap(opts.maxhang)
if not opts.all and ov == 0:
continue
print("{0}\t{1}".format(row.strip(), Overlap_types[ov])) | python | def annotate(args):
"""
%prog annotate coordsfile
Annotate coordsfile to append an additional column, with the following
overlaps: {0}.
"""
p = OptionParser(annotate.__doc__.format(", ".join(Overlap_types)))
p.add_option("--maxhang", default=100, type="int",
help="Max hang to call dovetail overlap [default: %default]")
p.add_option("--all", default=False, action="store_true",
help="Output all lines [default: terminal/containment]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
coordsfile, = args
fp = open(coordsfile)
for row in fp:
try:
c = CoordsLine(row)
except AssertionError:
continue
ov = c.overlap(opts.maxhang)
if not opts.all and ov == 0:
continue
print("{0}\t{1}".format(row.strip(), Overlap_types[ov])) | [
"def",
"annotate",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"annotate",
".",
"__doc__",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"Overlap_types",
")",
")",
")",
"p",
".",
"add_option",
"(",
"\"--maxhang\"",
",",
"default",
"=",
"100... | %prog annotate coordsfile
Annotate coordsfile to append an additional column, with the following
overlaps: {0}. | [
"%prog",
"annotate",
"coordsfile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/coords.py#L390-L421 | train | 200,888 |
tanghaibao/jcvi | jcvi/formats/coords.py | summary | def summary(args):
"""
%prog summary coordsfile
provide summary on id% and cov%, for both query and reference
"""
from jcvi.formats.blast import AlignStats
p = OptionParser(summary.__doc__)
p.add_option("-s", dest="single", default=False, action="store_true",
help="provide stats per reference seq")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(p.print_help())
coordsfile, = args
alignstats = get_stats(coordsfile)
alignstats.print_stats() | python | def summary(args):
"""
%prog summary coordsfile
provide summary on id% and cov%, for both query and reference
"""
from jcvi.formats.blast import AlignStats
p = OptionParser(summary.__doc__)
p.add_option("-s", dest="single", default=False, action="store_true",
help="provide stats per reference seq")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(p.print_help())
coordsfile, = args
alignstats = get_stats(coordsfile)
alignstats.print_stats() | [
"def",
"summary",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"blast",
"import",
"AlignStats",
"p",
"=",
"OptionParser",
"(",
"summary",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"-s\"",
",",
"dest",
"=",
"\"single\"",
",",
"d... | %prog summary coordsfile
provide summary on id% and cov%, for both query and reference | [
"%prog",
"summary",
"coordsfile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/coords.py#L424-L443 | train | 200,889 |
tanghaibao/jcvi | jcvi/formats/coords.py | bed | def bed(args):
"""
%prog bed coordsfile
will produce a bed list of mapped position and orientation (needs to
be beyond quality cutoff, say 50) in bed format
"""
p = OptionParser(bed.__doc__)
p.add_option("--query", default=False, action="store_true",
help="print out query intervals rather than ref [default: %default]")
p.add_option("--pctid", default=False, action="store_true",
help="use pctid in score [default: %default]")
p.add_option("--cutoff", dest="cutoff", default=0, type="float",
help="get all the alignments with quality above threshold " +\
"[default: %default]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(p.print_help())
coordsfile, = args
query = opts.query
pctid = opts.pctid
quality_cutoff = opts.cutoff
coords = Coords(coordsfile)
for c in coords:
if c.quality < quality_cutoff:
continue
line = c.qbedline(pctid=pctid) if query else c.bedline(pctid=pctid)
print(line) | python | def bed(args):
"""
%prog bed coordsfile
will produce a bed list of mapped position and orientation (needs to
be beyond quality cutoff, say 50) in bed format
"""
p = OptionParser(bed.__doc__)
p.add_option("--query", default=False, action="store_true",
help="print out query intervals rather than ref [default: %default]")
p.add_option("--pctid", default=False, action="store_true",
help="use pctid in score [default: %default]")
p.add_option("--cutoff", dest="cutoff", default=0, type="float",
help="get all the alignments with quality above threshold " +\
"[default: %default]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(p.print_help())
coordsfile, = args
query = opts.query
pctid = opts.pctid
quality_cutoff = opts.cutoff
coords = Coords(coordsfile)
for c in coords:
if c.quality < quality_cutoff:
continue
line = c.qbedline(pctid=pctid) if query else c.bedline(pctid=pctid)
print(line) | [
"def",
"bed",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"bed",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--query\"",
",",
"default",
"=",
"False",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"print out query intervals r... | %prog bed coordsfile
will produce a bed list of mapped position and orientation (needs to
be beyond quality cutoff, say 50) in bed format | [
"%prog",
"bed",
"coordsfile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/coords.py#L503-L534 | train | 200,890 |
tanghaibao/jcvi | jcvi/formats/coords.py | Coords.hits | def hits(self):
"""
returns a dict with query => blastline
"""
self.quality_sort()
hits = dict((query, list(blines)) for (query, blines) in \
groupby(self, lambda x: x.query))
self.ref_sort()
return hits | python | def hits(self):
"""
returns a dict with query => blastline
"""
self.quality_sort()
hits = dict((query, list(blines)) for (query, blines) in \
groupby(self, lambda x: x.query))
self.ref_sort()
return hits | [
"def",
"hits",
"(",
"self",
")",
":",
"self",
".",
"quality_sort",
"(",
")",
"hits",
"=",
"dict",
"(",
"(",
"query",
",",
"list",
"(",
"blines",
")",
")",
"for",
"(",
"query",
",",
"blines",
")",
"in",
"groupby",
"(",
"self",
",",
"lambda",
"x",
... | returns a dict with query => blastline | [
"returns",
"a",
"dict",
"with",
"query",
"=",
">",
"blastline"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/coords.py#L183-L194 | train | 200,891 |
tanghaibao/jcvi | jcvi/formats/coords.py | Coords.best_hits | def best_hits(self):
"""
returns a dict with query => best mapped position
"""
self.quality_sort()
best_hits = dict((query, next(blines)) for (query, blines) in \
groupby(self, lambda x: x.query))
self.ref_sort()
return best_hits | python | def best_hits(self):
"""
returns a dict with query => best mapped position
"""
self.quality_sort()
best_hits = dict((query, next(blines)) for (query, blines) in \
groupby(self, lambda x: x.query))
self.ref_sort()
return best_hits | [
"def",
"best_hits",
"(",
"self",
")",
":",
"self",
".",
"quality_sort",
"(",
")",
"best_hits",
"=",
"dict",
"(",
"(",
"query",
",",
"next",
"(",
"blines",
")",
")",
"for",
"(",
"query",
",",
"blines",
")",
"in",
"groupby",
"(",
"self",
",",
"lambda... | returns a dict with query => best mapped position | [
"returns",
"a",
"dict",
"with",
"query",
"=",
">",
"best",
"mapped",
"position"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/coords.py#L197-L208 | train | 200,892 |
tanghaibao/jcvi | jcvi/apps/base.py | sh | def sh(cmd, grid=False, infile=None, outfile=None, errfile=None,
append=False, background=False, threaded=None, log=True,
grid_opts=None, silent=False, shell="/bin/bash", check=False):
"""
simple wrapper for system calls
"""
if not cmd:
return 1
if silent:
outfile = errfile = "/dev/null"
if grid:
from jcvi.apps.grid import GridProcess
pr = GridProcess(cmd, infile=infile, outfile=outfile, errfile=errfile,
threaded=threaded, grid_opts=grid_opts)
pr.start()
return pr.jobid
else:
if infile:
cat = "cat"
if infile.endswith(".gz"):
cat = "zcat"
cmd = "{0} {1} |".format(cat, infile) + cmd
if outfile and outfile != "stdout":
if outfile.endswith(".gz"):
cmd += " | gzip"
tag = ">"
if append:
tag = ">>"
cmd += " {0}{1}".format(tag, outfile)
if errfile:
if errfile == outfile:
errfile = "&1"
cmd += " 2>{0}".format(errfile)
if background:
cmd += " &"
if log:
logging.debug(cmd)
call_func = check_call if check else call
return call_func(cmd, shell=True, executable=shell) | python | def sh(cmd, grid=False, infile=None, outfile=None, errfile=None,
append=False, background=False, threaded=None, log=True,
grid_opts=None, silent=False, shell="/bin/bash", check=False):
"""
simple wrapper for system calls
"""
if not cmd:
return 1
if silent:
outfile = errfile = "/dev/null"
if grid:
from jcvi.apps.grid import GridProcess
pr = GridProcess(cmd, infile=infile, outfile=outfile, errfile=errfile,
threaded=threaded, grid_opts=grid_opts)
pr.start()
return pr.jobid
else:
if infile:
cat = "cat"
if infile.endswith(".gz"):
cat = "zcat"
cmd = "{0} {1} |".format(cat, infile) + cmd
if outfile and outfile != "stdout":
if outfile.endswith(".gz"):
cmd += " | gzip"
tag = ">"
if append:
tag = ">>"
cmd += " {0}{1}".format(tag, outfile)
if errfile:
if errfile == outfile:
errfile = "&1"
cmd += " 2>{0}".format(errfile)
if background:
cmd += " &"
if log:
logging.debug(cmd)
call_func = check_call if check else call
return call_func(cmd, shell=True, executable=shell) | [
"def",
"sh",
"(",
"cmd",
",",
"grid",
"=",
"False",
",",
"infile",
"=",
"None",
",",
"outfile",
"=",
"None",
",",
"errfile",
"=",
"None",
",",
"append",
"=",
"False",
",",
"background",
"=",
"False",
",",
"threaded",
"=",
"None",
",",
"log",
"=",
... | simple wrapper for system calls | [
"simple",
"wrapper",
"for",
"system",
"calls"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/base.py#L739-L779 | train | 200,893 |
tanghaibao/jcvi | jcvi/apps/base.py | Popen | def Popen(cmd, stdin=None, stdout=PIPE, debug=False, shell="/bin/bash"):
"""
Capture the cmd stdout output to a file handle.
"""
from subprocess import Popen as P
if debug:
logging.debug(cmd)
# See: <https://blog.nelhage.com/2010/02/a-very-subtle-bug/>
proc = P(cmd, bufsize=1, stdin=stdin, stdout=stdout, \
shell=True, executable=shell)
return proc | python | def Popen(cmd, stdin=None, stdout=PIPE, debug=False, shell="/bin/bash"):
"""
Capture the cmd stdout output to a file handle.
"""
from subprocess import Popen as P
if debug:
logging.debug(cmd)
# See: <https://blog.nelhage.com/2010/02/a-very-subtle-bug/>
proc = P(cmd, bufsize=1, stdin=stdin, stdout=stdout, \
shell=True, executable=shell)
return proc | [
"def",
"Popen",
"(",
"cmd",
",",
"stdin",
"=",
"None",
",",
"stdout",
"=",
"PIPE",
",",
"debug",
"=",
"False",
",",
"shell",
"=",
"\"/bin/bash\"",
")",
":",
"from",
"subprocess",
"import",
"Popen",
"as",
"P",
"if",
"debug",
":",
"logging",
".",
"debu... | Capture the cmd stdout output to a file handle. | [
"Capture",
"the",
"cmd",
"stdout",
"output",
"to",
"a",
"file",
"handle",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/base.py#L782-L792 | train | 200,894 |
tanghaibao/jcvi | jcvi/apps/base.py | is_newer_file | def is_newer_file(a, b):
"""
Check if the file a is newer than file b
"""
if not (op.exists(a) and op.exists(b)):
return False
am = os.stat(a).st_mtime
bm = os.stat(b).st_mtime
return am > bm | python | def is_newer_file(a, b):
"""
Check if the file a is newer than file b
"""
if not (op.exists(a) and op.exists(b)):
return False
am = os.stat(a).st_mtime
bm = os.stat(b).st_mtime
return am > bm | [
"def",
"is_newer_file",
"(",
"a",
",",
"b",
")",
":",
"if",
"not",
"(",
"op",
".",
"exists",
"(",
"a",
")",
"and",
"op",
".",
"exists",
"(",
"b",
")",
")",
":",
"return",
"False",
"am",
"=",
"os",
".",
"stat",
"(",
"a",
")",
".",
"st_mtime",
... | Check if the file a is newer than file b | [
"Check",
"if",
"the",
"file",
"a",
"is",
"newer",
"than",
"file",
"b"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/base.py#L889-L897 | train | 200,895 |
tanghaibao/jcvi | jcvi/apps/base.py | need_update | def need_update(a, b):
"""
Check if file a is newer than file b and decide whether or not to update
file b. Can generalize to two lists.
"""
a = listify(a)
b = listify(b)
return any((not op.exists(x)) for x in b) or \
all((os.stat(x).st_size == 0 for x in b)) or \
any(is_newer_file(x, y) for x in a for y in b) | python | def need_update(a, b):
"""
Check if file a is newer than file b and decide whether or not to update
file b. Can generalize to two lists.
"""
a = listify(a)
b = listify(b)
return any((not op.exists(x)) for x in b) or \
all((os.stat(x).st_size == 0 for x in b)) or \
any(is_newer_file(x, y) for x in a for y in b) | [
"def",
"need_update",
"(",
"a",
",",
"b",
")",
":",
"a",
"=",
"listify",
"(",
"a",
")",
"b",
"=",
"listify",
"(",
"b",
")",
"return",
"any",
"(",
"(",
"not",
"op",
".",
"exists",
"(",
"x",
")",
")",
"for",
"x",
"in",
"b",
")",
"or",
"all",
... | Check if file a is newer than file b and decide whether or not to update
file b. Can generalize to two lists. | [
"Check",
"if",
"file",
"a",
"is",
"newer",
"than",
"file",
"b",
"and",
"decide",
"whether",
"or",
"not",
"to",
"update",
"file",
"b",
".",
"Can",
"generalize",
"to",
"two",
"lists",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/base.py#L921-L931 | train | 200,896 |
tanghaibao/jcvi | jcvi/apps/base.py | debug | def debug(level=logging.DEBUG):
"""
Turn on the debugging
"""
from jcvi.apps.console import magenta, yellow
format = yellow("%(asctime)s [%(module)s]")
format += magenta(" %(message)s")
logging.basicConfig(level=level,
format=format,
datefmt="%H:%M:%S") | python | def debug(level=logging.DEBUG):
"""
Turn on the debugging
"""
from jcvi.apps.console import magenta, yellow
format = yellow("%(asctime)s [%(module)s]")
format += magenta(" %(message)s")
logging.basicConfig(level=level,
format=format,
datefmt="%H:%M:%S") | [
"def",
"debug",
"(",
"level",
"=",
"logging",
".",
"DEBUG",
")",
":",
"from",
"jcvi",
".",
"apps",
".",
"console",
"import",
"magenta",
",",
"yellow",
"format",
"=",
"yellow",
"(",
"\"%(asctime)s [%(module)s]\"",
")",
"format",
"+=",
"magenta",
"(",
"\" %(... | Turn on the debugging | [
"Turn",
"on",
"the",
"debugging"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/base.py#L1018-L1028 | train | 200,897 |
tanghaibao/jcvi | jcvi/apps/base.py | mdownload | def mdownload(args):
"""
%prog mdownload links.txt
Multiple download a list of files. Use formats.html.links() to extract the
links file.
"""
from jcvi.apps.grid import Jobs
p = OptionParser(mdownload.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
linksfile, = args
links = [(x.strip(),) for x in open(linksfile)]
j = Jobs(download, links)
j.run() | python | def mdownload(args):
"""
%prog mdownload links.txt
Multiple download a list of files. Use formats.html.links() to extract the
links file.
"""
from jcvi.apps.grid import Jobs
p = OptionParser(mdownload.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
linksfile, = args
links = [(x.strip(),) for x in open(linksfile)]
j = Jobs(download, links)
j.run() | [
"def",
"mdownload",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"apps",
".",
"grid",
"import",
"Jobs",
"p",
"=",
"OptionParser",
"(",
"mdownload",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
... | %prog mdownload links.txt
Multiple download a list of files. Use formats.html.links() to extract the
links file. | [
"%prog",
"mdownload",
"links",
".",
"txt"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/base.py#L1049-L1067 | train | 200,898 |
tanghaibao/jcvi | jcvi/apps/base.py | timestamp | def timestamp(args):
"""
%prog timestamp path > timestamp.info
Record the timestamps for all files in the current folder.
filename atime mtime
This file can be used later to recover previous timestamps through touch().
"""
p = OptionParser(timestamp.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
path, = args
for root, dirs, files in os.walk(path):
for f in files:
filename = op.join(root, f)
atime, mtime = get_times(filename)
print(filename, atime, mtime) | python | def timestamp(args):
"""
%prog timestamp path > timestamp.info
Record the timestamps for all files in the current folder.
filename atime mtime
This file can be used later to recover previous timestamps through touch().
"""
p = OptionParser(timestamp.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
path, = args
for root, dirs, files in os.walk(path):
for f in files:
filename = op.join(root, f)
atime, mtime = get_times(filename)
print(filename, atime, mtime) | [
"def",
"timestamp",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"timestamp",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
":",
"sys",
".",
"exit",
"("... | %prog timestamp path > timestamp.info
Record the timestamps for all files in the current folder.
filename atime mtime
This file can be used later to recover previous timestamps through touch(). | [
"%prog",
"timestamp",
"path",
">",
"timestamp",
".",
"info"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/base.py#L1109-L1129 | train | 200,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.