code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
p = OptionParser(tigrprepare.__doc__) opts, args = p.parse_args(args) if len(args) != 4: sys.exit(not p.print_help()) fastafile, asmbl_id, db, pasa_db = args if asmbl_id == 'all': idsfile = fastafile + ".ids" if need_update(fastafile, idsfile): ids([fastafi...
def tigrprepare(args)
%prog tigrprepare asmbl.fasta asmbl.ids db pasa.terminal_exons.gff3 Run EVM in TIGR-only mode.
4.319391
3.621254
1.192789
p = OptionParser(uniq.__doc__) p.set_outfile() opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) gffile, cdsfasta = args gff = Gff(gffile) sizes = Sizes(cdsfasta).mapping gene_register = {} for g in gff: if g.type != "mRNA": ...
def uniq(args)
%prog uniq gffile cdsfasta Remove overlapping gene models. Similar to formats.gff.uniq(), overlapping 'piles' are processed, one by one. Here, we use a different algorithm, that retains the best non-overlapping subset witin each pile, rather than single best model. Scoring function is also differe...
4.784103
4.056575
1.179345
import __builtin__ from jcvi.utils.cbook import enumerate_reversed p = OptionParser(nmd.__doc__) p.set_outfile() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) gffile, = args gff = make_index(gffile) fw = must_open(opts.outfile, "w")...
def nmd(args)
%prog nmd gffile Identify transcript variants which might be candidates for nonsense mediated decay (NMD) A transcript is considered to be a candidate for NMD when the CDS stop codon is located more than 50nt upstream of terminal splice site donor References: http://www.nature.com/horizon/rna...
2.975805
2.871976
1.036152
symbols = {'+': '>', '-': '<'} for seqid, bs in bed.sub_beds(): prev_node, prev_strand = None, '+' for b in bs: accn = b.accn strand = b.strand node = "=".join(families[accn]) if prev_node: print("{}{}--{}{}".format(prev_node, ...
def print_edges(G, bed, families)
Instead of going through the graph construction, just print the edges.
4.492333
4.500399
0.998208
from jcvi.algorithms.graph import BiGraph p = OptionParser(fuse.__doc__) opts, args = p.parse_args(args) if len(args) < 1: sys.exit(not p.print_help()) bedfiles = [x for x in args if x.endswith(".bed")] anchorfiles = [x for x in args if x.endswith(".anchors")] # TODO: Use Ma...
def fuse(args)
%prog fuse *.bed *.anchors Fuse gene orders based on anchors file.
4.515965
4.088396
1.104581
import pygraphviz as pgv from jcvi.utils.iter import pairwise from jcvi.formats.base import SetFile p = OptionParser(adjgraph.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) infile, subgraph = args subgraph = SetFile(subgraph) ...
def adjgraph(args)
%prog adjgraph adjacency.txt subgraph.txt Construct adjacency graph for graphviz. The file may look like sample below. The lines with numbers are chromosomes with gene order information. genome 0 chr 0 -1 -13 -16 3 4 -6126 -5 17 -6 7 18 5357 8 -5358 5359 -9 -10 -11 5362 5360 chr 1 138 6133...
2.998851
2.954407
1.015043
p = OptionParser(pairs.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) anchorfile, prefix = args outfile = prefix + ".pairs" fw = open(outfile, "w") af = AnchorFile(anchorfile) blocks = af.blocks pad = len(str(len(blocks))) ...
def pairs(args)
%prog pairs anchorsfile prefix Convert anchorsfile to pairsfile.
2.861351
2.6448
1.081878
p = OptionParser(zipbed.__doc__) p.add_option("--prefix", default="b", help="Prefix for the new seqid [default: %default]") opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) bedfile, anchorfile = args prefix = opts.prefix bed = Be...
def zipbed(args)
%prog zipbed species.bed collinear.anchors Build ancestral contig from collinear blocks. For example, to build pre-rho order, use `zipbed rice.bed rice.rice.1x1.collinear.anchors`. The algorithms proceeds by interleaving the genes together.
3.164543
3.083869
1.02616
p = OptionParser(collinear.__doc__) p.set_beds() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) anchorfile, = args qbed, sbed, qorder, sorder, is_self = check_beds(anchorfile, p, opts) af = AnchorFile(anchorfile) newanchorfile = anchorfil...
def collinear(args)
%prog collinear a.b.anchors Reduce synteny blocks to strictly collinear, use dynamic programming in a procedure similar to DAGchainer.
3.34426
3.233208
1.034347
p = OptionParser(counts.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) vcffile, = args vcf_reader = vcf.Reader(open(vcffile)) for r in vcf_reader: v = CPRA(r) if not v.is_valid: continue for sample in r....
def counts(args)
%prog counts vcffile Collect allele counts from RO and AO fields.
3.161752
2.68715
1.176619
p = OptionParser(prepare.__doc__) p.add_option("--accuracy", default=.85, help="Sequencing per-base accuracy") opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) vcffile, bamfile = args right = "{:.2f}".format(opts.accuracy) wrong ...
def prepare(args)
%prog prepare vcffile bamfile Convert vcf and bam to variant list. Inputs are: - vcffile: contains the positions of variants - bamfile: contains the reads that hold the variants Outputs: - reads_to_phase: phasing for each read - variants_to_phase: in format of phased vcf
2.963151
2.925197
1.012975
return len(self.ref) == 1 and \ len(self.alt) == 1 and \ len(self.alt[0]) == 1
def is_valid(self)
Only retain SNPs or single indels, and are bi-allelic
3.85586
2.70543
1.42523
# Split. If there are no splits, return now s = regex.split(s) if len(s) == 1: return tuple(s) # Now convert the numbers to numbers, and leave strings as strings s = remove_empty(s) for i in range(len(s)): try: s[i] = numconv(s[i]) except ValueError: ...
def _number_finder(s, regex, numconv)
Helper to split numbers
4.568319
4.658287
0.980687
return sorted(seq, key=lambda x: natsort_key(key(x), number_type=number_type, signed=signed, exp=exp))
def natsorted(seq, key=lambda x: x, number_type=float, signed=True, exp=True)
\ Sorts a sequence naturally (alphabetically and numerically), not lexicographically. >>> a = ['num3', 'num5', 'num2'] >>> natsorted(a) ['num2', 'num3', 'num5'] >>> b = [('a', 'num3'), ('b', 'num5'), ('c', 'num2')] >>> from operator import itemgetter >>> natsorte...
2.370076
3.37059
0.703164
from operator import itemgetter item1 = itemgetter(1) # Pair the index and sequence together, then sort by index_seq_pair = [[x, key(y)] for x, y in zip(range(len(seq)), seq)] index_seq_pair.sort(key=lambda x: natsort_key(item1(x), number_type=n...
def index_natsorted(seq, key=lambda x: x, number_type=float, signed=True, exp=True)
\ Sorts a sequence naturally, but returns a list of sorted the indeces and not the sorted list. >>> a = ['num3', 'num5', 'num2'] >>> b = ['foo', 'bar', 'baz'] >>> index = index_natsorted(a) >>> index [2, 0, 1] >>> # Sort both lists by the sort order of a ...
3.398635
4.118252
0.825262
xargs = args[2:] p = OptionParser(calibrate.__doc__) opts, args, iopts = add_seeds_options(p, args) if len(args) != 2: sys.exit(not p.print_help()) imagefile, boxsize = args boxsize = float(boxsize) # Read in color checker colorcheckerfile = op.join(datadir, "colorchecker...
def calibrate(args)
%prog calibrate calibrate.JPG boxsize Calibrate pixel-inch ratio and color adjustment. - `calibrate.JPG` is the photo containig a colorchecker - `boxsize` is the measured size for the boxes on printed colorchecker, in squared centimeter (cm2) units
4.026233
3.709214
1.085468
from jcvi.formats.pdf import cat xargs = args[1:] p = OptionParser(batchseeds.__doc__) opts, args, iopts = add_seeds_options(p, args) if len(args) != 1: sys.exit(not p.print_help()) folder, = args folder = folder.rstrip('/') outdir = folder + "-debug" outfile = folder...
def batchseeds(args)
%prog batchseeds folder Extract seed metrics for each image in a directory.
3.758127
3.65714
1.027614
p = OptionParser(filterbedgraph.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) bedgraphfile, cutoff = args c = float(cutoff) fp = open(bedgraphfile) pf = bedgraphfile.rsplit(".", 1)[0] filteredbed = pf + ".filtered-{}.bed".format(c...
def filterbedgraph(args)
%prog filterbedgraph a.bedgraph 1 Filter the bedGraph, typically from the gem-mappability pipeline. Unique regions are 1, two copies .5, etc.
3.536202
3.525829
1.002942
p = OptionParser(tiling.__doc__) p.add_option("--overlap", default=3000, type="int", help="Minimum amount of overlaps required") p.set_verbose() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) bedfile, = args ov = opts.overlap ...
def tiling(args)
%prog tiling bedfile Compute minimum tiling path using as few clones as possible. Implemented with dynamic programming. Greedy algorithm may also work according a stackoverflow source.
3.267915
3.178959
1.027983
p = OptionParser(chain.__doc__) p.add_option("--dist", default=100000, help="Chaining distance") p.set_outfile() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) bedfile, = args cmd = "sort -k4,4 -k1,1 -k2,2n -k3,3n {0} -o {0}".format(bedfile) ...
def chain(args)
%prog chain bedfile Chain BED segments together.
2.669815
2.516366
1.06098
p = OptionParser(density.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) bedfile, fastafile = args bed = Bed(bedfile) sizes = Sizes(fastafile).mapping header = "seqid features size density_per_Mb".split() print("\t".join(header)) ...
def density(args)
%prog density bedfile ref.fasta Calculates density of features per seqid.
3.738964
3.24048
1.15383
p = OptionParser(clr.__doc__) p.set_bedpe() opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) bedpe, ref = args if bedpe.endswith(".bam"): bedpefile = bedpe.replace(".bam", ".bedpe") if need_update(bedpe, bedpefile): cmd = ...
def clr(args)
%prog clr [bamfile|bedpefile] ref.fasta Use mates from BEDPE to extract ranges where the ref is covered by mates. This is useful in detection of chimeric contigs.
2.715667
2.592768
1.0474
p = OptionParser(alignextend.__doc__) p.add_option("--len", default=100, type="int", help="Extend to this length") p.add_option("--qv", default=31, type="int", help="Dummy qv score for extended bases") p.add_option("--bedonly", default=False, action="store_true", ...
def alignextend(args)
%prog alignextend bedpefile ref.fasta Similar idea to alignextend, using mates from BEDPE and FASTA ref. See AMOS script here: https://github.com/nathanhaigh/amos/blob/master/src/Experimental/alignextend.pl
2.756646
2.79757
0.985372
p = OptionParser(seqids.__doc__) p.add_option("--maxn", default=100, type="int", help="Maximum number of seqids") p.add_option("--prefix", help="Seqids must start with") p.add_option("--exclude", default="random", help="Seqids should not contain") opts, args = p.parse_args(args...
def seqids(args)
%prog seqids bedfile Print out all seqids on one line. Useful for graphics.karyotype.
2.593969
2.45105
1.058309
from tempfile import mkstemp from pybedtools import BedTool p = OptionParser(juncs.__doc__) p.set_outfile() opts, args = p.parse_args(args) if len(args) < 1: sys.exit(not p.print_help()) fh, trimbed = mkstemp(suffix = ".bed") fw = must_open(trimbed, "w") for i, juncb...
def juncs(args)
%prog junctions junctions1.bed [junctions2.bed ...] Given a TopHat junctions.bed file, trim the read overhang to get intron span If more than one junction bed file is provided, uniq the junctions and calculate cumulative (sum) junction support
3.578962
3.486984
1.026378
from random import sample from jcvi.formats.base import flexible_cast p = OptionParser(random.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) bedfile, N = args assert is_number(N) b = Bed(bedfile) NN = flexible_cast(N) if ...
def random(args)
%prog random bedfile number_of_features Extract a random subset of features. Number of features can be an integer number, or a fractional number in which case a random fraction (for example 0.1 = 10% of all features) will be extracted.
3.220724
2.827135
1.139218
p = OptionParser(filter.__doc__) p.add_option("--minsize", default=0, type="int", help="Minimum feature length") p.add_option("--maxsize", default=1000000000, type="int", help="Minimum feature length") p.add_option("--minaccn", type="int", help="Mi...
def filter(args)
%prog filter bedfile Filter the bedfile to retain records between certain size range.
2.458642
2.313536
1.062721
p = OptionParser(mergebydepth.__doc__) p.add_option("--mindepth", default=3, type="int", help="Minimum depth required") opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) bedfile, fastafile = args mindepth = opts.mindepth bedgraph ...
def mergebydepth(args)
%prog mergebydepth reads.bed genome.fasta Similar to mergeBed, but only returns regions beyond certain depth.
3.144344
2.822086
1.114191
p = OptionParser(depth.__doc__) p.set_outfile() opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) readsbed, featsbed = args fp = open(featsbed) nargs = len(fp.readline().split("\t")) keepcols = ",".join(str(x) for x in range(1, nargs + 1)) ...
def depth(args)
%prog depth reads.bed features.bed Calculate depth depth per feature using coverageBed.
2.976961
2.518487
1.182043
key = lambda x: x.rsplit(".", 1)[0] iso_number = lambda x: get_number(x.split(".")[-1]) ids = sorted(ids, key=key) newids = [] for k, ii in groupby(ids, key=key): min_i = min(list(ii), key=iso_number) newids.append(min_i) return newids
def remove_isoforms(ids)
This is more or less a hack to remove the GMAP multiple mappings. Multiple GMAP mappings can be seen given the names .mrna1, .mrna2, etc.
3.305227
3.418669
0.966817
from jcvi.formats.sizes import Sizes p = OptionParser(longest.__doc__) p.add_option("--maxsize", default=20000, type="int", help="Limit max size") p.add_option("--minsize", default=60, type="int", help="Limit min size") p.add_option("--precedence", default="Me...
def longest(args)
%prog longest bedfile fastafile Select longest feature within overlapping piles.
2.978404
2.890622
1.030368
p = OptionParser(merge.__doc__) p.set_outfile() opts, args = p.parse_args(args) if len(args) < 1: sys.exit(not p.print_help()) bedfiles = args fw = must_open(opts.outfile, "w") for bedfile in bedfiles: bed = Bed(bedfile) pf = op.basename(bedfile).split(".")[0] ...
def merge(args)
%prog merge bedfiles > newbedfile Concatenate bed files together. Performing seqid and name changes to avoid conflicts in the new bed file.
2.704202
2.358712
1.146474
p = OptionParser(fix.__doc__) p.add_option("--minspan", default=0, type="int", help="Enforce minimum span [default: %default]") p.set_outfile() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) bedfile, = args minspan = opts.minsp...
def fix(args)
%prog fix bedfile > newbedfile Fix non-standard bed files. One typical problem is start > end.
2.470608
2.318221
1.065734
from jcvi.formats.base import SetFile from jcvi.utils.cbook import gene_name p = OptionParser(some.__doc__) p.add_option("-v", dest="inverse", default=False, action="store_true", help="Get the inverse, like grep -v [default: %default]") p.set_outfile() p.set_stripnames() ...
def some(args)
%prog some bedfile idsfile > newbedfile Retrieve a subset of bed features given a list of ids.
3.149628
2.844021
1.107456
from jcvi.formats.sizes import Sizes p = OptionParser(uniq.__doc__) p.add_option("--sizes", help="Use sequence length as score") p.add_option("--mode", default="span", choices=("span", "score"), help="Pile mode") opts, args = p.parse_args(args) if len(args) != 1: ...
def uniq(args)
%prog uniq bedfile Remove overlapping features with higher scores.
2.401915
2.296301
1.045993
from jcvi.formats.sizes import Sizes p = OptionParser(bins.__doc__) p.add_option("--binsize", default=100000, type="int", help="Size of the bins [default: %default]") p.add_option("--subtract", help="Subtract bases from window [default: %default]") p.add_optio...
def bins(args)
%prog bins bedfile fastafile Bin bed lengths into each consecutive window. Use --subtract to remove bases from window, e.g. --subtract gaps.bed ignores the gap sequences.
2.824761
2.729122
1.035044
from jcvi.utils.grouper import Grouper p = OptionParser(pile.__doc__) p.add_option("--minOverlap", default=0, type="int", help="Minimum overlap required [default: %default]") opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) abedfile...
def pile(args)
%prog pile abedfile bbedfile > piles Call intersectBed on two bedfiles.
3.235194
2.702508
1.197108
p = OptionParser(index.__doc__) p.add_option("--fasta", help="Generate bedgraph and index") p.add_option("--query", help="Chromosome location") p.set_outfile() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) bedfile, = args fastafile = opts...
def index(args)
%prog index bedfile Compress and index bedfile using `tabix`. Use --fasta to give a FASTA file so that a bedgraph file can be generated and indexed.
2.81429
2.476275
1.136502
from jcvi.formats.sizes import Sizes p = OptionParser(evaluate.__doc__) p.add_option("--query", help="Chromosome location [default: %default]") opts, args = p.parse_args(args) if len(args) != 3: sys.exit(not p.print_help()) prediction, reality, fastafile = args ...
def evaluate(args)
%prog evaluate prediction.bed reality.bed fastafile Make a truth table like: True False --- Reality True TP FP False FN TN |----Prediction Sn = TP / (all true in reality) = TP / (TP + FN) Sp = TP / (all true in prediction) = TP / (TP + FP) Ac = (TP + TN) / (...
3.223388
2.965093
1.087112
p = OptionParser(refine.__doc__) opts, args = p.parse_args(args) if len(args) != 3: sys.exit(not p.print_help()) abedfile, bbedfile, refinedbed = args fw = open(refinedbed, "w") intersected = refined = 0 for a, b in intersectBed_wao(abedfile, bbedfile): if b is None: ...
def refine(args)
%prog refine bedfile1 bedfile2 refinedbed Refine bed file using a second bed file. The final bed is keeping all the intervals in bedfile1, but refined by bedfile2 whenever they have intersection.
2.950983
2.606014
1.132374
from jcvi.utils.iter import pairwise p = OptionParser(distance.__doc__) p.add_option("--distmode", default="ss", choices=("ss", "ee"), help="Distance mode between paired reads. ss is outer distance, " \ "ee is inner distance [default: %default]") opts, args = p.parse_a...
def distance(args)
%prog distance bedfile Calculate distance between bed features. The output file is a list of distances, which can be used to plot histogram, etc.
3.555462
3.377935
1.052555
import random from jcvi.assembly.coverage import Coverage p = OptionParser(sample.__doc__) p.add_option("--raindrop", default=0, type="int", help="Raindrop selection, ignores all other options") p.add_option("--max", default=10, type="int", help="Max depth all...
def sample(args)
%prog sample bedfile sizesfile Sample bed file and remove high-coverage regions. When option --targetsize is used, this program uses a differnent mode. It first calculates the current total bases from all ranges and then compare to targetsize, if more, then sample down as close to targetsize as possib...
3.02211
2.778305
1.087753
from jcvi.assembly.coverage import bed_to_bedpe p = OptionParser(bedpe.__doc__) p.add_option("--span", default=False, action="store_true", help="Write span bed file [default: %default]") p.add_option("--strand", default=False, action="store_true", help="Write the stran...
def bedpe(args)
%prog bedpe bedfile Convert to bedpe format. Use --span to write another bed file that contain the span of the read pairs.
2.859687
2.712323
1.054331
p = OptionParser(sizes.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) bedfile, = args assert op.exists(bedfile) sizesfile = bedfile.rsplit(".", 1)[0] + ".sizes" fw = must_open(sizesfile, "w", checkexists=True, skipcheck=True) if ...
def sizes(args)
%prog sizes bedfile Infer the sizes for each seqid. Useful before dot plots.
3.725223
3.52458
1.056927
peak0 = [d for d in dists if d < cutoff] peak1 = [d for d in dists if d >= cutoff] c0, c1 = len(peak0), len(peak1) logging.debug("Component counts: {0} {1}".format(c0, c1)) if c0 == 0 or c1 == 0 or float(c1) / len(dists) < alpha: logging.debug("Single peak identified ({0} / {1} < {2})"....
def analyze_dists(dists, cutoff=1000, alpha=.1)
The dists can show bimodal distribution if they come from a mate-pair library. Assume bimodal distribution and then separate the two peaks. Based on the percentage in each peak, we can decide if it is indeed one peak or two peaks, and report the median respectively.
2.954425
2.87615
1.027215
p = OptionParser(pairs.__doc__) p.set_pairs() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) bedfile, = args basename = bedfile.split(".")[0] insertsfile = ".".join((basename, "inserts")) bedfile = sort([bedfile, "--accn"]) fp = open(...
def pairs(args)
See __doc__ for OptionParser.set_pairs().
5.519956
5.423583
1.017769
p = OptionParser(summary.__doc__) p.add_option("--sizes", default=False, action="store_true", help="Write .sizes file") p.add_option("--all", default=False, action="store_true", help="Write summary stats per seqid") opts, args = p.parse_args(args) if len(args)...
def summary(args)
%prog summary bedfile Sum the total lengths of the intervals.
3.114776
3.019944
1.031402
p = OptionParser(sort.__doc__) p.add_option("-i", "--inplace", dest="inplace", default=False, action="store_true", help="Sort bed file in place [default: %default]") p.add_option("-u", dest="unique", default=False, action="store_true", help="Uniqify the b...
def sort(args)
%prog sort bedfile Sort bed file to have ascending order of seqid, then start. It uses the `sort` command.
2.44911
2.378841
1.029539
p = OptionParser(mates.__doc__) p.add_option("--lib", default=False, action="store_true", help="Output library information along with pairs [default: %default]") p.add_option("--nointra", default=False, action="store_true", help="Remove mates that are intra-scaffold [default: %d...
def mates(args)
%prog mates bedfile Generate the mates file by inferring from the names.
3.55952
3.46606
1.026964
from numpy import array, argsort p = OptionParser(flanking.__doc__) p.add_option("--chrom", default=None, type="string", help="chrom name of the position in query. Make sure it matches bedfile.") p.add_option("--coord", default=None, type="int", help="coordinate of the posi...
def flanking(args)
%prog flanking bedfile [options] Get up to n features (upstream or downstream or both) flanking a given position.
2.603364
2.452642
1.061453
args = [getattr(self, attr) for attr in BlastLine.__slots__[:12]] args[0:2] = [self.subject, self.query] args[6:10] = [self.sstart, self.sstop, self.qstart, self.qstop] if self.orientation == '-': args[8], args[9] = args[9], args[8] b = "\t".join(str(x) for x...
def swapped(self)
Swap query and subject.
3.775545
3.602351
1.048078
p = OptionParser(gff.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) gbkfile, = args MultiGenBank(gbkfile)
def gff(args)
%prog gff seq.gbk Convert Genbank file to GFF and FASTA file. The Genbank file can contain multiple records.
3.414932
2.796341
1.221214
p = OptionParser(tofasta.__doc__) p.add_option("--prefix", default="gbfasta", help="prefix of output files [default: %default]") filenames, accessions, idfile, opts, args = preparegb(p, args) prefix = opts.prefix GenBank(filenames=filenames, accessions=accessions, idfile=idfile).\ ...
def tofasta(args)
%prog tofasta [--options] Read GenBank file, or retrieve from web. Output fasta file with one record per file or all records in one file
5.806116
5.725057
1.014159
p = OptionParser(getgenes.__doc__) p.add_option("--prefix", default="gbout", help="prefix of output files [default: %default]") p.add_option("--nopep", default=False, action="store_true", help="Only get cds and bed, no pep [default: %default]") filenames, accessions, idfile,...
def getgenes(args)
%prog getgenes [--options] Read GenBank file, or retrieve from web. Output bed, cds files, and pep file (can turn off with --nopep). Either --gb_dir or --id/--simple should be provided.
4.657657
3.813332
1.221414
prot_id = None for ftype in quals_ftypes: for i, quals in enumerate(locus[locus_tag][ftype]): for elem in quals: elem_id = elem[0] if len(locus[locus_tag]["protein_id"]) > 0 and ftype in ("mRNA", "CDS"): elem_id = locus[locus_tag]["pro...
def print_locus_quals(locus_tag, locus, quals_ftypes)
Given a locus_tag and dict of feaures, print out 3-column output: locus_tag, qualifier, value Replace locus_tag with protein_id if processing an "mRNA" or "CDS"
3.418918
3.396039
1.006737
p = OptionParser(getquals.__doc__) p.add_option("--types", default="gene,mRNA,CDS", type="str", dest="quals_ftypes", help="Feature types from which to extract qualifiers") p.add_option("--ignore", default="locus_tag,product,codon_start,translation", type=...
def getquals(args)
%prog getquals [--options] gbkfile > qualsfile Read GenBank file and extract all qualifiers per feature type into a tab-delimited file
2.145037
2.013005
1.06559
"Advance the iterator n-steps ahead. If n is none, consume entirely." # Use functions that consume iterators at C speed. if n is None: # feed the entire iterator into a zero-length deque collections.deque(iterator, maxlen=0) else: # advance to the empty slice starting at position...
def consume(iterator, n)
Advance the iterator n-steps ahead. If n is none, consume entirely.
2.41933
2.447042
0.988675
"Random selection from itertools.combinations(iterable, r)" pool = tuple(iterable) n = len(pool) indices = sorted(random.sample(xrange(n), r)) return tuple(pool[i] for i in indices)
def random_combination(iterable, r)
Random selection from itertools.combinations(iterable, r)
2.506187
2.126661
1.178461
"Random selection from itertools.combinations_with_replacement(iterable, r)" pool = tuple(iterable) n = len(pool) indices = sorted(random.randrange(n) for i in xrange(r)) return tuple(pool[i] for i in indices)
def random_combination_with_replacement(iterable, r)
Random selection from itertools.combinations_with_replacement(iterable, r)
2.613867
2.168791
1.205219
for value in islice(t.__copy__(), i, None): return value raise IndexError(i)
def tee_lookahead(t, i)
Inspect the i-th upcomping value from a tee object while leaving the tee object at its current position. Raise an IndexError if the underlying iterator doesn't have enough values.
10.473719
10.694083
0.979394
# Doesn't seem to run into any number-of-args limits. for group in (list(g) for g in zip_longest(*[iter(iterable)] * n, fillvalue=_marker)): if group[-1] is _marker: # If this is the last group, shuck off the padding: del group[...
def chunked(iterable, n)
Break an iterable into lists of a given length:: >>> list(chunked([1, 2, 3, 4, 5, 6, 7], 3)) [[1, 2, 3], [4, 5, 6], [7]] If the length of ``iterable`` is not evenly divisible by ``n``, the last returned list will be shorter. This is useful for splitting up a computation on a large number ...
8.139925
8.954328
0.909049
if not hasattr(self, '_peek'): try: self._peek = next(self._it) except StopIteration: if default is _marker: raise return default return self._peek
def peek(self, default=_marker)
Return the item that will be next returned from ``next()``. Return ``default`` if there are no items left. If ``default`` is not provided, raise ``StopIteration``.
2.686407
2.565084
1.047298
p = OptionParser(uniq.__doc__) p.set_outfile() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) fastqfile, = args fw = must_open(opts.outfile, "w") nduplicates = nreads = 0 seen = set() for rec in iter_fastq(fastqfile): nreads += ...
def uniq(args)
%prog uniq fastqfile Retain only first instance of duplicate reads. Duplicate is defined as having the same read name.
2.768735
2.581782
1.072412
p = OptionParser(suffix.__doc__) p.set_outfile() opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) fastqfile, sf = args fw = must_open(opts.outfile, "w") nreads = nselected = 0 for rec in iter_fastq(fastqfile): nreads += 1 if r...
def suffix(args)
%prog suffix fastqfile CAG Filter reads based on suffix.
3.042276
2.784178
1.092702
p = OptionParser(readlen.__doc__) p.set_firstN() p.add_option("--silent", default=False, action="store_true", help="Do not print read length stats") p.add_option("--nocheck", default=False, action="store_true", help="Do not check file type suffix") opts, args =...
def readlen(args)
%prog readlen fastqfile Calculate read length, will only try the first N reads. Output min, max, and avg for each file.
2.790467
2.795806
0.99809
p = OptionParser(fasta.__doc__) p.add_option("--seqtk", default=False, action="store_true", help="Use seqtk to convert") p.set_outdir() p.set_outfile(outfile=None) opts, args = p.parse_args(args) if len(args) < 1: sys.exit(not p.print_help()) fastqfiles = args...
def fasta(args)
%prog fasta fastqfiles Convert fastq to fasta and qual file.
3.187926
3.007523
1.059984
from jcvi.apps.base import need_update p = OptionParser(first.__doc__) p.set_outfile() opts, args = p.parse_args(args) if len(args) < 2: sys.exit(not p.print_help()) N = int(args[0]) nlines = N * 4 fastqfiles = args[1:] fastqfile = fastqfiles[0] outfile = opts.out...
def first(args)
%prog first N fastqfile(s) Get first N reads from file.
2.45853
2.19349
1.12083
p = OptionParser(filter.__doc__) p.add_option("-q", dest="qv", default=20, type="int", help="Minimum quality score to keep [default: %default]") p.add_option("-p", dest="pct", default=95, type="int", help="Minimum percent of bases that have [-q] quality "\ ...
def filter(args)
%prog filter paired.fastq Filter to get high qv reads. Use interleaved format (one file) or paired format (two files) to filter on paired reads.
3.204611
2.892759
1.107804
p = OptionParser(shuffle.__doc__) p.set_tag() opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) p1, p2 = args pairsfastq = pairspf((p1, p2)) + ".fastq" tag = opts.tag p1fp = must_open(p1) p2fp = must_open(p2) pairsfw = must_open(pairs...
def shuffle(args)
%prog shuffle p1.fastq p2.fastq Shuffle pairs into interleaved format.
3.358299
3.120088
1.076348
from jcvi.apps.grid import Jobs p = OptionParser(split.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) pairsfastq, = args gz = pairsfastq.endswith(".gz") pf = pairsfastq.replace(".gz", "").rsplit(".", 1)[0] p1 = pf + ".1.fastq" ...
def split(args)
%prog split pairs.fastq Split shuffled pairs into `.1.fastq` and `.2.fastq`, using `sed`. Can work on gzipped file. <http://seqanswers.com/forums/showthread.php?t=13776>
2.749703
2.598952
1.058004
p = OptionParser(guessoffset.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) fastqfile, = args ai = iter_fastq(fastqfile) rec = next(ai) offset = 64 while rec: quality = rec.quality lowcounts = len([x for x in qualit...
def guessoffset(args)
%prog guessoffset fastqfile Guess the quality offset of the fastqfile, whether 33 or 64. See encoding schemes: <http://en.wikipedia.org/wiki/FASTQ_format> SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS............................... ..........................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX...
2.699579
2.708517
0.9967
p = OptionParser(format.__doc__) p.add_option("--convert", default=None, choices=[">=1.8", "<1.8", "sra"], help="Convert fastq header to a different format" + " [default: %default]") p.set_tag(specify_tag=True) opts, args = p.parse_args(args) if len(args) != 1:...
def format(args)
%prog format fastqfile Format FASTQ file. Currently provides option to convert FASTQ header from one dialect to another.
3.851692
3.443885
1.118415
p = OptionParser(some.__doc__) opts, args = p.parse_args(args) if len(args) not in (2, 3): sys.exit(not p.print_help()) idsfile, afastq, = args[:2] bfastq = args[2] if len(args) == 3 else None ids = DictFile(idsfile, valuepos=None) ai = iter_fastq(open(afastq)) arec = ne...
def some(args)
%prog some idsfile afastq [bfastq] Select a subset of the reads with ids present in the idsfile. `bfastq` is optional (only if reads are paired)
2.972727
2.294189
1.295763
p = OptionParser(trim.__doc__) p.add_option("-f", dest="first", default=0, type="int", help="First base to keep. Default is 1.") p.add_option("-l", dest="last", default=0, type="int", help="Last base to keep. Default is entire read.") opts, args = p.parse_args(args) if ...
def trim(args)
%prog trim fastqfile Wraps `fastx_trimmer` to trim from begin or end of reads.
2.552694
2.433039
1.049179
p = OptionParser(catread.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) r1, r2 = args p1fp, p2fp = FastqPairedIterator(r1, r2) outfile = pairspf((r1, r2)) + ".cat.fastq" fw = must_open(outfile, "w") while True: a = list(isl...
def catread(args)
%prog catread fastqfile1 fastqfile2 Concatenate paired end reads into one. Useful for example to do single-end mapping and perform filtering on the whole read pair level.
3.339979
3.095534
1.078967
p = OptionParser(splitread.__doc__) p.add_option("-n", dest="n", default=76, type="int", help="Split at N-th base position [default: %default]") p.add_option("--rc", default=False, action="store_true", help="Reverse complement second read [default: %default]") opts, args = p...
def splitread(args)
%prog splitread fastqfile Split fastqfile into two read fastqfiles, cut in the middle.
2.612853
2.489864
1.049396
p = OptionParser(size.__doc__) opts, args = p.parse_args(args) if len(args) < 1: sys.exit(not p.print_help()) total_size = total_numrecords = 0 for f in args: cur_size = cur_numrecords = 0 for rec in iter_fastq(f): if not rec: break ...
def size(args)
%prog size fastqfile Find the total base pairs in a list of fastq files
2.33525
2.27957
1.024426
p = OptionParser(convert.__doc__) p.set_phred() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) infastq, = args phred = opts.phred or str(guessoffset([infastq])) ophred = {"64": "33", "33": "64"}[phred] gz = infastq.endswith(".gz") outf...
def convert(args)
%prog convert in.fastq illumina fastq quality encoding uses offset 64, and sanger uses 33. This script creates a new file with the correct encoding. Output gzipped file if input is also gzipped.
3.172027
2.9161
1.087763
from jcvi.utils.iter import pairwise p = OptionParser(pairinplace.__doc__) p.set_rclip() p.set_tag() p.add_option("--base", help="Base name for the output files [default: %default]") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()...
def pairinplace(args)
%prog pairinplace bulk.fastq Pair up the records in bulk.fastq by comparing the names for adjancent records. If they match, print to bulk.pairs.fastq, else print to bulk.frags.fastq.
3.316688
3.05005
1.087421
p = OptionParser(fromsra.__doc__) p.add_option("--paired", default=False, action="store_true", help="Specify if library layout is paired-end " + \ "[default: %default]") p.add_option("--compress", default=None, choices=["gzip", "bzip2"], help="Compress output fa...
def fromsra(args)
%prog fromsra srafile Convert sra file to fastq using the sratoolkit `fastq-dump`
2.626724
2.474169
1.061659
p = OptionParser(blast.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) btabfile, = args btab = Btab(btabfile) for b in btab: print(b.blastline)
def blast(args)
%prog blast btabfile Convert to BLAST -m8 format.
2.74627
2.381157
1.153334
from jcvi.formats.blast import BlastLine p = OptionParser(bed.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) btabfile, = args btab = Btab(btabfile) for b in btab: Bline = BlastLine(b.blastline) print(Bline.bedline)
def bed(args)
%prog bed btabfile Convert btab to bed format.
2.904101
2.555094
1.136592
from jcvi.utils.range import range_minmax from jcvi.formats.gff import valid_gff_parent_child, valid_gff_type p = OptionParser(gff.__doc__) p.add_option("--source", default=None, help="Specify GFF source." + " By default, it picks algorithm used to generate btab file." + ...
def gff(args)
%prog gff btabfile Convert btab file generated by AAT to gff3 format.
3.337012
3.149939
1.059389
for taxid in list_of_taxids: handle = Entrez.efetch(db='Taxonomy', id=taxid, retmode="xml") records = Entrez.read(handle) yield records[0]["ScientificName"]
def batch_taxonomy(list_of_taxids)
Convert list of taxids to Latin names
2.409266
2.227921
1.081397
for name in list_of_names: handle = Entrez.esearch(db='Taxonomy', term=name, retmode="xml") records = Entrez.read(handle) yield records["IdList"][0]
def batch_taxids(list_of_names)
Opposite of batch_taxonomy(): Convert list of Latin names to taxids
2.629781
2.346381
1.120782
for term in list_of_terms: logging.debug("Search term %s" % term) success = False ids = None if not term: continue while not success: try: search_handle = Entrez.esearch(db=db, retmax=retmax, term=term) rec = Ent...
def batch_entrez(list_of_terms, db="nuccore", retmax=1, rettype="fasta", batchsize=1, email=myEmail)
Retrieve multiple rather than a single record
2.501748
2.5652
0.975265
p = OptionParser(ensembl.__doc__) p.add_option("--version", default="75", help="Ensembl version [default: %default]") opts, args = p.parse_args(args) version = opts.version url = "ftp://ftp.ensembl.org/pub/release-{0}/".format(version) fasta_url = url + "fasta/" valid...
def ensembl(args)
%prog ensembl species Retrieve genomes and annotations from ensembl FTP. Available species listed below. Use comma to give a list of species to download. For example: $ %prog ensembl danio_rerio,gasterosteus_aculeatus
3.119105
3.220025
0.968659
from jcvi.apps.biomart import GlobusXMLParser p = OptionParser(phytozome10.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) species, = args fp = open("get-directory.html") g = GlobusXMLParser(fp) g.parse_folder()
def phytozome10(args)
%prog phytozome species Retrieve genomes and annotations from phytozome using Globus API. Available species listed below. Use comma to give a list of species to download. For example: $ %prog phytozome Athaliana,Vvinifera,Osativa,Sbicolor,Slycopersicum
4.564952
4.236294
1.077581
from jcvi.formats.gff import bed as gff_bed from jcvi.formats.fasta import format as fasta_format p = OptionParser(phytozome.__doc__) p.add_option("--version", default="9.0", help="Phytozome version [default: %default]") p.add_option("--assembly", default=False, action="store_...
def phytozome(args)
%prog phytozome species Retrieve genomes and annotations from phytozome FTP. Available species listed below. Use comma to give a list of species to download. For example: $ %prog phytozome Athaliana,Vvinifera,Osativa,Sbicolor,Slycopersicum
4.914038
4.789932
1.02591
f = list(SeqIO.parse(fastafile, "fasta")) if len(f) > 1: logging.debug("{0} records found in {1}, using the first one". format(len(f), fastafile)) return f[0]
def get_first_rec(fastafile)
Returns the first record in the fastafile
2.999074
2.957284
1.014131
p = OptionParser(bisect.__doc__) p.set_email() opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) acc, fastafile = args arec = get_first_rec(fastafile) valid = None for i in range(1, 100): term = "%s.%d" % (acc, i) try: ...
def bisect(args)
%prog bisect acc accession.fasta determine the version of the accession by querying entrez, based on a fasta file. This proceeds by a sequential search from xxxx.1 to the latest record.
5.015296
4.372916
1.1469
p = OptionParser(sra.__doc__) p.add_option("--nogzip", dest="nogzip", default=False, action="store_true", help="Do not gzip the FASTQ generated by fastq-dump") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) term, = ar...
def sra(args)
%prog sra [term|term.ids] Given an SRA run ID, fetch the corresponding .sra file from the sra-instant FTP. The term can also be a file containing list of SRR ids, one per line. Once downloaded, the SRA file is processed through `fastq-dump` to produce FASTQ formatted sequence files, which are gzipped ...
3.293507
3.023265
1.089387
for i in dir(item): try: member = str(getattr(item, i)) if maxchar and len(member) > maxchar: member = member[:maxchar] + "..." except: member = "[ERROR]" print("{}: {}".format(i, member), file=sys.stderr)
def inspect(item, maxchar=80)
Inspect the attributes of an item.
2.64877
2.671629
0.991444
import time def timed(*args, **kw): ts = time.time() result = func(*args, **kw) te = time.time() msg = "{0}{1} {2:.2f}s".format(func.__name__, args, te - ts) logging.debug(msg) return result return timed
def timeit(func)
<http://www.zopyx.com/blog/a-python-decorator-for-measuring-the-execution-time-of-methods>
2.245885
2.038965
1.101483
from jcvi.apps.base import need_update, listify infile = "infile" outfile = "outfile" def wrapper(*args, **kwargs): assert outfile in kwargs, \ "You need to specify `outfile=` on function call" if infile in kwargs: infilename = listify(kwargs[infile]) ...
def depends(func)
Decorator to perform check on infile and outfile. When infile is not present, issue warning, and when outfile is present, skip function calls.
3.349925
3.198536
1.047331
for index in reversed(xrange(len(sequence))): yield index, sequence[index]
def enumerate_reversed(sequence)
Perform reverse enumeration, returning an iterator with decrementing index/position values Source: http://stackoverflow.com/questions/529424/traverse-a-list-in-reverse-order-in-python
2.867743
3.735332
0.767735
_a, _b = a, b pct = "{0:.{1}f}%".format(a * 100. / b, precision) a, b = thousands(a), thousands(b) if mode == 0: return "{0} of {1} ({2})".format(a, b, pct) elif mode == 1: return "{0} ({1})".format(a, pct) elif mode == 2: return _a * 100. / _b return pct
def percentage(a, b, precision=1, mode=0)
>>> percentage(100, 200) '100 of 200 (50.0%)'
2.448844
2.282147
1.073044
import locale try: locale.setlocale(locale.LC_ALL, "en_US.utf8") except Exception: locale.setlocale(locale.LC_ALL, "en_US.UTF-8") finally: s = '%d' % x groups = [] while s and s[-1].isdigit(): groups.append(s[-3:]) s = s[:-3] r...
def thousands(x)
>>> thousands(12345) '12,345'
2.312011
2.288479
1.010283
'''Convert a file size to human-readable form. Keyword arguments: size -- file size in bytes a_kilobyte_is_1024_bytes -- if True (default), use multiples of 1024 if False, use multiples of 1000 Returns: string Credit: <http://diveintopython3.org/your-first-pytho...
def human_size(size, a_kilobyte_is_1024_bytes=False, precision=1, target=None)
Convert a file size to human-readable form. Keyword arguments: size -- file size in bytes a_kilobyte_is_1024_bytes -- if True (default), use multiples of 1024 if False, use multiples of 1000 Returns: string Credit: <http://diveintopython3.org/your-first-python-progr...
2.560473
1.535997
1.666977
slen = str(bp) tlen = slen[0:2] if len(slen) > 1 else slen[0] precision = len(slen) - 2 # how many zeros we need to pad? bp_len_scaled = int(tlen) # scale bp_len to range (0, 100) tick_diffs = [(x, abs(bp_len_scaled / x - optimal)) for x in [1, 2, 5, 10]] best_stride, best_tick_diff = min...
def autoscale(bp, optimal=6)
>>> autoscale(150000000) 20000000 >>> autoscale(97352632) 10000000
4.397855
4.55964
0.964518