code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
p = OptionParser(clean.__doc__)
p.add_option("--fancy", default=False, action="store_true",
help="Pretty print the sequence [default: %default]")
p.add_option("--canonical", default=False, action="store_true",
help="Use only acgtnACGTN [default: %default]")
p.set_o... | def clean(args) | %prog clean fastafile
Remove irregular chars in FASTA seqs. | 2.902768 | 2.699877 | 1.075148 |
transl_tables = [str(x) for x in xrange(1,25)]
p = OptionParser(translate.__doc__)
p.add_option("--ids", default=False, action="store_true",
help="Create .ids file with the complete/partial/gaps "
"label [default: %default]")
p.add_option("--longest", default=... | def translate(args) | %prog translate cdsfasta
Translate CDS to proteins. The tricky thing is that sometimes the CDS
represents a partial gene, therefore disrupting the frame of the protein.
Check all three frames to get a valid translation. | 2.670033 | 2.524506 | 1.057646 |
p = OptionParser(filter.__doc__)
p.add_option("--less", default=False, action="store_true",
help="filter the sizes < certain cutoff [default: >=]")
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
fastafile, cutoff =... | def filter(args) | %prog filter fastafile 100
Filter the FASTA file to contain records with size >= or <= certain cutoff. | 2.939259 | 2.433521 | 1.207822 |
from jcvi.formats.base import longest_unique_prefix
p = OptionParser(pool.__doc__)
p.add_option("--sep", default=".", help="Separator between prefix and name")
p.add_option("--sequential", default=False, action="store_true",
help="Add sequential IDs")
opts, args = p.parse_args(args... | def pool(args) | %prog pool fastafiles > pool.fasta
Pool a bunch of FASTA files, and add prefix to each record based on
filenames. File names are simplified to longest unique prefix to avoid
collisions after getting shortened. | 3.223734 | 2.919873 | 1.104067 |
p = OptionParser(ids.__doc__)
p.add_option("--until", default=None,
help="Truncate the name and description at words [default: %default]")
p.add_option("--description", default=False, action="store_true",
help="Generate a second column with description [default: %default]")
... | def ids(args) | %prog ids fastafiles
Generate the FASTA headers without the '>'. | 3.043873 | 2.724559 | 1.117199 |
p = OptionParser(sort.__doc__)
p.add_option("--sizes", default=False, action="store_true",
help="Sort by decreasing size [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(p.print_help())
fastafile, = args
sortedfastafile = fastafil... | def sort(args) | %prog sort fastafile
Sort a list of sequences and output with sorted IDs, etc. | 2.692628 | 2.663733 | 1.010847 |
from jcvi.formats.agp import OO, Phases, build
from jcvi.formats.sizes import Sizes
p = OptionParser(join.__doc__)
p.add_option("--newid", default=None,
help="New sequence ID [default: `%default`]")
p.add_option("--gapsize", default=100, type="int",
help="Number of N's ... | def join(args) | %prog join fastafile [phasefile]
Make AGP file for a bunch of sequences, and add gaps between, and then build
the joined fastafile. This is useful by itself, but with --oo option this
can convert the .oo (BAMBUS output) into AGP and a joined fasta.
Phasefile is optional, but must contain two columns -... | 3.154919 | 2.900826 | 1.087593 |
from jcvi.utils.natsort import natsort_key
p = OptionParser(summary.__doc__)
p.add_option("--suffix", default="Mb",
help="make the base pair counts human readable [default: %default]")
p.add_option("--ids",
help="write the ids that have >= 50% N's [default: %default]")
... | def summary(args) | %prog summary *.fasta
Report real bases and N's in fastafiles in a tabular report | 2.964792 | 2.76337 | 1.07289 |
plus_match = _print_first_difference(arec, brec, ignore_case=ignore_case,
ignore_N=ignore_N, report_match=report_match)
if rc and not plus_match:
logging.debug("trying reverse complement of %s" % brec.id)
brec.seq = brec.seq.reverse_complement()
minus_match = _print_firs... | def print_first_difference(arec, brec, ignore_case=False, ignore_N=False,
rc=False, report_match=True) | Returns the first different nucleotide in two sequence comparisons
runs both Plus and Minus strand | 2.169094 | 2.192735 | 0.989219 |
aseq, bseq = arec.seq, brec.seq
asize, bsize = len(aseq), len(bseq)
matched = True
for i, (a, b) in enumerate(zip_longest(aseq, bseq)):
if ignore_case and None not in (a, b):
a, b = a.upper(), b.upper()
if ignore_N and ('N' in (a, b) or 'X' in (a, b)):
cont... | def _print_first_difference(arec, brec, ignore_case=False, ignore_N=False,
report_match=True) | Returns the first different nucleotide in two sequence comparisons | 2.692068 | 2.634092 | 1.02201 |
from jcvi.utils.table import banner
p = OptionParser(diff.__doc__)
p.add_option("--ignore_case", default=False, action="store_true",
help="ignore case when comparing sequences [default: %default]")
p.add_option("--ignore_N", default=False, action="store_true",
help="ignore ... | def diff(args) | %prog diff afasta bfasta
print out whether the records in two fasta files are the same | 2.509261 | 2.453799 | 1.022602 |
if ignore_stop:
seq = seq.rstrip("*")
if ignore_case:
seq = seq.upper()
if ignore_N:
if not all(c.upper() in 'ATGCN' for c in seq):
seq = re.sub('X', '', seq)
else:
seq = re.sub('N', '', seq)
if checksum == "MD5":
hashed = md5(seq).he... | def hash_fasta(seq, ignore_case=False, ignore_N=False, ignore_stop=False, checksum="MD5") | Generates checksum of input sequence element | 3.083457 | 3.037879 | 1.015003 |
from jcvi.utils.cbook import AutoVivification
allowed_checksum = ["MD5", "GCG"]
p = OptionParser(identical.__doc__)
p.add_option("--ignore_case", default=False, action="store_true",
help="ignore case when comparing sequences [default: %default]")
p.add_option("--ignore_N", default... | def identical(args) | %prog identical *.fasta
Given multiple fasta files, find all the exactly identical records
based on the computed md5 hexdigest or GCG checksum of each sequence.
Output is an N + 1 column file (where N = number of input fasta files).
If there are duplicates within a given fasta file, they will all be
... | 2.301177 | 2.226009 | 1.033768 |
qualfile1 = fastafile.rsplit(".", 1)[0] + suffix
qualfile2 = fastafile + suffix
if check:
if op.exists(qualfile1):
logging.debug("qual file `{0}` found".format(qualfile1))
return qualfile1
elif op.exists(qualfile2):
logging.debug("qual file `{0}` fou... | def get_qual(fastafile, suffix=QUALSUFFIX, check=True) | Check if current folder contains a qual file associated with the fastafile | 2.129154 | 2.068414 | 1.029365 |
p = OptionParser(some.__doc__)
p.add_option("--exclude", default=False, action="store_true",
help="Output sequences not in the list file [default: %default]")
p.add_option("--uniprot", default=False, action="store_true",
help="Header is from uniprot [default: %default]")
op... | def some(args) | %prog some fastafile listfile outfastafile
generate a subset of fastafile, based on a list | 2.547184 | 2.406552 | 1.058437 |
from jcvi.formats.fastq import FastqLite
p = OptionParser(fastq.__doc__)
p.add_option("--qv", type="int",
help="Use generic qv value [dafault: %default]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
fastafile, = args
fastq... | def fastq(args) | %prog fastq fastafile
Generate fastqfile by combining fastafile and fastafile.qual.
Also check --qv option to use a default qv score. | 3.069477 | 2.871927 | 1.068786 |
p = OptionParser(pair.__doc__)
p.set_sep(sep=None, help="Separator in name to reduce to clone id" +\
"e.g. GFNQ33242/1 use /, BOT01-2453H.b1 use .")
p.add_option("-m", dest="matepairs", default=False, action="store_true",
help="generate .matepairs file [often used for Celer... | def pair(args) | %prog pair fastafile
Generate .pairs.fasta and .fragments.fasta by matching records
into the pairs and the rest go to fragments. | 3.192271 | 3.104645 | 1.028224 |
from jcvi.utils.iter import pairwise
p = OptionParser(pairinplace.__doc__)
p.add_option("-r", dest="rclip", default=1, type="int",
help="pair ID is derived from rstrip N chars [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_hel... | def pairinplace(args) | %prog pairinplace bulk.fasta
Pair up the records in bulk.fasta by comparing the names for adjacent
records. If they match, print to bulk.pairs.fasta, else print to
bulk.frags.fasta. | 3.417743 | 3.176881 | 1.075817 |
p = OptionParser(extract.__doc__)
p.add_option('--newname', help="Use this new name instead")
p.add_option('--include', default=False, action="store_true",
help="search description line for match [default: %default]")
p.add_option('--exclude', default=False, action="store_true",
... | def extract(args) | %prog extract fasta query
extract query out of fasta file, query needs to be in the form of
"seqname", or "seqname:start-stop", or "seqname:start-stop:-" | 2.849163 | 2.717394 | 1.048491 |
seen = set()
for rec in SeqIO.parse(fastafile, "fasta"):
name = str(rec.seq) if seq else rec.id
if name in seen:
logging.debug("ignore {0}".format(rec.id))
continue
seen.add(name)
yield rec | def _uniq_rec(fastafile, seq=False) | Returns unique records | 2.488253 | 2.474604 | 1.005516 |
p = OptionParser(uniq.__doc__)
p.add_option("--seq", default=False, action="store_true",
help="Uniqify the sequences [default: %default]")
p.add_option("-t", "--trimname", dest="trimname",
action="store_true", default=False,
help="turn on the defline trim to first sp... | def uniq(args) | %prog uniq fasta uniq.fasta
remove fasta records that are the same | 3.417008 | 3.224139 | 1.059821 |
from random import sample
p = OptionParser(random.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
fastafile, N = args
N = int(N)
assert N > 0
f = Fasta(fastafile)
fw = must_open("stdout", "w")
for key in sample(f.keys(), ... | def random(args) | %prog random fasta 100 > random100.fasta
Take number of records randomly from fasta | 2.803113 | 2.586 | 1.083957 |
from Bio.SeqIO.QualityIO import PairedFastaQualIterator
if not qualfile:
qualfile = make_qual(fastafile, score=defaultqual)
rec_iter = PairedFastaQualIterator(open(fastafile), open(qualfile))
for rec in rec_iter:
yield rec if not modify else modify_qual(rec) | def iter_fasta_qual(fastafile, qualfile, defaultqual=OKQUAL, modify=False) | used by trim, emits one SeqRecord with quality values in it | 3.839351 | 3.598809 | 1.06684 |
from jcvi.algorithms.maxsum import max_sum
p = OptionParser(trim.__doc__)
p.add_option("-c", dest="min_length", type="int", default=64,
help="minimum sequence length after trimming")
p.add_option("-s", dest="score", default=QUAL,
help="quality trimming cutoff [default: %de... | def trim(args) | %prog trim fasta.screen newfasta
take the screen output from `cross_match` (against a vector db, for
example), then trim the sequences to remove X's. Will also perform quality
trim if fasta.screen.qual is found. The trimming algorithm is based on
finding the subarray that maximize the sum | 3.06593 | 2.95052 | 1.039115 |
p = OptionParser(sequin.__doc__)
p.add_option("--unk", default=100, type="int",
help="The size for unknown gaps [default: %default]")
p.add_option("--newid", default=None,
help="Use this identifier instead [default: %default]")
p.add_option("--chromosome", default=None,
... | def sequin(args) | %prog sequin inputfasta
Generate a gapped fasta format with known gap sizes embedded. suitable for
Sequin submission.
A gapped sequence represents a newer method for describing non-contiguous
sequences, but only requires a single sequence identifier. A gap is
represented by a line that starts with... | 2.698813 | 2.506472 | 1.076738 |
p = OptionParser(tidy.__doc__)
p.add_option("--gapsize", dest="gapsize", default=0, type="int",
help="Set all gaps to the same size [default: %default]")
p.add_option("--minlen", dest="minlen", default=100, type="int",
help="Minimum component size [default: %default]")
opts... | def tidy(args) | %prog tidy fastafile
Trim terminal Ns, normalize gap sizes and remove small components. | 2.726196 | 2.451304 | 1.112141 |
from jcvi.formats.sizes import agp
from jcvi.formats.agp import mask, build
p = OptionParser(gaps.__doc__)
p.add_option("--split", default=False, action="store_true",
help="Generate .split.fasta [default: %default]")
p.set_mingap(default=100)
p.set_cpus()
opts, args = p.par... | def gaps(args) | %prog gaps fastafile
Print out a list of gaps in BED format (.gaps.bed). | 2.799631 | 2.740386 | 1.021619 |
start = start - 1 if start is not None else 0
stop = stop if stop is not None else len(fasta)
if start < 0:
msg = "start ({0}) must > 0 of `{1}`. Reset to 1".\
format(start + 1, fasta.id)
logging.error(msg)
start = 0
... | def subseq(cls, fasta, start=None, stop=None, strand=None) | Take Bio.SeqRecord and slice "start:stop" from it, does proper
index and error handling | 2.5444 | 2.525471 | 1.007495 |
assert 'chr' in f, "`chr` field required"
name = f['chr']
assert name in self, "feature: %s not in `%s`" % \
(f, self.filename)
fasta = self[f['chr']]
seq = Fasta.subseq(fasta,
f.get('start'), f.get('stop'), f.get('strand'))
i... | def sequence(self, f, asstring=True) | Emulate brentp's pyfasta/fasta.py sequence() methods
take a feature and use the start/stop or exon_keys to return
the sequence from the assocatied fasta file:
f: a feature
asstring: if true, return the sequence as a string
: if false, return as a biopython Seq
... | 5.273304 | 4.930429 | 1.069543 |
start = frame
while start + 3 <= self.size:
yield self.sequence[start : start + 3], start
start += 3 | def codons(self, frame) | A generator that yields DNA in one codon blocks
"frame" counts for 0. This function yields a tuple (triplet, index) with
index relative to the original DNA sequence | 4.596102 | 4.250275 | 1.081366 |
orf_start = None
for c, index in self.codons(frame):
if (c not in self.stop and (c in self.start or not self.start)
and orf_start is None):
orf_start = index
elif c in self.stop and orf_start is not None:
self._update_longe... | def scan_sequence(self, frame, direction) | Search in one reading frame | 2.930113 | 2.97646 | 0.984429 |
if not ca:
return s[:-1]
if s[0] == '1':
return s[2:]
return s.rstrip('ab') | def clone_name(s, ca=False) | >>> clone_name("120038881639")
"0038881639"
>>> clone_name("GW11W6RK01DAJDWa")
"GW11W6RK01DAJDW" | 7.140831 | 8.543545 | 0.835816 |
fp = must_open(bedfile)
fw = must_open(bedpefile, "w")
if pairsbedfile:
fwpairs = must_open(pairsbedfile, "w")
clones = defaultdict(list)
for row in fp:
b = BedLine(row)
name = b.accn
clonename = clone_name(name, ca=ca)
clones[clonename].append(b)
i... | def bed_to_bedpe(bedfile, bedpefile, pairsbedfile=None, matesfile=None, ca=False, strand=False) | This converts the bedfile to bedpefile, assuming the reads are from CA. | 2.620827 | 2.63766 | 0.993618 |
p = OptionParser(posmap.__doc__)
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(p.print_help())
frgscffile, fastafile, scf = args
# fasta
cmd = "faOneRecord {0} {1}".format(fastafile, scf)
scffastafile = scf + ".fasta"
if not op.exists(scffastafile):
... | def posmap(args) | %prog posmap frgscf.sorted scf.fasta scfID
Perform QC on the selected scfID, generate multiple BED files for plotting. | 3.261611 | 3.032129 | 1.075684 |
'Updates the widget to show the ETA or total time when finished.'
if pbar.currval == 0:
return 'ETA: --:--:--'
elif pbar.finished:
return 'Time: %s' % self.format_time(pbar.seconds_elapsed)
else:
elapsed = pbar.seconds_elapsed
eta = elaps... | def update(self, pbar) | Updates the widget to show the ETA or total time when finished. | 4.027123 | 2.95699 | 1.361899 |
'Updates the widget with the current SI prefixed speed.'
if pbar.seconds_elapsed < 2e-6 or pbar.currval < 2e-6: # =~ 0
scaled = power = 0
else:
speed = pbar.currval / pbar.seconds_elapsed
power = int(math.log(speed, 1000))
scaled = speed / 1000.**... | def update(self, pbar) | Updates the widget with the current SI prefixed speed. | 7.558087 | 5.454376 | 1.385692 |
'''Updates the widget to show the next marker or the first marker when
finished'''
if pbar.finished: return self.markers[0]
self.curmark = (self.curmark + 1) % len(self.markers)
return self.markers[self.curmark] | def update(self, pbar) | Updates the widget to show the next marker or the first marker when
finished | 6.7312 | 3.399904 | 1.979821 |
'Updates the progress bar and its subcomponents'
left, marker, right = (format_updatable(i, pbar) for i in
(self.left, self.marker, self.right))
width -= len(left) + len(right)
# Marker must *always* have length of 1
marker *= int(pbar.currval / p... | def update(self, pbar, width) | Updates the progress bar and its subcomponents | 4.440053 | 4.251541 | 1.04434 |
'Updates the progress bar and its subcomponents'
left, marker, right = (format_updatable(i, pbar) for i in
(self.left, self.marker, self.right))
width -= len(left) + len(right)
if pbar.finished: return '%s%s%s' % (left, width * marker, right)
po... | def update(self, pbar, width) | Updates the progress bar and its subcomponents | 4.107019 | 4.010668 | 1.024024 |
'Tries to catch resize signals sent from the terminal.'
h, w = array('h', ioctl(self.fd, termios.TIOCGWINSZ, '\0' * 8))[:2]
self.term_width = w | def _handle_resize(self, signum=None, frame=None) | Tries to catch resize signals sent from the terminal. | 7.59286 | 4.242216 | 1.789834 |
'Joins the widgets and justifies the line'
widgets = ''.join(self._format_widgets())
if self.left_justify: return widgets.ljust(self.term_width)
else: return widgets.rjust(self.term_width) | def _format_line(self) | Joins the widgets and justifies the line | 7.440477 | 4.771089 | 1.559492 |
'Returns whether the ProgressBar should redraw the line.'
if self.currval >= self.next_update or self.finished: return True
delta = time.time() - self.last_update_time
return self._time_sensitive and delta > self.poll | def _need_update(self) | Returns whether the ProgressBar should redraw the line. | 13.859288 | 9.534692 | 1.453564 |
'Checks all widgets for the time sensitive bit'
self._time_sensitive = any(getattr(w, 'TIME_SENSITIVE', False)
for w in self.widgets) | def _update_widgets(self) | Checks all widgets for the time sensitive bit | 11.950857 | 5.654054 | 2.113679 |
'Updates the ProgressBar to a new value.'
if value is not None and value is not UnknownLength:
if (self.maxval is not UnknownLength
and not 0 <= value <= self.maxval):
raise ValueError('Value out of range')
self.currval = value
if not ... | def update(self, value=None) | Updates the ProgressBar to a new value. | 4.465471 | 4.306525 | 1.036908 |
'''Starts measuring time, and prints the bar at 0%.
It returns self so you can use it like this:
>>> pbar = ProgressBar().start()
>>> for i in range(100):
... # do something
... pbar.update(i+1)
...
>>> pbar.finish()
'''
if self.max... | def start(self) | Starts measuring time, and prints the bar at 0%.
It returns self so you can use it like this:
>>> pbar = ProgressBar().start()
>>> for i in range(100):
... # do something
... pbar.update(i+1)
...
>>> pbar.finish() | 4.076032 | 2.637952 | 1.54515 |
'Puts the ProgressBar bar in the finished state.'
self.finished = True
self.update(self.maxval)
self.fd.write('\n')
if self.signal_set:
signal.signal(signal.SIGWINCH, signal.SIG_DFL) | def finish(self) | Puts the ProgressBar bar in the finished state. | 7.168081 | 5.134816 | 1.395976 |
from jcvi.graphics.base import plt, savefig
from jcvi.graphics.chromosome import ChromosomeMap
p = OptionParser(plot.__doc__)
p.add_option("--firstn", type="int", help="Only plot the first N genes")
p.add_option("--ymax", type="int", help="Y-axis max value")
p.add_option("--log", action="s... | def plot(args) | %prog plot tagged.new.bed chr1
Plot gene identifiers along a particular chromosome, often to illustrate the
gene id assignment procedure. | 2.960505 | 2.878901 | 1.028346 |
p = OptionParser(instantiate.__doc__)
p.set_annot_reformat_opts()
p.add_option("--extended_stride", default=False, action="store_true",
help="Toggle extended strides for gene numbering")
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
... | def instantiate(args) | %prog instantiate tagged.bed blacklist.ids big_gaps.bed
instantiate NEW genes tagged by renumber. | 4.102789 | 3.818015 | 1.074587 |
pf = bedfile.rsplit(".", 1)[0]
abedfile = pf + ".a.bed"
bbedfile = pf + ".b.bed"
fwa = open(abedfile, "w")
fwb = open(bbedfile, "w")
bed = Bed(bedfile)
seen = set()
for b in bed:
accns = b.accn.split(";")
new_accns = []
for accn in accns:
if ":" ... | def prepare(bedfile) | Remove prepended tags in gene names. | 2.753028 | 2.748165 | 1.00177 |
from jcvi.algorithms.lis import longest_increasing_subsequence
from jcvi.utils.grouper import Grouper
p = OptionParser(renumber.__doc__)
p.set_annot_reformat_opts()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
bedfile, = args
pf = bedf... | def renumber(args) | %prog renumber Mt35.consolidated.bed > tagged.bed
Renumber genes for annotation updates. | 3.613333 | 3.554373 | 1.016588 |
import string
p = OptionParser(rename.__doc__)
p.add_option("-a", dest="gene_increment", default=10, type="int",
help="Increment for continuous genes [default: %default]")
p.add_option("-b", dest="gap_increment", default=1000, type="int",
help="Increment for gaps ... | def rename(args) | %prog rename genes.bed [gaps.bed]
Rename genes for annotation release.
For genes on chromosomes (e.g. the 12th gene on C1):
Bo1g00120
For genes on scaffolds (e.g. the 12th gene on unplaced Scaffold00285):
Bo00285s120
The genes identifiers will increment by 10. So assuming no gap, these are
... | 3.200842 | 2.917367 | 1.097168 |
pf, id = (), identifier
if "|" in identifier:
pf, id = tuple(identifier.split('|')[:-1]), identifier.split('|')[-1]
return pf, id | def parse_prefix(identifier) | Parse identifier such as a|c|le|d|li|re|or|AT4G00480.1 and return
tuple of prefix string (separated at '|') and suffix (AGI identifier) | 6.167175 | 4.885639 | 1.262307 |
p = OptionParser(publocus.__doc__)
p.add_option("--locus_tag", default="MTR_",
help="GenBank locus tag [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
locus_tag = opts.locus_tag
index = AutoVivification()
... | def publocus(args) | %prog publocus idsfile > idsfiles.publocus
Given a list of model identifiers, convert each into a GenBank approved
pub_locus.
Example output:
Medtr1g007020.1 MTR_1g007020
Medtr1g007030.1 MTR_1g007030
Medtr1g007060.1 MTR_1g007060A
Medtr1g007060.2 MTR_1g007060B | 2.915756 | 2.765725 | 1.054246 |
from jcvi.formats.gff import Gff
p = OptionParser(augustus.__doc__)
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
ingff3, = args
gff = Gff(ingff3)
fw = must_open(opts.outfile, "w")
seen = defaultdict(int)
for g in ... | def augustus(args) | %prog augustus augustus.gff3 > reformatted.gff3
AUGUSTUS does generate a gff3 (--gff3=on) but need some refinement. | 2.521109 | 2.380777 | 1.058944 |
from jcvi.formats.gff import sort
p = OptionParser(tRNAscan.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
trnaout, = args
gffout = trnaout + ".gff3"
fp = open(trnaout)
fw = open(gffout, "w")
next(fp)
next(fp)
row = n... | def tRNAscan(args) | %prog tRNAscan all.trna > all.trna.gff3
Convert tRNAscan-SE output into gff3 format.
Sequence tRNA Bounds tRNA Anti Intron Bounds Cove
Name tRNA # Begin End Type Codon Begin End Score
-------- ------ ---- ... | 3.146721 | 2.900554 | 1.084869 |
p = OptionParser(summary.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
fastafile, = args
f = Fasta(fastafile, index=False)
halfmaskedseqs = set()
allmasked = 0
allbases = 0
cutoff = 50
for key, seq in f.iteritems():
... | def summary(args) | %prog summary fastafile
Report the number of bases and sequences masked. | 3.017741 | 2.832952 | 1.065229 |
p = OptionParser(mask.__doc__)
p.add_option("--hard", dest="hard", default=False, action="store_true",
help="Hard mask the low-complexity bases [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
genomefile, = args
# e... | def mask(args) | %prog mask fastafile
This script pipelines the windowmasker in NCBI BLAST+. Masked fasta file
will have an appended suffix of .mask with all the low-complexity bases masked
(default to lower case, set --hard for hardmasking). | 3.544256 | 3.143801 | 1.127379 |
group.sort()
pos = bisect_left(group, (query, 0))
left_flanker = group[0] if pos == 0 else group[pos-1]
right_flanker = group[-1] if pos == len(group) else group[pos]
# pick the closest flanker
if abs(query - left_flanker[0]) < abs(query - right_flanker[0]):
flanker, other = left_fl... | def get_flanker(group, query) | >>> get_flanker([(370, 15184), (372, 15178), (373, 15176), (400, 15193)], 385)
((373, 15176), (400, 15193), True)
>>> get_flanker([(124, 13639), (137, 13625)], 138)
((137, 13625), (137, 13625), False) | 2.173206 | 2.331902 | 0.931946 |
regions = []
ysorted = sorted(data, key=lambda x: x[1])
g = Grouper()
a, b = tee(ysorted)
next(b, None)
for ia, ib in izip(a, b):
pos1, pos2 = ia[1], ib[1]
if pos2 - pos1 < window and sbed[pos1].seqid == sbed[pos2].seqid:
g.join(ia, ib)
for group in sorted(... | def find_synteny_region(query, sbed, data, window, cutoff, colinear=False) | Get all synteny blocks for a query, algorithm is single linkage
anchors are a window centered on query
Two categories of syntenic regions depending on what query is:
(Syntelog): syntenic region is denoted by the syntelog
(Gray gene): syntenic region is marked by the closest flanker | 5.017644 | 4.566099 | 1.098891 |
m, n = len(qpadnames), len(spadnames)
qpadorder, spadorder = qpadbed.order, spadbed.order
qpadid = dict((a, i) for i, a in enumerate(qpadnames))
spadid = dict((a, i) for i, a in enumerate(spadnames))
qpadlen = dict((a, len(b)) for a, b in qpadbed.sub_beds())
spadlen = dict((a, len(b)) for a... | def make_arrays(blastfile, qpadbed, spadbed, qpadnames, spadnames) | This function makes three matrices: observed, expected and logmp. The logmp
contains the statistical significance for each comparison. | 2.712725 | 2.601244 | 1.042857 |
from jcvi.formats.cdt import CDT
p = OptionParser(pad.__doc__)
p.set_beds()
p.add_option("--cutoff", default=.3, type="float",
help="The clustering cutoff to call similar [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.prin... | def pad(args) | %prog pad blastfile cdtfile --qbed q.pad.bed --sbed s.pad.bed
Test and reconstruct candidate PADs. | 3.659804 | 3.450032 | 1.060803 |
from jcvi.utils.range import range_chain, LEFT, RIGHT
NUL = 2
selected, score = range_chain(ranges)
endpoints = [(x.start, NUL) for x in selected]
endpoints += [(x[0], LEFT) for x in extra]
endpoints += [(x[1], RIGHT) for x in extra]
endpoints.sort()
current_left = 0
for a, a... | def get_segments(ranges, extra, minsegment=40) | Given a list of Range, perform chaining on the ranges and select a highest
scoring subset and cut based on their boundaries. Let's say the projection
of the synteny blocks onto one axis look like the following.
1=====10......20====30....35====~~
Then the segmentation will yield a block [1, 20), [20, 3... | 4.174054 | 4.235098 | 0.985586 |
from jcvi.utils.range import Range
p = OptionParser(cluster.__doc__)
p.set_beds()
p.add_option("--minsize", default=10, type="int",
help="Only segment using blocks >= size [default: %default]")
p.add_option("--path", default="~/scratch/bin",
help="Path to the ... | def cluster(args) | %prog cluster blastfile anchorfile --qbed qbedfile --sbed sbedfile
Cluster the segments and form PAD. This is the method described in Tang et
al. (2010) PNAS paper. The anchorfile defines a list of synteny blocks,
based on which the genome on one or both axis can be chopped up into pieces
and clustered... | 3.189967 | 3.07571 | 1.037148 |
p = OptionParser(cat.__doc__.format(page_range_help=PAGE_RANGE_HELP))
p.add_option("--nosort", default=False, action="store_true",
help="Do not sort file names")
p.add_option("--cleanup", default=False, action="store_true",
help="Remove individual pdfs after merging")
... | def cat(args) | %prog cat *.pdf -o output.pdf
Concatenate pages from pdf files into a single pdf file.
Page ranges refer to the previously-named file.
A file not followed by a page range means all the pages of the file.
PAGE RANGES are like Python slices.
{page_range_help}
EXAMPLES
pdfcat -o ... | 2.654883 | 2.533564 | 1.047885 |
l = len(kmer) - 2
k = l if l < 64 else 64
counts = defaultdict(int)
for i in range(l):
trinuc = kmer[i: i + 3]
counts[trinuc] += 1
logk = math.log(k)
res = 0
for k, v in counts.items():
f = v * 1. / l
res += f * math.log(f) / logk
return res * -100 | def entropy_score(kmer) | Schmieder and Edwards. Quality control and preprocessing of metagenomic datasets. (2011) Bioinformatics
https://academic.oup.com/bioinformatics/article/27/6/863/236283/Quality-control-and-preprocessing-of-metagenomic | 3.327209 | 3.379021 | 0.984666 |
p = OptionParser(entropy.__doc__)
p.add_option("--threshold", default=0, type="int",
help="Complexity needs to be above")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
kmc_out, = args
fp = open(kmc_out)
for row in fp:
k... | def entropy(args) | %prog entropy kmc_dump.out
kmc_dump.out contains two columns:
AAAAAAAAAAAGAAGAAAGAAA 34 | 3.336012 | 3.180103 | 1.049026 |
from jcvi.formats.fasta import rc, parse_fasta
p = OptionParser(bed.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
fastafile, dumpfile = args
fp = open(dumpfile)
KMERS = set()
for row in fp:
kmer = row.split()[0]
k... | def bed(args) | %prog bed fastafile kmer.dump.txt
Map kmers on FASTA. | 2.433812 | 2.177671 | 1.117622 |
p = OptionParser(kmcop.__doc__)
p.add_option("--action", choices=("union", "intersect"),
default="union", help="Action")
p.add_option("-o", default="results", help="Output name")
opts, args = p.parse_args(args)
if len(args) < 2:
sys.exit(not p.print_help())
indices... | def kmcop(args) | %prog kmcop *.kmc_suf
Intersect or union kmc indices. | 3.752324 | 3.232098 | 1.160956 |
p = OptionParser(kmc.__doc__)
p.add_option("-k", default=21, type="int", help="Kmer size")
p.add_option("--ci", default=2, type="int",
help="Exclude kmers with less than ci counts")
p.add_option("--cs", default=2, type="int",
help="Maximal value of a counter")
... | def kmc(args) | %prog kmc folder
Run kmc3 on Illumina reads. | 3.091515 | 3.034688 | 1.018726 |
p = OptionParser(meryl.__doc__)
p.add_option("-k", default=19, type="int", help="Kmer size")
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
folder, = args
K = opts.k
cpus = opts.cpus
mm = MakeManager()
for p, pf in iter... | def meryl(args) | %prog meryl folder
Run meryl on Illumina reads. | 3.420545 | 3.272519 | 1.045233 |
from scipy.stats import binom, poisson
p = OptionParser(model.__doc__)
p.add_option("-k", default=23, type="int", help="Kmer size")
p.add_option("--cov", default=50, type="int", help="Expected coverage")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help(... | def model(args) | %prog model erate
Model kmer distribution given error rate. See derivation in FIONA paper:
<http://bioinformatics.oxfordjournals.org/content/30/17/i356.full> | 4.303513 | 3.815313 | 1.127958 |
from math import log
from jcvi.formats.base import DictFile
p = OptionParser(logodds.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
cnt1, cnt2 = args
d = DictFile(cnt2)
fp = open(cnt1)
for row in fp:
scf, c1 = row.spli... | def logodds(args) | %prog logodds cnt1 cnt2
Compute log likelihood between two db. | 2.519497 | 2.364323 | 1.065631 |
from bitarray import bitarray
p = OptionParser(count.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
fastafile, jfdb = args
K = get_K(jfdb)
cmd = "jellyfish query {0} -C | cut -d' ' -f 2".format(jfdb)
t = must_open("tmp", "w")
... | def count(args) | %prog count fastafile jf.db
Run dump - jellyfish - bin - bincount in serial. | 3.419256 | 3.082718 | 1.109169 |
from bitarray import bitarray
from jcvi.formats.sizes import Sizes
p = OptionParser(bincount.__doc__)
p.add_option("-K", default=23, type="int",
help="K-mer size [default: %default]")
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(... | def bincount(args) | %prog bincount fastafile binfile
Count K-mers in the bin. | 2.581566 | 2.278369 | 1.133076 |
from bitarray import bitarray
p = OptionParser(bin.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
inp, outp = args
fp = must_open(inp)
fw = must_open(outp, "w")
a = bitarray()
for row in fp:
c = row.split()[-1]
... | def bin(args) | %prog bin filename filename.bin
Serialize counts to bitarrays. | 2.768208 | 2.62714 | 1.053697 |
p = OptionParser(dump.__doc__)
p.add_option("-K", default=23, type="int",
help="K-mer size [default: %default]")
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
fastafile, = args
K = opts.K
fw = must_open(opt... | def dump(args) | %prog dump fastafile
Convert FASTA sequences to list of K-mers. | 2.375031 | 2.042125 | 1.163019 |
from jcvi.apps.base import getfilesize
from jcvi.utils.cbook import human_size
p = OptionParser(jellyfish.__doc__)
p.add_option("-K", default=23, type="int",
help="K-mer size [default: %default]")
p.add_option("--coverage", default=40, type="int",
help="Expecte... | def jellyfish(args) | %prog jellyfish [*.fastq|*.fasta]
Run jellyfish to dump histogram to be used in kmer.histogram(). | 2.838264 | 2.760062 | 1.028333 |
pf, sf = op.splitext(merylfile)
outfile = pf + ".histogram"
if need_update(merylfile, outfile):
cmd = "meryl -Dh -s {0}".format(pf)
sh(cmd, outfile=outfile)
return outfile | def merylhistogram(merylfile) | Run meryl to dump histogram to be used in kmer.histogram(). The merylfile
are the files ending in .mcidx or .mcdat. | 7.375899 | 7.091737 | 1.040069 |
p = OptionParser(multihistogram.__doc__)
p.add_option("--kmin", default=15, type="int",
help="Minimum K-mer size, inclusive")
p.add_option("--kmax", default=30, type="int",
help="Maximum K-mer size, inclusive")
p.add_option("--vmin", default=2, type="int",
help="... | def multihistogram(args) | %prog multihistogram *.histogram species
Plot the histogram based on a set of K-mer hisotograms. The method is based
on Star et al.'s method (Atlantic Cod genome paper). | 2.475554 | 2.42689 | 1.020052 |
p = OptionParser(histogram.__doc__)
p.add_option("--vmin", dest="vmin", default=1, type="int",
help="minimum value, inclusive [default: %default]")
p.add_option("--vmax", dest="vmax", default=100, type="int",
help="maximum value, inclusive [default: %default]")
p.add_option(... | def histogram(args) | %prog histogram meryl.histogram species K
Plot the histogram based on meryl K-mer distribution, species and N are
only used to annotate the graphic. | 3.191788 | 3.034657 | 1.051779 |
db = get_abs_path(db)
nin = db + ".nin"
run_formatdb(infile=db, outfile=nin)
cmd = "blastn"
cmd += " -task blastn"
cmd += " -query {0} -db {1} -out {2}".format(infile, db, outfile)
cmd += " -penalty -5 -gapopen 4 -gapextend 4 -dust yes -soft_masking true"
cmd += " -searchsp 1750000... | def run_vecscreen(infile=None, outfile=None, db="UniVec_Core",
pctid=None, hitlen=None) | BLASTN parameters reference:
http://www.ncbi.nlm.nih.gov/VecScreen/VecScreen_docs.html | 4.233618 | 4.274263 | 0.990491 |
from itertools import product
from jcvi.apps.grid import MakeManager
from jcvi.formats.base import split
p = OptionParser(nucmer.__doc__)
p.add_option("--chunks", type="int",
help="Split both query and subject into chunks")
p.set_params(prog="nucmer", params="-l 100 -c 50... | def nucmer(args) | %prog nucmer ref.fasta query.fasta
Run NUCMER using query against reference. Parallel implementation derived
from: <https://github.com/fritzsedlazeck/sge_mummer> | 3.415491 | 3.422866 | 0.997846 |
from jcvi.apps.grid import MakeManager
from jcvi.utils.iter import grouper
p = OptionParser(blasr.__doc__)
p.set_cpus(cpus=8)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
reffasta, fofn = args
flist = sorted([x.strip() for x in open(fofn... | def blasr(args) | %prog blasr ref.fasta fofn
Run blasr on a set of PacBio reads. This is based on a divide-and-conquer
strategy described below. | 2.90783 | 2.873731 | 1.011866 |
p = OptionParser(blat.__doc__)
p.set_align(pctid=95, hitlen=30)
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
reffasta, queryfasta = args
blastfile = get_outfile(reffasta, queryfasta, suffix="blat")
run_blat(infile=queryfasta... | def blat(args) | %prog blat ref.fasta query.fasta
Calls blat and filters BLAST hits. | 2.884622 | 2.706221 | 1.065923 |
task_choices = ("blastn", "blastn-short", "dc-megablast", \
"megablast", "vecscreen")
p = OptionParser(blast.__doc__)
p.set_align(pctid=0, evalue=.01)
p.add_option("--wordsize", type="int", help="Word size [default: %default]")
p.add_option("--best", default=1, type="int",
... | def blast(args) | %prog blast ref.fasta query.fasta
Calls blast and then filter the BLAST hits. Default is megablast. | 3.146474 | 2.989973 | 1.052342 |
from jcvi.apps.grid import MakeManager
p = OptionParser(lastgenome.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
gA, gB = args
mm = MakeManager()
bb = lambda x : op.basename(x).rsplit(".", 1)[0]
gA_pf, gB_pf = bb(gA), bb(gB)
... | def lastgenome(args) | %prog genome_A.fasta genome_B.fasta
Run LAST by calling LASTDB, LASTAL and LAST-SPLIT. The recipe is based on
tutorial here:
<https://github.com/mcfrith/last-genome-alignments>
The script runs the following steps:
$ lastdb -P0 -uNEAR -R01 Chr10A-NEAR Chr10A.fa
$ lastal -E0.05 -C2 Chr10A-NEAR ... | 3.931587 | 2.280395 | 1.724082 |
p = OptionParser(last.__doc__)
p.add_option("--dbtype", default="nucl",
choices=("nucl", "prot"),
help="Molecule type of subject database")
p.add_option("--path", help="Specify LAST path")
p.add_option("--mask", default=False, action="store_true", help="Invoke -c i... | def last(args, dbtype=None) | %prog database.fasta query.fasta
Run LAST by calling LASTDB and LASTAL. LAST program available:
<http://last.cbrc.jp>
Works with LAST-719. | 3.593852 | 3.313951 | 1.084461 |
p = OptionParser(extract.__doc__)
p.add_option("--format", default=False, action="store_true",
help="enable flag to reformat header into a symbol separated list of constituent reads "+ \
"[default: %default]")
p.add_option("--singlets", default=False, action="store_true",
... | def extract(args) | %prog extract [--options] ace_file
Extract contigs from ace file and if necessary reformat header with
a pipe(|) separated list of constituent reads. | 3.594482 | 3.140971 | 1.144386 |
from jcvi.utils.table import tabulate
p = OptionParser(report.__doc__)
types = {"read": ["padded_start", "padded_end", "orient"],
"consensus": ["padded_consensus_start", "padded_consensus_end"],
"quality" : ["qual_clipping_start", "qual_clipping_end", "align_clipping_s... | def report(args) | %prog report [--options] ace_file > report
Prepare a report of read location, consensus location or quality segment per contig | 2.728382 | 2.595306 | 1.051276 |
p = OptionParser(correct.__doc__)
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) < 1:
sys.exit(not p.print_help())
lstfile = "reads2cor.lst"
fw = open(lstfile, "w")
print("\n".join(x for x in args if x[:2] == "PE"), file=fw)
fw.close()
p1 = args[0]
offs... | def correct(args) | %prog correct *.fastq
Correct reads using ErrorCorrection. Only PE will be used to build the K-mer
table. | 4.266564 | 4.066124 | 1.049295 |
p = OptionParser(clean.__doc__)
p.add_option("-a", default=0, type="int",
help="Trim length at 5' end [default: %default]")
p.add_option("-b", default=50, type="int",
help="Trim length at 3' end [default: %default]")
p.set_cpus()
opts, args = p.parse_args(args)... | def clean(args) | %prog clean 1.fastq 2.fastq [insertsize]
Clean and dedup paired FASTQ files. | 2.889029 | 2.766288 | 1.04437 |
from jcvi.utils.cbook import SummaryStats, percentage, thousands
p = OptionParser(fillstats.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
fillfile, = args
fp = open(fillfile)
scaffolds = 0
gaps = []
for row in fp:
if ... | def fillstats(args) | %prog fillstats genome.fill
Build stats on .fill file from GapCloser. | 2.572788 | 2.539694 | 1.013031 |
from jcvi.formats.base import write_file
p = OptionParser(prepare.__doc__ + FastqNamings)
p.add_option("-K", default=45, type="int",
help="K-mer size [default: %default]")
p.add_option("--assemble_1st_rank_only", default=False, action="store_true",
help="Assemble ... | def prepare(args) | %prog prepare *.fastq
Scan input fastq files (see below) and write SOAP config files based
on inputfiles. Use "--scaffold contigs.fasta" to perform scaffolding. | 3.758321 | 3.601738 | 1.043474 |
'''Iterator over elements repeating each as many times as its count.
>>> c = Counter('ABCABC')
>>> sorted(c.elements())
['A', 'A', 'B', 'B', 'C', 'C']
If an element's count has been set to zero or is a negative number,
elements() will ignore it.
'''
for... | def elements(self) | Iterator over elements repeating each as many times as its count.
>>> c = Counter('ABCABC')
>>> sorted(c.elements())
['A', 'A', 'B', 'B', 'C', 'C']
If an element's count has been set to zero or is a negative number,
elements() will ignore it. | 4.717317 | 1.980368 | 2.38204 |
p = OptionParser(bed.__doc__)
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
pslfile, = args
fw = must_open(opts.outfile, "w")
psl = Psl(pslfile)
for p in psl:
print(p.bed12line, file=fw) | def bed(args) | %prog bed pslfile
Convert to bed format. | 2.811676 | 2.500688 | 1.124361 |
p = OptionParser(gff.__doc__)
p.add_option("--source", default="GMAP",
help="specify GFF source [default: %default]")
p.add_option("--type", default="EST_match",
help="specify GFF feature type [default: %default]")
p.add_option("--suffix", default=".match",
... | def gff(args) | %prog gff pslfile
Convert to gff format. | 3.00756 | 2.978796 | 1.009656 |
last = self.blockCount - 1
return ((self.tEnd == self.tStarts[last] + 3 * self.blockSizes[last]) \
and self.strand == "+") or \
((self.tStart == self.tSize - (self.tStarts[last] + 3 * self.blockSizes[last])\
and self.strand == "-")) | def _isProtein(self) | check if blockSizes and scores are in the protein space or not | 4.637963 | 4.024746 | 1.152362 |
sizeMult = self._sizeMult
qAlnSize, tAlnSize = self.qspan * sizeMult, self.tspan
alnSize = min(qAlnSize, tAlnSize)
if alnSize <= 0:
return 0
sizeDiff = qAlnSize - tAlnSize
if sizeDiff < 0:
sizeDiff = 0 if ismRNA else -sizeDiff
i... | def _milliBad(self, ismRNA=False) | calculate badness in parts per thousand
i.e. number of non-identical matches | 4.853752 | 4.695283 | 1.033751 |
prefix = glob(dir + "*.gkpStore")[0]
prefix = op.basename(prefix).rsplit(".", 1)[0]
return prefix | def get_prefix(dir="../") | Look for prefix.gkpStore in the upper directory. | 10.761915 | 4.4382 | 2.424838 |
from jcvi.formats.base import read_block
p = OptionParser(cnsfix.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
cnsfixout, = args
fp = open(cnsfixout)
utgs = []
saves = []
for header, contents in read_block(fp, "Evaluating"):
... | def cnsfix(args) | %prog cnsfix consensus-fix.out.FAILED > blacklist.ids
Parse consensus-fix.out to extract layouts for fixed unitigs. This will
mark all the failed fragments detected by utgcnsfix and pop them out of the
existing unitigs. | 4.900616 | 4.295329 | 1.140918 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.