code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
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 = o...
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, marke...
3.496681
3.184669
1.097973
p = OptionParser(gc3.__doc__) p.add_option("--plot", default=False, action="store_true", help="Also plot the GC3 histogram [default: %default]") p.set_outfile() opts, args = p.parse_args(args) outfile = opts.outfile plot = opts.plot if not 1 < len(args) < 4: ...
def gc3(args)
%prog gc3 ksfile cdsfile [cdsfile2] -o newksfile Filter the Ks results to remove high GC3 genes. High GC3 genes are problematic in Ks calculation - see Tang et al. 2010 PNAS. Specifically, the two calculation methods produce drastically different results for these pairs. Therefore we advise to remoeve ...
3.200287
2.896285
1.104963
agenome = op.basename(abed.filename).split(".")[0] bgenome = op.basename(bbed.filename).split(".")[0] aorder = abed.order border = bbed.order pairsfile = "{0}.{1}.pairs".format(agenome, bgenome) fw = open(pairsfile, "w") is_self = abed.filename == bbed.filename npairs = 0 for g...
def extract_pairs(abed, bbed, groups)
Called by fromgroups(), extract pairs specific to a pair of species.
3.224095
3.154078
1.022199
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()....
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.
2.570176
2.504405
1.026262
from jcvi.formats.fasta import Fasta p = OptionParser(prepare.__doc__) p.set_outfile() opts, args = p.parse_args(args) outfile = opts.outfile if len(args) == 2: pairsfile, cdsfile = args pepfile = None elif len(args) == 3: pairsfile, cdsfile, pepfile = args ...
def prepare(args)
%prog prepare pairsfile cdsfile [pepfile] -o paired.cds.fasta Pick sequences from cdsfile to form pairs, ready to be calculated. The pairsfile can be generated from formats.blast.cscore(). The first two columns contain the pair.
2.372474
2.190009
1.083317
from jcvi.formats.fasta import translate p = OptionParser(calc.__doc__) p.add_option("--longest", action="store_true", help="Get longest ORF, only works if no pep file, "\ "e.g. ESTs [default: %default]") p.add_option("--msa", default="clustalw", choices=("cl...
def calc(args)
%prog calc [prot.fasta] cds.fasta > out.ks Protein file is optional. If only one file is given, it is assumed to be CDS sequences with correct frame (frame 0). Results will be written to stdout. Both protein file and nucleotide file are assumed to be Fasta format, with adjacent records as the pairs to ...
3.051007
2.903537
1.05079
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\nwei...
def find_synonymous(input_file, work_dir)
Run yn00 to find the synonymous subsitution rate for the alignment.
3.955684
3.681017
1.074617
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() ...
def run_mrtrans(align_fasta, recs, work_dir, outfmt="paml")
Align nucleotide sequences with mrtrans and the protein alignment.
3.005509
2.97525
1.01017
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="PRO...
def clustal_align_protein(recs, work_dir, outfmt="fasta")
Align given proteins with clustalw. recs are iterable of Biopython SeqIO objects
3.278415
3.288432
0.996954
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) s...
def muscle_align_protein(recs, work_dir, outfmt="fasta", inputorder=True)
Align given proteins with muscle. recs are iterable of Biopython SeqIO objects
3.183319
3.283579
0.969466
sh("cp {0} {0}.old".format(alnfile), log=False) maxi = 30 if trunc_name else 1000 aa = AlignIO.read(alnfile, "clustal") alignment = dict((a.id[:maxi], a) for a in aa) if trunc_name and len(alignment) < len(aa): raise ValueError\ ("ERROR: The first 30 chars of your seq names...
def muscle_inputorder(inputfastafile, alnfile, trunc_name=True)
Fix for muscle -stable option according to here: http://drive5.com/muscle/stable.html
3.647979
3.746166
0.97379
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()...
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.
2.709919
2.573107
1.05317
from jcvi.apps.base import popen probs, mus, sigmas = [], [], [] fw = must_open("tmp", "w") log_data = [log(x) for x in data if x > .05] data = "\n".join(["%.4f" % x for x in log_data]).replace("inf\n", "") fw.write(data) fw.close() cmd = "gmm-bic {0} {1} {2}".format(components, l...
def get_mixture(data, components)
probs = [.476, .509] mus = [.69069, -.15038] variances = [.468982e-1, .959052e-1]
3.271788
3.239517
1.009962
''' %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 = Op...
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
3.796185
3.03931
1.249028
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] == "#": pr...
def passthrough(args)
%prog passthrough chrY.vcf chrY.new.vcf Pass through Y and MT vcf.
2.850423
2.547111
1.119081
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...
def validate(args)
%prog validate imputed.vcf withheld.vcf Validate imputation against withheld variants.
3.010177
2.656217
1.133257
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 = MakeManage...
def minimac(args)
%prog batchminimac input.txt Use MINIMAC3 to impute vcf on all chromosomes.
2.48657
2.460213
1.010713
pf = vcffile.rsplit(".", 1)[0] ranges = [(1, 2699519), (2699520, 154931043), (154931044, 155270560)] tags = ["PAR1", "NONPAR", "PAR2"] Xvcf = [] phasedfiles = [] for tag, (start, end) in zip(tags, ranges): recodefile = pf + "_{0}.recode.vcf".format(tag) cmd = "vcftools --vcf...
def minimac_X(mm, chr, vcffile, opts)
See details here: http://genome.sph.umich.edu/wiki/Minimac3_Cookbook_:_Chromosome_X_Imputation
3.46866
3.427944
1.011878
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" ...
def beagle(args)
%prog beagle input.vcf 1 Use BEAGLE4.1 to impute vcf on chromosome 1.
4.745138
4.313373
1.100099
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 ...
def impute(args)
%prog impute input.vcf hs37d5.fa 1 Use IMPUTE2 to impute vcf on chromosome 1.
3.390382
3.265167
1.038349
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"): ...
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
3.071739
2.65697
1.156106
p = OptionParser(statstable.__doc__) opts, args = p.parse_args(args) if len(args) < 1: sys.exit(not p.print_help()) gff_files = args for metric in metrics: logging.debug("Parsing files in `{0}`..".format(metric)) table = {} for x in gff_files: pf =...
def statstable(args)
%prog statstable *.gff Print gene statistics table.
4.154409
3.874067
1.072364
from jcvi.graphics.histogram import histogram_multiple p = OptionParser(histogram.__doc__) p.add_option("--bins", dest="bins", default=40, type="int", help="number of bins to plot in the histogram [default: %default]") opts, args = p.parse_args(args) if len(args) < 1: sys....
def histogram(args)
%prog histogram *.gff Plot gene statistics based on output of stats. For each gff file, look to see if the metrics folder (i.e. Exon_Length) contains the data and plot them.
3.507729
3.259982
1.075997
p = OptionParser(stats.__doc__) p.add_option("--gene", default="mRNA", help="The gene type [default: %default]") p.add_option("--exon", default="CDS", help="The exon type [default: %default]") opts, args = p.parse_args(args) if len(args) != 1: sys.exit...
def stats(args)
%prog stats infile.gff Collect gene statistics based on gff file. There are some terminology issues here and so normally we call "gene" are actually mRNA, and sometimes "exon" are actually CDS, but they are configurable. Thee numbers are written to text file in four separate folders, corresponding...
2.200162
2.096383
1.049504
p = OptionParser(rdotplot.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) dotplot_template = rdotplotfile, = args assert rdotplotfile.endswith(".rdotplot") pngfile = rdotplotfile.replace(".rdotplot", ".png") rtemplate = RTemplate...
def rdotplot(args)
%prog rdotplotfile Dot plot to visualize relationship between two sequences, by plotting .rdotplot file (often generated by LASTZ)
3.27188
3.205228
1.020795
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....
def run(self, clean=True)
Create a temporary file and run it
8.266833
8.018145
1.031016
spurs = [] path_nodes = [] for k, d in G.degree().iteritems(): if d == 1: spurs.append(k) elif d == 2: path_nodes.append(k) logging.debug("Remove {0} spurs.".format(len(spurs))) G.remove_nodes_from(spurs) SG = G.subgraph(path_nodes) cc = nx.conn...
def graph_simplify(G)
Simplify big graphs: remove spurs and contract unique paths.
2.956044
2.657378
1.112391
npaths = len(paths) weights = weights or [1] * npaths assert len(paths) == len(weights) G = nx.DiGraph() for path, w in zip(paths, weights): for a, b in pairwise(path): update_weight(G, a, b, w) return G
def make_paths(paths, weights=None)
Zip together paths. Called by merge_paths().
2.579926
2.601195
0.991823
from jcvi.algorithms.lpsolve import min_feedback_arc_set while not nx.is_directed_acyclic_graph(G): edges = [] for a, b, w in G.edges_iter(data=True): w = w['weight'] edges.append((a, b, w)) mf, mf_score = min_feedback_arc_set(edges) for a, b, w in m...
def reduce_paths(G)
Make graph into a directed acyclic graph (DAG).
3.779235
3.674768
1.028428
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)
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 redu...
3.907531
4.379351
0.892263
G = make_paths(paths, weights=weights) G = reduce_paths(G) return G
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]
6.195173
9.1671
0.675805
assert nx.is_directed_acyclic_graph(G) tree = nx.topological_sort(G) node_to_index = dict((t, i) for i, t in enumerate(tree)) nnodes = len(tree) weights = [weights.get(x, 1) for x in tree] if weights else [1] * nnodes score, fromc = weights[:], [-1] * nnodes si = node_to_index[source]...
def longest_path_weighted_nodes(G, source, target, weights=None)
The longest path problem is the problem of finding a simple path of maximum length in a given graph. While for general graph, this problem is NP-hard, but if G is a directed acyclic graph (DAG), longest paths in G can be found in linear time with dynamic programming. >>> G = nx.DiGraph([(1, 2), (1, 3),...
3.054782
3.264852
0.935657
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: ...
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 ...
4.698082
3.618507
1.298348
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}".f...
def dust2bed(args)
%prog dust2bed fastafile Use dustmasker to find low-complexity regions (LCRs) in the genome.
2.935234
2.700697
1.086843
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 ...
def fasta2bed(fastafile)
Alternative BED generation from FASTA file. Used for sanity check.
4.749977
4.767151
0.996397
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.pri...
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.
2.497519
2.33134
1.071281
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(fastafil...
def dust(args)
%prog dust assembly.fasta Remove low-complexity contigs within assembly.
2.919239
2.760217
1.057612
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 ...
def dedup(args)
%prog dedup assembly.assembly.blast assembly.fasta Remove duplicate contigs within assembly.
3.196972
3.007254
1.063087
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.p...
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 s...
4.593752
3.925843
1.170131
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(...
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.
3.610709
3.208077
1.125506
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) ...
def scaffold(args)
%prog scaffold ctgfasta agpfile Build scaffolds based on ordering in the AGP file.
3.560594
3.391075
1.04999
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.wri...
def overlapbatch(args)
%prog overlapbatch ctgfasta poolfasta Fish out the sequences in `poolfasta` that overlap with `ctgfasta`. Mix and combine using `minimus2`.
3.338158
2.875571
1.160868
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] ru...
def array(args)
%prog array commands.list Parallelize a set of commands on grid using array jobs.
4.796079
4.586178
1.045768
p = OptionParser(run.__doc__) p.set_grid_opts() p.set_params(prog="grid") opts, args = p.parse_args(args) if len(args) == 0: sys.exit(not p.print_help()) sep = ":::" if sep in args: sepidx = args.index(sep) filenames = args[sepidx + 1:] args = args[:sep...
def run(args)
%prog run command ::: file1 file2 Parallelize a set of commands on grid. The syntax is modeled after GNU parallel <http://www.gnu.org/s/parallel/man.html#options> {} - input line {.} - input line without extension {_} - input line first part {/} - basename of input line {/.} - basenam...
2.771632
2.602869
1.064837
import shlex from jcvi.apps.base import sh, getusername from subprocess import check_output, CalledProcessError import xml.etree.ElementTree as ET valid_methods = ("pattern", "jobid") p = OptionParser(kill.__doc__) p.add_option("--method", choices=valid_methods, help="...
def kill(args)
%prog kill [options] JOBNAMEPAT/JOBIDs Kill jobs based on JOBNAME pattern matching (case-sensitive) or list of JOBIDs (comma separated) Examples: %prog kill "pyth*" # Use regex %prog kill 160253,160245,160252 # Use list of job ids %prog kill all # Everyth...
3.210731
3.261052
0.984569
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") ...
def covlen(args)
%prog covlen covfile fastafile Plot coverage vs length. `covfile` is two-column listing contig id and depth of coverage.
2.355743
2.312276
1.018798
from jcvi.formats.bed import mates, bedpe p = OptionParser(coverage.__doc__) p.add_option("--ymax", default=None, type="int", help="Limit ymax [default: %default]") p.add_option("--spans", default=False, action="store_true", help="BED files already contain clone s...
def coverage(args)
%prog coverage fastafile ctg bedfile1 bedfile2 .. Plot coverage from a set of BED files that contain the read mappings. The paired read span will be converted to a new bedfile that contain the happy mates. ctg is the chr/scf/ctg that you want to plot the histogram on. If the bedfiles already contain t...
3.313109
3.080179
1.075622
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 [defa...
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...
3.584146
3.466348
1.033983
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]") ...
def A50(args)
%prog A50 contigs_A.fasta contigs_B.fasta ... Plots A50 graphics, see blog post (http://blog.malde.org/index.php/a50/)
3.059055
2.997527
1.020526
p = OptionParser(merge.__doc__) p.set_outfile(outfile="merged_results.delta") opts, args = p.parse_args(args) if len(args) < 3: sys.exit(not p.print_help()) ref, query = args[:2] deltafiles = args[2:] outfile = opts.outfile ref = get_abs_path(ref) query = get_abs_path...
def merge(args)
%prog merge ref.fasta query.fasta *.delta Merge delta files into a single delta.
3.522174
2.914587
1.208464
p = OptionParser(blast.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) deltafile, = args blastfile = deltafile.rsplit(".", 1)[0] + ".blast" if need_update(deltafile, blastfile): coords = Coords(deltafile) fw = open(blastfil...
def blast(args)
%prog blast <deltafile|coordsfile> Covert delta or coordsfile to BLAST tabular output.
2.898485
2.431979
1.191822
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 co...
def fromdelta(args)
%prog fromdelta deltafile Convert deltafile to coordsfile.
3.641561
2.929904
1.242894
import jcvi.formats.blast return jcvi.formats.blast.sort(args + ["--coords"])
def sort(args)
%prog sort coordsfile Sort coordsfile based on query or ref.
12.315608
12.723311
0.967956
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 ...
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
2.609952
2.490458
1.047981
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 [defaul...
def annotate(args)
%prog annotate coordsfile Annotate coordsfile to append an additional column, with the following overlaps: {0}.
3.934021
3.514314
1.119428
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()) coord...
def summary(args)
%prog summary coordsfile provide summary on id% and cov%, for both query and reference
4.253542
3.345288
1.271503
p = OptionParser(filter.__doc__) p.set_align(pctid=0, hitlen=0) p.add_option("--overlap", default=False, action="store_true", help="Print overlap status (e.g. terminal, contained)") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) pctid =...
def filter(args)
%prog filter <deltafile|coordsfile> Produce a new delta/coords file and filter based on id% or cov%. Use `delta-filter` for .delta file.
3.515422
3.235806
1.086413
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_op...
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
3.0318
2.886883
1.050198
aL, aR = 1, self.reflen bL, bR = 1, self.querylen aLhang, aRhang = self.start1 - aL, aR - self.end1 bLhang, bRhang = self.start2 - bL, bR - self.end2 if self.orientation == '-': bLhang, bRhang = bRhang, bLhang s1 = aLhang + bRhang s2 = aRhang...
def overlap(self, max_hang=100)
Determine the type of overlap given query, ref alignment coordinates Consider the following alignment between sequence a and b: aLhang \ / aRhang \------------/ /------------\ bLhang / \ bRhang Terminal overlap: a before b, b be...
2.721296
2.381608
1.14263
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)
returns a dict with query => blastline
10.198977
6.792256
1.501559
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)
returns a dict with query => best mapped position
9.35479
6.966965
1.342735
from jcvi.formats.fastq import guessoffset p = OptionParser(align.__doc__) p.set_firstN(firstN=0) p.add_option("--full", default=False, action="store_true", help="Enforce end-to-end alignment [default: local]") p.add_option("--reorder", default=False, action="store_true", ...
def align(args)
%prog align database.fasta read1.fq [read2.fq] Wrapper for `bowtie2` single-end or paired-end, depending on the number of args.
3.193035
3.127142
1.021071
cfg = {} options = Config.options(section) for option in options: try: cfg[option] = Config.get(section, option) if cfg[option] == -1: logging.debug("skip: {0}".format(option)) except: logging.debug("exception on {0}!".format(option)) ...
def ConfigSectionMap(Config, section)
Read a specific section from a ConfigParser() object and return a dict() of all key-value pairs in that section
1.536069
1.707262
0.899727
"Get module-level docstring of Python module at filepath, e.g. 'path/to/file.py'." co = compile(open(filepath).read(), filepath, 'exec') if co.co_consts and isinstance(co.co_consts[0], six.string_types): docstring = co.co_consts[0] else: docstring = None return docstring
def get_module_docstring(filepath)
Get module-level docstring of Python module at filepath, e.g. 'path/to/file.py'.
3.042277
2.017523
1.507926
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() ...
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
2.677198
2.694782
0.993475
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")
Capture the cmd stdout output to a file handle.
5.722585
5.654891
1.011971
import glob as gl if pattern: pathname = op.join(pathname, pattern) return natsorted(gl.glob(pathname))
def glob(pathname, pattern=None)
Wraps around glob.glob(), but return a sorted list.
4.802586
4.165473
1.152951
matches = [] patterns = patterns.split(",") if "," in patterns else listify(patterns) for root, dirnames, filenames in os.walk(pathname): matching = [] for pattern in patterns: matching.extend(fnmatch.filter(filenames, pattern)) for filename in matching: ...
def iglob(pathname, patterns)
Allow multiple file formats. This is also recursive. For example: >>> iglob("apps", "*.py,*.pyc")
2.712045
3.383454
0.801561
if op.isdir(dirname): if overwrite: shutil.rmtree(dirname) os.mkdir(dirname) logging.debug("Overwrite folder `{0}`.".format(dirname)) else: return False # Nothing is changed else: try: os.mkdir(dirname) except: ...
def mkdir(dirname, overwrite=False)
Wraps around os.mkdir(), but checks for existence first.
3.724886
3.794603
0.981627
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)
Check if the file a is newer than file b
2.260633
2.221741
1.017505
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)
Check if file a is newer than file b and decide whether or not to update file b. Can generalize to two lists.
4.051657
3.694931
1.096545
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)
Turn on the debugging
4.863702
5.177522
0.939388
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)
%prog mdownload links.txt Multiple download a list of files. Use formats.html.links() to extract the links file.
3.145377
2.924526
1.075517
p = OptionParser(expand.__doc__) p.add_option("--symlink", default=False, action="store_true", help="Create symbolic link [default: %default]") opts, args = p.parse_args(args) if len(args) < 1: sys.exit(not p.print_help()) seen = set() for a in args: oa = ...
def expand(args)
%prog expand */* Move files in subfolders into the current folder. Use --symlink to create a link instead.
3.044801
2.883607
1.0559
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) ...
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().
2.257618
2.085539
1.08251
from time import ctime p = OptionParser(touch.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) info, = args fp = open(info) for row in fp: path, atime, mtime = row.split() atime = float(atime) mtime = float(mtime...
def touch(args)
%prog touch timestamp.info Recover timestamps for files in the current folder. CAUTION: you must execute this in the same directory as timestamp().
2.779766
2.815634
0.987261
from jcvi.formats.base import must_open p = OptionParser(less.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) filename, pos = args fsize = getfilesize(filename) if pos == "all": pos = [x / 10. for x in range(0, 10)] else: ...
def less(args)
%prog less filename position | less Enhance the unix `less` command by seeking to a file location first. This is useful to browse big files. Position is relative 0.00 - 1.00, or bytenumber. $ %prog less myfile 0.1 # Go to 10% of the current file and streaming $ %prog less myfile 0.1,0.2 # Stream...
2.795768
2.521596
1.10873
assert -1 <= priority <= 2, \ "Priority should be an int() between -1 and 2" if timestamp == None: from time import time timestamp = int(time()) retry, expire = (300, 3600) if priority == 2 \ else (None, None) conn = HTTPSConnection("api.pushover.net:443")...
def pushover(message, token, user, title="JCVI: Job Monitor", \ priority=0, timestamp=None)
pushover.net python API <https://pushover.net/faq#library-python>
2.318748
2.374065
0.976699
assert -2 <= priority <= 2, \ "Priority should be an int() between -2 and 2" conn = HTTPSConnection("www.notifymyandroid.com") conn.request("POST", "/publicapi/notify", urlencode({ "apikey": apikey, "application": "python notify", "event": event,...
def nma(description, apikey, event="JCVI: Job Monitor", priority=0)
notifymyandroid.com API <http://www.notifymyandroid.com/api.jsp>
3.432786
3.46032
0.992043
import base64 headers = {} auth = base64.encodestring("{0}:".format(apikey)).strip() headers['Authorization'] = "Basic {0}".format(auth) headers['Content-type'] = "application/x-www-form-urlencoded" conn = HTTPSConnection("api.pushbullet.com".format(apikey)) conn.request("POST", "/api...
def pushbullet(body, apikey, device, title="JCVI: Job Monitor", type="note")
pushbullet.com API <https://www.pushbullet.com/api>
2.570354
2.570622
0.999896
import types assert type(priority) is int and -1 <= priority <= 2, \ "Priority should be and int() between -1 and 2" cfgfile = op.join(op.expanduser("~"), "pushnotify.ini") Config = ConfigParser() if op.exists(cfgfile): Config.read(cfgfile) else: sys.exit("Push ...
def pushnotify(subject, message, api="pushover", priority=0, timestamp=None)
Send push notifications using pre-existing APIs Requires a config `pushnotify.ini` file in the user home area containing the necessary api tokens and user keys. Default API: "pushover" Config file format: ------------------- [pushover] token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ...
3.358765
2.980736
1.126824
from smtplib import SMTP from email.mime.text import MIMEText SERVER = "localhost" _message = MIMEText(message) _message['Subject'] = subject _message['From'] = fromaddr _message['To'] = ", ".join(toaddr) server = SMTP(SERVER) server.sendmail(fromaddr, toaddr, _message.as_stri...
def send_email(fromaddr, toaddr, subject, message)
Send an email message
1.991596
2.037238
0.977596
if whoami == "user": username = getusername() domain = getdomainname() myemail = "{0}@{1}".format(username, domain) return myemail else: fromaddr = "notifier-donotreply@{0}".format(getdomainname()) return fromaddr
def get_email_address(whoami="user")
Auto-generate the FROM and TO email address
4.465785
4.214103
1.059724
import re qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]' dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]' atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+' quoted_pair = '\\x5c[\\x00-\\x7f]' domain_literal = "\\x5b(?:%s|%s)*\\x5d" % (dtext, quoted_pair) quot...
def is_valid_email(email)
RFC822 Email Address Regex -------------------------- Originally written by Cal Henderson c.f. http://iamcal.com/publish/articles/php/parsing_email/ Translated to Python by Tim Fletcher, with changes suggested by Dan Kubb. Licensed under a Creative Commons Attribution-ShareAlike 2.5 License h...
1.685787
1.674306
1.006857
from jcvi.utils.iter import flatten valid_notif_methods.extend(available_push_api.keys()) fromaddr = get_email_address(whoami="notifier") p = OptionParser(notify.__doc__) p.add_option("--method", default="email", choices=valid_notif_methods, help="Specify the mode of notific...
def notify(args)
%prog notify "Message to be sent" Send a message via email/push notification. Email notify: Recipient email address is constructed by joining the login `username` and `dnsdomainname` of the server Push notify: Uses available API
3.347692
3.254762
1.028552
import shlex from jcvi.utils.iter import flatten valid_notif_methods.extend(list(flatten(available_push_api.values()))) p = OptionParser(waitpid.__doc__) p.add_option("--notify", default="email", choices=valid_notif_methods, help="Specify type of notification to be sent after...
def waitpid(args)
%prog waitpid PID ::: "./command_to_run param1 param2 ...." Given a PID, this script will wait for the PID to finish running and then perform a desired action (notify user and/or execute a new command) Specify "--notify=METHOD` to send the user a notification after waiting for PID Specify `--grid` opt...
3.68101
3.305544
1.113587
p = which(cmd) # if in PATH, just returns it if p: return p PATH = "Path" config = RawConfigParser() cfg = op.expanduser(cfg) changed = False if op.exists(cfg): config.read(cfg) assert name is not None, "Need a program name" try: fullpath = config.get...
def getpath(cmd, name=None, url=None, cfg="~/.jcvirc", warn="exit")
Get install locations of common binaries First, check ~/.jcvirc file to get the full path If not present, ask on the console and store
3.676061
3.586463
1.024982
for k in dir(object): try: details = getattr(object, k) except Exception as e: details = e try: details = str(details) except Exception as e: details = e print("{}: {}".format(k, details), file=sys.stderr)
def inspect(object)
A better dir() showing attributes and values
2.8129
2.630012
1.069539
import random if N < len(a): return random.sample(a, N) return [random.choice(a) for x in range(N)]
def sample_N(a, N)
When size of N is >= size of a, random.sample() will emit an error: ValueError: sample larger than population This method handles such restrictions by repeatedly sampling when that happens. Examples: >>> sample_N([1, 2, 3], 2) >>> sample_N([1, 2, 3], 3) >>> sample_N([1, 2, 3], 4)
3.467086
4.140576
0.837344
dest_prog = "to {0}".format(prog) if prog else "" self.add_option("--params", dest="extra", default=params, help="Extra parameters to pass {0}".format(dest_prog) + \ " (these WILL NOT be validated)")
def set_params(self, prog=None, params="")
Add --params options for given command line programs
9.358276
8.529865
1.097119
from multiprocessing import cpu_count max_cpus = cpu_count() if not 0 < cpus < max_cpus: cpus = max_cpus self.add_option("--cpus", default=cpus, type="int", help="Number of CPUs to use, 0=unlimited [default: %default]")
def set_cpus(self, cpus=0)
Add --cpus options to specify how many threads to use.
3.592846
3.366733
1.067161
from jcvi.utils.db import valid_dbconn, get_profile self.add_option("--db", default=dbname, dest="dbname", help="Specify name of database to query [default: %default]") self.add_option("--connector", default="Sybase", dest="dbconn", choices=valid_dbconn....
def set_db_opts(self, dbname="mta4", credentials=True)
Add db connection specific attributes
2.665707
2.618312
1.018102
from jcvi.graphics.base import ImageOptions, setup_theme allowed_format = ("emf", "eps", "pdf", "png", "ps", \ "raw", "rgba", "svg", "svgz") allowed_fonts = ("Helvetica", "Palatino", "Schoolbook", "Arial") allowed_styles = ("darkgrid", "whitegrid", "da...
def set_image_options(self, args=None, figsize="6x6", dpi=300, format="pdf", font="Helvetica", palette="deep", style="darkgrid", cmap="jet")
Add image format options for given command line programs.
2.579189
2.567416
1.004585
self.set_usage(self.set_pairs.__doc__) self.add_option("--pairsfile", default=None, help="Write valid pairs to pairsfile [default: %default]") self.add_option("--nrows", default=200000, type="int", help="Only use the first n lines [default: %default]") ...
def set_pairs(self)
%prog pairs <blastfile|samfile|bedfile> Report how many paired ends mapped, avg distance between paired ends, etc. Paired reads must have the same prefix, use --rclip to remove trailing part, e.g. /1, /2, or .f, .r, default behavior is to truncate until last char.
4.168796
3.580042
1.164455
from jcvi.formats.fasta import gaps from jcvi.apps.cdhit import deduplicate, ids p = OptionParser(dedup.__doc__) p.set_align(pctid=GoodPct) p.set_mingap(default=10) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) scaffolds, = args minga...
def dedup(args)
%prog dedup scaffolds.fasta Remove redundant contigs with CD-HIT. This is run prior to assembly.sspace.embed().
3.889416
3.784457
1.027734
try: parts = id.split(".") aid = ".".join(parts[:2]) fid = int(parts[2].replace("frag", "")) except: aid, fid = None, None return aid, fid
def get_shred_id(id)
>>> get_shred_id("ca-bacs.5638.frag11.22000-23608") ("ca-bacs.5638", 11)
4.755158
3.089341
1.539214
from jcvi.apps.align import run_megablast p = OptionParser(blast.__doc__) p.add_option("-n", type="int", default=2, help="Take best N hits [default: %default]") opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) allfasta, clonename = args ...
def blast(args)
%prog blast allfasta clonename Insert a component into agpfile by aligning to the best hit in pool and see if they have good overlaps.
2.964575
2.768691
1.07075
from jcvi.apps.align import run_blat p = OptionParser(bes.__doc__) p.set_cpus() opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) bacfasta, clonename = args entrez([clonename, "--database=nucgss", "--skipcheck"]) besfasta = clonename + ".fas...
def bes(args)
%prog bes bacfasta clonename Use the clone name to download BES gss sequences from Genbank, map and then visualize.
4.371561
3.936138
1.110622
p = OptionParser(flip.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) fastafile, = args outfastafile = fastafile.rsplit(".", 1)[0] + ".flipped.fasta" fo = open(outfastafile, "w") f = Fasta(fastafile, lazy=True) for name, rec in f.it...
def flip(args)
%prog flip fastafile Go through each FASTA record, check against Genbank file and determines whether or not to flip the sequence. This is useful before updates of the sequences to make sure the same orientation is used.
2.725869
2.625648
1.03817
p = OptionParser(batchoverlap.__doc__) p.set_cpus() opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) pairsfile, outdir = args fp = open(pairsfile) cmds = [] mkdir("overlaps") for row in fp: a, b = row.split()[:2] oa = op.j...
def batchoverlap(args)
%prog batchoverlap pairs.txt outdir Check overlaps between pairs of sequences.
2.802975
2.633549
1.064334