code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
p = OptionParser(grasstruth.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) james, = args fp = open(james) pairs = set() for row in fp: atoms = row.split() genes = [] idx = {} for i, a in enumerate(atoms)...
def grasstruth(args)
%prog grasstruth james-pan-grass.txt Prepare truth pairs for 4 grasses.
3.154462
2.948055
1.070015
p = OptionParser(synfind.__doc__) opts, args = p.parse_args(args) if len(args) < 2: sys.exit(not p.print_help()) lastfile = args[0] bedfiles = args[1:] fp = open(lastfile) filteredlast = lastfile + ".filtered" fw = open(filteredlast, "w") for row in fp: b = Bla...
def synfind(args)
%prog synfind all.last *.bed Prepare input for SynFind.
2.587844
2.415478
1.071359
p = OptionParser(yeasttruth.__doc__) p.set_outfile() opts, args = p.parse_args(args) if len(args) < 2: sys.exit(not p.print_help()) pillars = args[0] gffiles = args[1:] aliases = {} pivot = {} for gffile in gffiles: is_pivot = op.basename(gffile).startswith("Sa...
def yeasttruth(args)
%prog yeasttruth Pillars.tab *.gff Prepare pairs data for 14 yeasts.
2.644542
2.511631
1.052918
from matplotlib_venn import venn2 p = OptionParser(venn.__doc__) opts, args, iopts = p.set_image_options(args, figsize="9x9") if len(args) < 1: sys.exit(not p.print_help()) bcs = args fig = plt.figure(1, (iopts.w, iopts.h)) root = fig.add_axes([0, 0, 1, 1]) pad = .02 ...
def venn(args)
%prog venn *.benchmark Display benchmark results as Venn diagram.
3.211409
3.181002
1.009559
p = OptionParser(coge.__doc__) opts, args = p.parse_args(args) if len(args) < 1: sys.exit(not p.print_help()) gffs = args for gff in gffs: atoms = op.basename(gff).split(".") gid = atoms[-2] assert gid.startswith("gid") gid = get_number(gid) gen...
def coge(args)
%prog coge *.gff Prepare coge datasets.
4.656058
4.241477
1.097744
p = OptionParser(benchmark.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) pf, bedfile = args truth = pf + ".truth" synfind = pf + ".synfind" mcscanx = pf + ".mcscanx" iadhore = pf + ".iadhore" orthofinder = pf + ".orthofinder" ...
def benchmark(args)
%prog benchmark at bedfile Compare SynFind, MCScanx, iADHoRe and OrthoFinder against the truth.
2.577518
2.19212
1.17581
p = OptionParser(cyntenator.__doc__) opts, args = p.parse_args(args) if len(args) < 2: sys.exit(not p.print_help()) lastfile = args[0] fp = open(lastfile) filteredlastfile = lastfile + ".blast" fw = open(filteredlastfile, "w") for row in fp: b = BlastLine(row) ...
def cyntenator(args)
%prog cyntenator athaliana.athaliana.last athaliana.bed Prepare input for Cyntenator.
3.852404
3.64122
1.057998
p = OptionParser(iadhore.__doc__) opts, args = p.parse_args(args) if len(args) < 2: sys.exit(not p.print_help()) lastfile = args[0] bedfiles = args[1:] blast_table = "blast_table.txt" fp = open(lastfile) seen = set() for row in fp: c = BlastLine(row) a,...
def iadhore(args)
%prog iadhore athaliana.athaliana.last athaliana.bed Wrap around iADHoRe.
3.101125
3.054992
1.015101
p = OptionParser(athalianatruth.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) atxt, bctxt = args g = Grouper() pairs = set() for txt in (atxt, bctxt): extract_groups(g, pairs, txt) fw = open("pairs", "w") for pair in ...
def athalianatruth(args)
%prog athalianatruth J_a.txt J_bc.txt Prepare pairs data for At alpha/beta/gamma.
2.825551
2.660889
1.061883
p = OptionParser(mcscanx.__doc__) opts, args = p.parse_args(args) if len(args) < 2: sys.exit(not p.print_help()) blastfile = args[0] bedfiles = args[1:] prefix = "_".join(op.basename(x)[:2] for x in bedfiles) symlink(blastfile, prefix + ".blast") allbedfile = prefix + ".gf...
def mcscanx(args)
%prog mcscanx athaliana.athaliana.last athaliana.bed Wrap around MCScanX.
2.915783
2.839213
1.026969
p = OptionParser(grass._doc__) p.set_verbose() opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) master, james = args fp = open(master) next(fp) master_store = defaultdict(set) for row in fp: atoms = row.split() s = set() ...
def grass(args)
%prog grass coge_master_table.txt james.txt Validate SynFind pan-grass set against James. This set can be generated: https://genomevolution.org/r/fhak
2.9049
2.791263
1.040711
p = OptionParser(ecoli.__doc__) p.set_outfile() opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) master, querybed = args fp = open(master) header = next(fp) assert header[0] == '#' qorg = header.strip().split("\t")[1] qorg = qorg.spli...
def ecoli(args)
%prog ecoli coge_master_table.txt query.bed Perform gene presence / absence analysis in Ecoli master spreadsheet. Ecoli spresheets can be downloaded below: Ecoli K12 MG1655 (K) as query Regenerate this analysis: https://genomevolution.org/r/fggo Ecoli O157:H7 EDL933 (O) as query Regenerate th...
4.19033
4.09256
1.02389
p = OptionParser(cartoon.__doc__) opts, args, iopts = p.set_image_options(args, figsize="10x7") fig = plt.figure(1, (iopts.w, iopts.h)) root = fig.add_axes([0, 0, 1, 1]) # Panel A A = CartoonRegion(41) A.draw(root, .35, .85, strip=False, color=False) x1, x2 = A.x1, A.x2 lsg = ...
def cartoon(args)
%prog synteny.py Generate cartoon illustration of SynFind.
3.619598
3.581594
1.010611
from jcvi.formats.base import split p = OptionParser(parallel.__doc__) p.set_home("maker") p.set_tmpdir(tmpdir="tmp") p.set_grid_opts(array=True) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) genome, NN = args threaded = opts.threaded...
def parallel(args)
%prog parallel genome.fasta N Partition the genome into parts and run separately. This is useful if MAKER is to be run on the grid.
4.754758
4.493413
1.058162
from jcvi.formats.gff import merge as gmerge p = OptionParser(merge.__doc__) p.set_home("maker") opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) outdir, outputgff = args fsnames, suffix = get_fsnames(outdir) nfs = len(fsnames) cmd = op....
def merge(args)
%prog merge outdir output.gff Follow-up command after grid jobs are completed after parallel().
6.340092
6.054099
1.04724
from jcvi.utils.counter import Counter p = OptionParser(validate.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) outdir, genome = args counter = Counter() fsnames, suffix = get_fsnames(outdir) dsfile = "{0}{1}/{0}.maker.output/{0}...
def validate(args)
%prog validate outdir genome.fasta Validate current folder after MAKER run and check for failures. Failed batch will be written to a directory for additional work.
4.380803
4.107612
1.066508
from jcvi.formats.bed import evaluate from jcvi.formats.gff import make_index p = OptionParser(evaluate.__doc__) p.add_option("--type", default="CDS", help="list of features to extract, use comma to separate (e.g." "'five_prime_UTR,CDS,three_prime_UTR') [default: %default]"...
def batcheval(args)
%prog batcheval model.ids gff_file evidences.bed fastafile Get the accuracy for a list of models against evidences in the range of the genes. For example: $ %prog batcheval all.gff3 isoforms.ids proteins.bed scaffolds.fasta Outfile contains the scores for the models can be found in models.scores
3.338075
3.009954
1.109012
bed_file = get_bed_file(gff_file, stype, key) cmd = "intersectBed -a {0} -b {1} -wao".format(split_bed, bed_file) cmd += " | cut -f4,10" p = popen(cmd) splits = defaultdict(set) for row in p: a, b = row.split() splits[a].add(b) return splits
def get_splits(split_bed, gff_file, stype, key)
Use intersectBed to find the fused gene => split genes mappings.
2.808934
2.614559
1.074343
from jcvi.formats.bed import evaluate bed_file = get_bed_file(gff_file, type, key) b = evaluate([bed_file, evidences_bed, sizesfile, "--query={0}".format(query)]) return b
def get_accuracy(query, gff_file, evidences_bed, sizesfile, type, key)
Get sensitivity, specificity and accuracy given gff_file, and a query range that look like "chr1:1-10000".
4.979709
5.055483
0.985011
from jcvi.formats.bed import Bed p = OptionParser(split.__doc__) p.add_option("--key", default="Name", help="Key in the attributes to extract predictor.gff [default: %default]") p.add_option("--parents", default="match", help="list of features to extract, use comma to separ...
def split(args)
%prog split split.bed evidences.bed predictor1.gff predictor2.gff fastafile Split MAKER models by checking against predictors (such as AUGUSTUS and FGENESH). For each region covered by a working model. Find out the combination of predictors that gives the best accuracy against evidences (such as PASA)....
2.668696
2.443971
1.091951
p = OptionParser(datastore.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) ds, = args fp = open(ds) for row in fp: fn = row.strip() assert op.exists(fn) pp, logfile = op.split(fn) flog = open(fn) for ...
def datastore(args)
%prog datastore datastore.log > gfflist.log Generate a list of gff filenames to merge. The `datastore.log` file can be generated by something like: $ find /usr/local/scratch/htang/EVM_test/gannotation/maker/1132350111853_default/i1/ -maxdepth 4 -name "*datastore*.log" > datastore.log
3.739252
3.642381
1.026596
from jcvi.formats.base import DictFile p = OptionParser(libsvm.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) csvfile, prefixids = args d = DictFile(prefixids) fp = open(csvfile) next(fp) for row in fp: atoms = row.spl...
def libsvm(args)
%prog libsvm csvfile prefix.ids Convert csv file to LIBSVM format. `prefix.ids` contains the prefix mapping. Ga -1 Gr 1 So the feature in the first column of csvfile get scanned with the prefix and mapped to different classes. Formatting spec: http://svmlight.joachims.org/
3.100321
2.757751
1.124221
N = len(nodes) E = len(edges) A = np.zeros((E, N), dtype=int) for i, (a, b, distance) in enumerate(edges): A[i, a] = 1 A[i, b] = -1 K = np.eye(E, dtype=int) L = np.array([x[-1] for x in edges]) s = spring_system(A, K, L) return np.array([0] + [int(round(x, 0)) for...
def determine_positions(nodes, edges)
Construct the problem instance to solve the positions of contigs. The input for spring_system() is A, K, L, which looks like the following. A = np.array([[1, -1, 0], [0, 1, -1], [1, 0, -1]]) K = np.eye(3, dtype=int) L = np.array([1, 2, 3]) For example, A-B distance 1, B-C distance 2, A-C distance ...
3.101441
2.536464
1.222742
N = len(nodes) M = np.zeros((N, N), dtype=float) for a, b, w in edges: M[a, b] += w M = symmetrize(M) return get_signs(M, cutoff=cutoff, validate=False)
def determine_signs(nodes, edges, cutoff=1e-10)
Construct the orientation matrix for the pairs on N molecules. >>> determine_signs([0, 1, 2], [(0, 1, 1), (0, 2, -1), (1, 2, -1)]) array([ 1, 1, -1])
3.460259
3.877702
0.892348
# Is this a symmetric matrix? assert is_symmetric(M), "the matrix is not symmetric:\n{0}".format(str(M)) N, x = M.shape # eigh() works on symmetric matrix (Hermitian) w, v = np.linalg.eigh(M) m = np.argmax(w) mv = v[:, m] f = lambda x: (x if abs(x) > cutoff else 0) mv = [f(x) f...
def get_signs(M, cutoff=1e-10, validate=True, ambiguous=True)
Given a numpy array M that contains pairwise orientations, find the largest eigenvalue and associated eigenvector and return the signs for the eigenvector. This should correspond to the original orientations for the individual molecule. In the first example below, let's say 3 molecules A, B and C, A-B:s...
5.168143
5.298134
0.975465
# Linear equation is A'KAx = -A'KL C = np.dot(A.T, K) left = np.dot(C, A) right = - np.dot(C, L) left = left[1:, 1:] right = right[1:] x = np.linalg.solve(left, right) return x
def spring_system(A, K, L)
Solving the equilibrium positions of the objects, linked by springs of length L, stiffness of K, and connectivity matrix A. Then solving: F_nodes = -A'KAx - A'KL = 0 In the context of scaffolding, lengths (L) are inferred by mate inserts, stiffness (K) is inferred via the number of links, connectivity...
4.700365
4.598763
1.022093
p = OptionParser(fix.__doc__) p.add_option("--ignore_sym_pat", default=False, action="store_true", help="Do not fix names matching symbol patterns i.e." + \ " names beginning or ending with gene symbols or a series of numbers." + \ " e.g. `ARM repeat superfamily protein`, `beta-hexo...
def fix(args)
%prog fix ahrd.csv > ahrd.fixed.csv Fix ugly names from Uniprot.
5.867056
5.490234
1.068635
p = OptionParser(merge.__doc__) opts, args = p.parse_args(args) if len(args) < 1: sys.exit(not p.print_help()) csvfiles = args cf = csvfiles[0] fp = open(cf) for row in fp: if row.startswith("Protein"): break header = row.rstrip() print(header) ...
def merge(args)
%prog merge output/*.csv > ahrd.csv Merge AHRD results, remove redundant headers, empty lines, etc. If there are multiple lines containing the same ID (first column). Then whatever comes the first will get retained.
2.830992
2.734676
1.03522
p = OptionParser(batch.__doc__) ahrd_weights = { "blastp": [0.5, 0.3, 0.2], "blastx": [0.6, 0.4, 0.0] } blast_progs = tuple(ahrd_weights.keys()) p.add_option("--path", default="~/code/AHRD/", help="Path where AHRD is installed [default: %de...
def batch(args)
%prog batch splits output The arguments are two folders. Input FASTA sequences are in splits/. Output csv files are in output/. Must have folders swissprot/, tair/, trembl/ that contains the respective BLAST output. Once finished, you can run, for example: $ parallel java -Xmx2g -jar ~/code/A...
3.946648
3.587261
1.100184
if gff3: s = s.replace('+', 'PlusSign') d = parse_qs(s, keep_attr_order=keep_attr_order) for key in d: d[key][0] = unquote(d[key][0].replace('PlusSign', '+').replace('"', '')) else: attributes = s.split(";") d = DefaultOrderedDict(list) if keep_a...
def make_attributes(s, gff3=True, keep_attr_order=True)
In GFF3, the last column is typically: ID=cds00002;Parent=mRNA00002; In GFF2, the last column is typically: Gene 22240.t000374; Note "Carbonic anhydrase"
3.084357
3.37514
0.913846
from jcvi.utils.range import Range if score or id: _score = score if score else obj.score _id = id if id else obj.id return Range(seqid=obj.seqid, start=obj.start, end=obj.end, \ score=_score, id=_id) elif strand: return (obj.seqid, obj.start, obj.end, obj.s...
def to_range(obj, score=None, id=None, strand=None)
Given a gffutils object, convert it to a range object
2.339034
2.341828
0.998807
p = OptionParser(addparent.__doc__) p.add_option("--childfeat", default="CDS", help="Type of children feature") p.add_option("--parentfeat", default="mRNA", help="Type of merged feature") p.set_outfile() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()...
def addparent(args)
%prog addparent file.gff Merge sister features and infer parents.
2.512474
2.440731
1.029394
_strand = 1 if strand == '+' else -1 return fasta.sequence({'chr': seqid, 'start': start, 'stop': stop, \ 'strand': _strand})
def _fasta_slice(fasta, seqid, start, stop, strand)
Return slice of fasta, given (seqid, start, stop, strand)
4.024476
3.937519
1.022084
if len(codon) != 3: return False if type == 'start': if codon != 'ATG': return False elif type == 'stop': if not any(_codon == codon for _codon in ('TGA', 'TAG', 'TAA')): return False else: logging.error("`{0}` is not a valid codon type. ".fo...
def is_valid_codon(codon, type='start')
Given a codon sequence, check if it is a valid start/stop codon
2.671605
2.659463
1.004566
s, e = codon_span[0], codon_span[1] while True: if (type == 'start' and strand == '+') or \ (type == 'stop' and strand == '-'): s, e = s - 3, e - 3 else: s, e = s + 3, e + 3 codon = _fasta_slice(genome, seqid, s, e, strand) is_valid = is_...
def scan_for_valid_codon(codon_span, strand, seqid, genome, type='start')
Given a codon span, strand and reference seqid, scan upstream/downstream to find a valid in-frame start/stop codon
2.222182
2.146001
1.035499
p = OptionParser(sizes.__doc__) p.set_outfile() p.add_option("--parents", dest="parents", default="mRNA", help="parent feature(s) for which size is to be calculated") p.add_option("--child", dest="child", default="CDS", help="child feature to use for size calculations") ...
def sizes(args)
%prog sizes gffile Given a gff file of features, calculate the sizes of chosen parent feature based on summation of sizes of child features. For example, for parent 'mRNA' and child 'CDS' feature types, calcuate sizes of mRNA by summing the sizes of the disjoint CDS parts.
3.274271
2.877501
1.137887
from jcvi.utils.grouper import Grouper from itertools import combinations p = OptionParser(cluster.__doc__) p.add_option("--slop", default=False, action="store_true", help="allow minor variation in terminal 5'/3' UTR" + \ " start/stop position [default: %default]") ...
def cluster(args)
%prog cluster gffile Given a gff file of gene structures (multiple transcripts per gene locus), cluster/consolidate all transcripts based on shared splicing structure. If `slop` is enabled, clustering/consolidation will collapse any variation in terminal UTR lengths, keeping only the longest as repres...
2.358458
2.27633
1.036079
from jcvi.formats.base import SetFile from jcvi.formats.bed import BedSummary from jcvi.utils.table import tabulate p = OptionParser(summary.__doc__) p.add_option("--isoform", default=False, action="store_true", help="Find longest isoform of each id") p.add_option("--ids",...
def summary(args)
%prog summary gffile Print summary stats for features of different types.
2.746888
2.674602
1.027027
from Bio.Alphabet import generic_dna try: from BCBio import GFF except ImportError: print("You need to install dep first: $ easy_install bcbio-gff", file=sys.stderr) p = OptionParser(gb.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.prin...
def gb(args)
%prog gb gffile fastafile Convert GFF3 to Genbank format. Recipe taken from: <http://www.biostars.org/p/2492/>
2.598323
2.422902
1.072401
from jcvi.formats.fasta import longestorf p = OptionParser(orient.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) ingff3, fastafile = args idsfile = fastafile.rsplit(".", 1)[0] + ".orf.ids" if need_update(fastafile, idsfile): l...
def orient(args)
%prog orient in.gff3 features.fasta > out.gff3 Change the feature orientations based on translation. This script is often needed in fixing the strand information after mapping RNA-seq transcripts. You can generate the features.fasta similar to this command: $ %prog load --parents=EST_match --children...
3.276163
3.210238
1.020536
p = OptionParser(rename.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) ingff3, switch = args switch = DictFile(switch) gff = Gff(ingff3) for g in gff: id, = g.attributes["ID"] newname = switch.get(id, id) g.att...
def rename(args)
%prog rename in.gff3 switch.ids > reindexed.gff3 Change the IDs within the gff3.
2.848674
2.359897
1.207118
p = OptionParser(parents.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) gff_file, idsfile = args g = make_index(gff_file) fp = open(idsfile) for row in fp: cid = row.strip() b = next(g.parents(cid, 1)) print("\...
def parents(args)
%prog parents gffile models.ids Find the parents given a list of IDs in "models.ids".
3.82469
3.235641
1.18205
p = OptionParser(filter.__doc__) p.add_option("--type", default="mRNA", help="The feature to scan for the attributes [default: %default]") g1 = OptionGroup(p, "Filter by identity/coverage attribute values") g1.add_option("--id", default=95, type="float", help="Minimum ...
def filter(args)
%prog filter gffile > filtered.gff Filter the gff file based on criteria below: (1) feature attribute values: [Identity, Coverage]. You can get this type of gff by using gmap $ gmap -f 2 .... (2) Total bp length of child features
2.386064
2.303233
1.035963
p = OptionParser(gapsplit.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) gffile, = args gff = Gff(gffile) for g in gff: if re.match("EST_match", g.type): match = re.search(r'\S+ (\d+) \d+ ([\s{1}\-])', g....
def gapsplit(args)
%prog gapsplit gffile > split.gff Read in the gff (normally generated by GMAP) and print it out after splitting each feature into one parent and multiple child features based on alignment information encoded in CIGAR string.
2.458143
2.390766
1.028182
p = OptionParser(fixboundaries.__doc__) p.add_option("--type", default="gene", type="str", help="Feature type for which to adjust boundaries") p.add_option("--child_ftype", default="mRNA", type="str", help="Child featuretype(s) to use for identifying boundaries") p...
def fixboundaries(args)
%prog fixboundaries gffile --type="gene" --child_ftype="mRNA" > gffile.fixed Adjust the boundary coordinates of parents features based on range chained child features, extracting their min and max values
2.792766
2.356482
1.185142
p = OptionParser(liftover.__doc__) p.add_option("--tilesize", default=50000, type="int", help="The size for each tile [default: %default]") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) gffile, = args gff = Gff(gffile) for g i...
def liftover(args)
%prog liftover gffile > liftover.gff Adjust gff coordinates based on tile number. For example, "gannotation.asmbl.000095.7" is the 8-th tile on asmbl.000095.
2.474503
2.16694
1.141934
from jcvi.utils.range import Range, range_piles ranges = [Range(a.seqid, a.start, a.end, 0, i) \ for i, a in enumerate(allgenes)] for pile in range_piles(ranges): yield [allgenes[x] for x in pile]
def get_piles(allgenes)
Before running uniq, we need to compute all the piles. The piles are a set of redundant features we want to get rid of. Input are a list of GffLines features. Output are list of list of features distinct "piles".
4.430434
4.237797
1.045457
f1c, f2c = list(dbx1.children(f1, featuretype=featuretype, order_by='start')), \ list(dbx2.children(f2, featuretype=featuretype, order_by='start')) lf1c, lf2c = len(f1c), len(f2c) if match_nchildren(f1c, f2c): if lf1c > 0 and lf2c > 0: exclN = set() if featu...
def match_subfeats(f1, f2, dbx1, dbx2, featuretype=None, slop=False)
Given 2 gffutils features located in 2 separate gffutils databases, iterate through all subfeatures of a certain type and check whether they are identical or not The `slop` parameter allows for variation in the terminal UTR region
2.889957
2.848741
1.014468
supported_modes = ("span", "score") p = OptionParser(uniq.__doc__) p.add_option("--type", default="gene", help="Types of features to non-redundify [default: %default]") p.add_option("--mode", default="span", choices=supported_modes, help="Pile mode [default: %defau...
def uniq(args)
%prog uniq gffile > uniq.gff Remove redundant gene models. For overlapping gene models, take the longest gene. A second scan takes only the genes selected. --mode controls whether you want larger feature, or higher scoring feature. --best controls how many redundant features to keep, e.g. 10 for est2g...
3.105157
2.960523
1.048854
valid_sort_methods = ("unix", "topo") p = OptionParser(sort.__doc__) p.add_option("--method", default="unix", choices=valid_sort_methods, help="Specify sort method [default: %default]") p.add_option("-i", dest="inplace", default=False, action="store_true", help="I...
def sort(args)
%prog sort gffile Sort gff file using plain old unix sort based on [chromosome, start coordinate]. or topologically based on hierarchy of features using the gt (genometools) toolkit
3.110766
2.903384
1.071428
p = OptionParser(fromgtf.__doc__) p.add_option("--transcript_id", default="transcript_id", help="Field name for transcript [default: %default]") p.add_option("--gene_id", default="gene_id", help="Field name for gene [default: %default]") p.add_option("--augustus", ...
def fromgtf(args)
%prog fromgtf gtffile Convert gtf to gff file. In gtf, the "transcript_id" will convert to "ID=", the "transcript_id" in exon/CDS feature will be converted to "Parent=".
2.229429
2.170307
1.027241
p = OptionParser(frombed.__doc__) p.add_option("--type", default="match", help="GFF feature type [default: %default]") p.add_option("--source", default="default", help="GFF source qualifier [default: %default]") opts, args = p.parse_args(args) if len(args) != 1...
def frombed(args)
%prog frombed bed_file [--options] > gff_file Convert bed to gff file. In bed, the accn will convert to key='ID' Default type will be `match` and default source will be `source`
2.65457
2.154772
1.231949
p = OptionParser(fromsoap.__doc__) p.add_option("--type", default="nucleotide_match", help="GFF feature type [default: %default]") p.add_option("--source", default="soap", help="GFF source qualifier [default: %default]") p.set_fixchrnames(orgn="maize") p.set_out...
def fromsoap(args)
%prog fromsoap soapfile > gff_file
3.687697
3.341352
1.103654
p = OptionParser(gtf.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) gffile, = args gff = Gff(gffile) transcript_info = AutoVivification() for g in gff: if g.type.endswith(("RNA", "transcript")): if "ID" in g.attribu...
def gtf(args)
%prog gtf gffile Convert gff to gtf file. In gtf, only exon/CDS features are important. The first 8 columns are the same as gff, but in the attributes field, we need to specify "gene_id" and "transcript_id".
2.350284
2.284036
1.029005
p = OptionParser(merge.__doc__) p.add_option("--seq", default=False, action="store_true", help="Print FASTA sequences at the end") p.set_outfile() opts, args = p.parse_args(args) nargs = len(args) if nargs < 1: sys.exit(not p.print_help()) if nargs == 1: ...
def merge(args)
%prog merge gffiles Merge several gff files into one. When only one file is given, it is assumed to be a file with a list of gff files.
2.880445
2.677744
1.075698
p = OptionParser(extract.__doc__) p.add_option("--contigs", help="Extract features from certain contigs [default: %default]") p.add_option("--names", help="Extract features with certain names [default: %default]") p.add_option("--types", type="str", default=None, ...
def extract(args)
%prog extract gffile --contigs: Extract particular contig(s) from the gff file. If multiple contigs are involved, use "," to separate, e.g. "contig_12,contig_150"; or provide a file with multiple contig IDs, one per line --names: Process particular ID(s) from the gff file. If multiple IDs are invol...
3.188984
2.936364
1.086031
p = OptionParser(split.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) gffile, outdir = args mkdir(outdir) g = Gff(gffile) seqids = g.seqids for s in seqids: outfile = op.join(outdir, s + ".gff") extract([gffile, ...
def split(args)
%prog split gffile outdir Split the gff into one contig per file. Will also take sequences if the file contains FASTA sequences.
3.162964
2.681286
1.179644
p = OptionParser(note.__doc__) p.add_option("--type", default=None, help="Only process certain types, multiple types allowed with comma") p.add_option("--attribute", default="Parent,Note", help="Attribute field to extract, multiple fields allowd with comma") p.add_option("--...
def note(args)
%prog note gffile > tabfile Extract certain attribute field for each feature.
3.046747
2.753163
1.106635
from tempfile import mkstemp from pybedtools import BedTool from jcvi.utils.cbook import SummaryStats p = OptionParser(splicecov.__doc__) p.set_outfile() opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) gfffile, juncsbed, = args tagged ...
def splicecov(args)
%prog splicecov annotation.gff3 junctions.bed Given an annotation GFF file (containing introns) and a TopHat junctions.bed file (preprocessed using formats.bed.juncs(), each intron gets tagged with the JUNC identifier and read coverage. Output is a summary table listing for each gene locus, the isofor...
2.786511
2.699027
1.032413
''' %prog bed gff_file [--options] Parses the start, stop locations of the selected features out of GFF and generate a bed file ''' from jcvi.utils.cbook import gene_name p = OptionParser(bed.__doc__) p.add_option("--type", dest="type", default="gene", help="Feature type to...
def bed(args)
%prog bed gff_file [--options] Parses the start, stop locations of the selected features out of GFF and generate a bed file
2.638214
2.374987
1.110833
import gffutils db_file = gff_file + ".db" if need_update(gff_file, db_file): if op.exists(db_file): os.remove(db_file) logging.debug("Indexing `{0}`".format(gff_file)) gffutils.create_db(gff_file, db_file, merge_strategy="create_unique") else: logging.d...
def make_index(gff_file)
Make a sqlite database for fast retrieval of features.
2.340239
2.372663
0.986334
p = OptionParser(children.__doc__) p.add_option("--parents", default="gene", help="list of features to extract, use comma to separate (e.g." "'gene,mRNA') [default: %default]") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) gff...
def children(args)
%prog children gff_file Get the children that have the same parent.
3.408213
3.064181
1.112275
# can request upstream sequence only from the following valid sites valid_upstream_sites = ["TSS", "TrSS"] upstream_site, upstream_len = None, None flag, error_msg = None, None parents, children = None, None if re.match(r'upstream', feature): parents, children = "mRNA", "CDS" ...
def parse_feature_param(feature)
Take the --feature param (coming from gff.load() and parse it. Returns feature, parents and children terms. Also returns length of upstream sequence (and start site) requested If erroneous, returns a flag and error message to be displayed on exit
3.330456
2.988718
1.114343
if uSite == "TSS": (upstream_start, upstream_stop) = \ (feat.start - uLen, feat.start - 1) \ if feat.strand == "+" else \ (feat.end + 1, feat.end + uLen) elif uSite == "TrSS": children = [] for c in gffdb.children(feat.id, 1): ...
def get_upstream_coords(uSite, uLen, seqlen, feat, children_list, gffdb)
Subroutine takes upstream site, length, reference sequence length, parent mRNA feature (GffLine object), list of child feature types and a GFFutils.GFFDB object as the input If upstream of TSS is requested, use the parent feature coords to extract the upstream sequence If upstream of TrSS is reque...
2.406862
2.239722
1.074625
p = OptionParser(bed12.__doc__) p.add_option("--parent", default="mRNA", help="Top feature type [default: %default]") p.add_option("--block", default="exon", help="Feature type for regular blocks [default: %default]") p.add_option("--thick", default="CDS", help="...
def bed12(args)
%prog bed12 gffile > bedfile Produce bed12 file for coding features. The exons will be converted to blocks. The CDS range will be shown between thickStart to thickEnd. For reference, bed format consists of the following fields: 1. chrom 2. chromStart 3. chromEnd 4. name 5. score 6....
2.177887
2.009732
1.08367
sig_elems = [self.seqid, self.source, self.type, \ self.start, self.end, self.strand, \ self.phase] if re.search("exon|CDS|UTR", self.type): parent = self.get_attr("Parent") if parent: (locus, iso) = atg_name(parent...
def signature(self)
create a unique signature for any GFF line based on joining columns 1,2,3,4,5,7,8 (into a comma separated string)
4.999623
4.476635
1.116826
p = OptionParser(main.__doc__) p.add_option("--refids", help="Use subset of contigs in the ref") p.add_option("--refcov", default=.01, type="float", help="Minimum reference coverage [default: %default]") p.add_option("--all", default=False, action="store_true", hel...
def main(args)
%prog deltafile Plot one query. Extract the references that have major matches to this query. Control "major" by option --refcov.
3.481893
3.206017
1.086049
p = OptionParser(bed.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(p.print_help()) flist = args prefix = flist[0].split(".")[0] j = 0 for f in flist: reader = Maf(f).reader for rec in reader: a, b = rec.components ...
def bed(args)
%prog bed maffiles > out.bed Convert a folder of maf alignments to the bed features then useful to check coverage, etc.
3.893902
3.707149
1.050377
''' %prog blast maffiles > out.blast From a folder of .maf files, generate .blast file with tabular format. ''' p = OptionParser(blast.__doc__) opts, args = p.parse_args(args) if len(args) == 0: sys.exit(p.print_help()) flist = args for f in flist: maf_to_blast8(f...
def blast(args)
%prog blast maffiles > out.blast From a folder of .maf files, generate .blast file with tabular format.
4.370489
2.25994
1.933896
indexes = interval_index_file.Indexes() in_handle = open(filename) reader = maf.Reader(in_handle) while True: pos = reader.file.tell() rec = next(reader) if rec is None: break for c in rec.components: ...
def build_index(self, filename, indexfile)
Recipe from Brad Chapman's blog <http://bcbio.wordpress.com/2009/07/26/sorting-genomic-alignments-using-python/>
4.716141
4.494425
1.049331
size = len(candidate) prob = random.random() if prob > .5: # Inversion p = random.randint(0, size-1) q = random.randint(0, size-1) if p > q: p, q = q, p q += 1 s = candidate[p:q] x = candidate[:p] + s[::-1] + candidate[q:] return cr...
def genome_mutation(candidate)
Return the mutants created by inversion mutation on the candidates. This function performs inversion or insertion. It randomly chooses two locations along the candidate and reverses the values within that slice. Insertion is done by popping one item and insert it back at random position.
2.829352
2.634816
1.073833
# Evaluate the individuals with an invalid fitness invalid_ind = [ind for ind in population if not ind.fitness.valid] fitnesses = toolbox.map(toolbox.evaluate, invalid_ind) for ind, fit in zip(invalid_ind, fitnesses): ind.fitness.values = fit if halloffame is not None: halloffa...
def eaSimpleConverge(population, toolbox, cxpb, mutpb, ngen, stats=None, halloffame=None, callback=None, verbose=True)
This algorithm reproduce the simplest evolutionary algorithm as presented in chapter 7 of [Back2000]_. Modified to allow checking if there is no change for ngen, as a simple rule for convergence. Interface is similar to eaSimple(). However, in eaSimple, ngen is total number of iterations; in eaSimpleCo...
1.693926
1.776109
0.953729
from jcvi.formats.fasta import Fasta from jcvi.formats.bed import Bed from jcvi.utils.cbook import fill p = OptionParser(frombed.__doc__) opts, args = p.parse_args(args) if len(args) != 3: sys.exit(not p.print_help()) bedfile, contigfasta, readfasta = args prefix = bedfil...
def frombed(args)
%prog frombed bedfile contigfasta readfasta Convert read placement to contig format. This is useful before running BAMBUS.
2.999459
2.804577
1.069487
p = OptionParser(main.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) contigfile, = args bedfile = contigfile.rsplit(".", 1)[0] + ".bed" fw = open(bedfile, "w") c = ContigFile(contigfile) for rec in c.iter_records(): for r ...
def bed(args)
%prog bed contigfile Prints out the contigs and their associated reads.
3.03594
2.800821
1.083947
''' runs the command: `tesseract_cmd` `input_filename` `output_filename_base` returns the exit status of tesseract, as well as tesseract's stderr output ''' command = [tesseract_cmd, input_filename, output_filename_base] if lang is not None: command += ['-l', lang] if bo...
def run_tesseract(input_filename, output_filename_base, lang=None, boxes=False)
runs the command: `tesseract_cmd` `input_filename` `output_filename_base` returns the exit status of tesseract, as well as tesseract's stderr output
3.760585
2.402981
1.564966
''' returns all lines in the error_string that start with the string "error" ''' lines = error_string.splitlines() error_lines = tuple(line for line in lines if line.find('Error') >= 0) if len(error_lines) > 0: return '\n'.join(error_lines) else: return error_string.strip()
def get_errors(error_string)
returns all lines in the error_string that start with the string "error"
3.510636
2.564074
1.369163
''' returns a temporary file-name ''' # prevent os.tmpname from printing an error... stderr = sys.stderr try: sys.stderr = cStringIO.StringIO() return os.tempnam(None, 'tess_') finally: sys.stderr = stderr
def tempnam()
returns a temporary file-name
7.023331
7.057039
0.995223
''' Runs tesseract on the specified image. First, the image is written to disk, and then the tesseract command is run on the image. Resseract's result is read, and the temporary files are erased. ''' input_file_name = '%s.bmp' % tempnam() output_file_name_base = tempnam() if not boxes:...
def image_to_string(image, lang=None, boxes=False)
Runs tesseract on the specified image. First, the image is written to disk, and then the tesseract command is run on the image. Resseract's result is read, and the temporary files are erased.
3.181112
2.198546
1.446916
import pandas as pd p = OptionParser(mitosomatic.__doc__) p.add_option("--minaf", default=.005, type="float", help="Minimum allele fraction") p.add_option("--maxaf", default=.1, type="float", help="Maximum allele fraction") opts, args = p.parse_args(args) ...
def mitosomatic(args)
%prog mitosomatic t.piledriver Find mito mosaic somatic mutations in piledriver results.
2.42432
2.446278
0.991024
p = OptionParser(bed.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) delt, = args dt = Delly(delt) dt.write_bed("del.bed")
def bed(args)
%prog bed del.txt Convert `del.txt` to BED format. DELLY manual here: <http://www.embl.de/~rausch/delly.html> Deletion: chr, start, end, size, #supporting_pairs, avg._mapping_quality, deletion_id chr1, 10180, 10509, 329, 75, 15.8667, Deletion_Sample_00000000
3.998654
3.428037
1.166456
from jcvi.formats.vcf import VcfLine from six.moves.urllib.parse import parse_qsl p = OptionParser(mitocompile.__doc__) opts, args = p.parse_args(args) if len(args) < 1: sys.exit(not p.print_help()) vcfs = args print("\t".join("vcf samplekey depth seqid pos alt svlen pe sr".s...
def mitocompile(args)
%prog mitcompile *.vcf.gz Extract information about deletions in vcf file.
3.638021
3.526044
1.031757
p = OptionParser(mito.__doc__) p.set_aws_opts(store="hli-mv-data-science/htang/mito-deletions") p.add_option("--realignonly", default=False, action="store_true", help="Realign only") p.add_option("--svonly", default=False, action="store_true", help="Run Realign => ...
def mito(args)
%prog mito chrM.fa input.bam Identify mitochondrial deletions.
3.545511
3.317906
1.068599
p = OptionParser(fcs.__doc__) p.add_option("--cutoff", default=200, help="Skip small components less than [default: %default]") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) fcsfile, = args cutoff = opts.cutoff fp = open(fcsfi...
def fcs(args)
%prog fcs fcsfile Process the results from Genbank contaminant screen. An example of the file looks like: contig name, length, span(s), apparent source contig0746 11760 1..141 vector contig0751 14226 13476..14226 vector contig0800 124133 30512..30559 primer/adapter
2.88502
2.814128
1.025191
from jcvi.formats.base import must_open p = OptionParser(asn.__doc__) p.set_outfile() opts, args = p.parse_args(args) if len(args) < 1: sys.exit(not p.print_help()) fw = must_open(opts.outfile, "w") for asnfile in args: fp = open(asnfile) ingeneralblock = Fals...
def asn(args)
%prog asn asnfiles Mainly to get this block, and extract `str` field: general { db "TIGR" , tag str "mtg2_12952" } , genbank { accession "AC148996" ,
2.84407
2.612783
1.088521
from jcvi.formats.fasta import sequin p = OptionParser(htgnew.__doc__) p.add_option("--comment", default="", help="Comments for this submission [default: %default]") opts, args = p.parse_args(args) if len(args) != 3: sys.exit(not p.print_help()) fastafile, phasefile, ...
def htgnew(args)
%prog htgnew fastafile phasefile template.sbt Prepare sqnfiles for submitting new Genbank HTG records. `fastafile` contains the sequences. `phasefile` contains the phase information, it is a two column file: mth2-45h12 3 `template.sbt` is the Genbank submission template. This function is...
4.904938
4.534799
1.081622
rows, cols = get_rows_cols() plate, splate = get_plate() n96 = rows.index(c96[0]) * ncols / 2 + int(c96[1:]) q = "{0:02d}{1}".format(n96, "ABCD"[quad - 1]) return splate[q]
def convert_96_to_384(c96, quad, nrows=Nrows, ncols=Ncols)
Convert the 96-well number and quad number to 384-well number >>> convert_96_to_384("B02", 1) 'C3' >>> convert_96_to_384("H09", 4) 'P18'
7.721169
8.131645
0.949521
p = OptionParser(t384.__doc__) opts, args = p.parse_args(args) plate, splate = get_plate() fw = sys.stdout for i in plate: for j, p in enumerate(i): if j != 0: fw.write('|') fw.write(p) fw.write('\n')
def t384(args)
%prog t384 Print out a table converting between 96 well to 384 well
4.8772
4.384521
1.112368
s = "".join(s.split()[1:]).replace("/", ";") a = parse_qs(s) return a
def parse_description(s)
Returns a dictionary based on the FASTA header, assuming JCVI data
11.196808
9.586869
1.167932
from jcvi.formats.base import FileMerger from jcvi.formats.bed import mates from jcvi.formats.contig import frombed from jcvi.formats.fasta import join from jcvi.utils.iter import grouper p = OptionParser(scaffold.__doc__) p.set_rclip(rclip=1) p.add_option("--conf", help="BAMBUS c...
def scaffold(args)
%prog scaffold ctgfasta reads1.fasta mapping1.bed reads2.fasta mapping2.bed ... Run BAMBUS on set of contigs, reads and read mappings.
3.93345
3.759332
1.046316
from jcvi.formats.fastq import shuffle, pairinplace, split from jcvi.apps.base import getfilesize p = OptionParser(diginorm.__doc__) p.add_option("--single", default=False, action="store_true", help="Single end reads") p.add_option("--tablesize", help="Memory size") p.add_...
def diginorm(args)
%prog diginorm fastqfile Run K-mer based normalization. Based on tutorial: <http://ged.msu.edu/angus/diginorm-2012/tutorial.html> Assume input is either an interleaved pairs file, or two separate files. To set up khmer: $ git clone git://github.com/ged-lab/screed.git $ git clone git://github....
3.442291
3.438977
1.000963
import math from jcvi.formats.fasta import Fasta, SeqIO from jcvi.formats.fastq import readlen, first, fasta from jcvi.formats.blast import Blast from jcvi.formats.base import FileShredder from jcvi.apps.bowtie import align, get_samfile from jcvi.apps.align import blast p = Option...
def expand(args)
%prog expand bes.fasta reads.fastq Expand sequences using short reads. Useful, for example for getting BAC-end sequences. The template to use, in `bes.fasta` may just contain the junction sequences, then align the reads to get the 'flanks' for such sequences.
4.4566
4.348136
1.024945
from jcvi.apps.bowtie import BowtieLogFile, align p = OptionParser(contamination.__doc__) p.set_firstN() opts, args = p.parse_args(args) if len(args) != 3: sys.exit(not p.print_help()) ecoli, genome, fq = args firstN_opt = "--firstN={0}".format(opts.firstN) samfile, logfi...
def contamination(args)
%prog contamination Ecoli.fasta genome.fasta read.fastq Check read contamination on a folder of paired reads. Use bowtie2 to compare the reads against: 1. Ecoli.fsata - this will tell us the lower bound of contamination 2. genome.fasta - this will tell us the upper bound of contamination
3.443541
3.246171
1.060801
choices = "prepare,align,filter,rmdup,genreads".split(",") p = OptionParser(alignextend.__doc__) p.add_option("--nosuffix", default=False, action="store_true", help="Do not add /1/2 suffix to the read [default: %default]") p.add_option("--rc", default=False, action="store_true", ...
def alignextend(args)
%prog alignextend ref.fasta read.1.fastq read.2.fastq Wrapper around AMOS alignextend.
3.195261
3.073931
1.039471
from jcvi.utils.table import loadtable, write_csv p = OptionParser(count.__doc__) p.add_option("--dir", help="Sub-directory where FASTQC was run [default: %default]") p.add_option("--human", default=False, action="store_true", help="Human friendly numbers [default: ...
def count(args)
%prog count *.gz Count reads based on FASTQC results. FASTQC needs to be run on all the input data given before running this command.
3.325669
3.271976
1.01641
p = OptionParser(hetsmooth.__doc__) p.add_option("-K", default=23, type="int", help="K-mer size [default: %default]") p.add_option("-L", type="int", help="Bottom threshold, first min [default: %default]") p.add_option("-U", type="int", help="Top th...
def hetsmooth(args)
%prog hetsmooth reads_1.fq reads_2.fq jf-23_0 Wrapper against het-smooth. Below is the command used in het-smooth manual. $ het-smooth --kmer-len=23 --bottom-threshold=38 --top-threshold=220 --no-multibase-replacements --jellyfish-hash-file=23-mers.jf reads_1.fq reads_2.fq
3.177659
2.148694
1.478879
from jcvi.assembly.allpaths import prepare from jcvi.assembly.base import FastqNamings p = OptionParser(correct.__doc__ + FastqNamings) p.add_option("--dir", default="data", help="Working directory [default: %default]") p.add_option("--fragsdedup", default=False, action="store_...
def correct(args)
%prog correct *.fastq Correct the fastqfile and generated corrected fastqfiles. This calls assembly.allpaths.prepare() to generate input files for ALLPATHS-LG. The naming convention for your fastqfiles are important, and are listed below. By default, this will correct all PE reads, and remove duplicat...
3.256847
3.027355
1.075806
import re import csv p = OptionParser(fetch.__doc__) p.add_option("--format", default="tab", choices=valid_formats, help="download format [default: %default]") p.add_option("--columns", default="entry name, protein names, genes,organism", help="columns to down...
def fetch(args)
%prog fetch "query" OR %prog fetch queries.txt Please provide a UniProt compatible `query` to retrieve data. If `query` contains spaces, please remember to "quote" it. You can also specify a `filename` which contains queries, one per line. Follow this syntax <http://www.uniprot.org/help/t...
3.110633
3.037267
1.024155
chr, se = s.split(":") start, end = se.split("-") start, end = int(start), int(end) if start > end: start, end = end, start return Range(chr, start, end, 0, 0)
def range_parse(s)
>>> range_parse("chr1:1000-1") Range(seqid='chr1', start=1, end=1000, score=0, id=0)
3.141739
2.639445
1.190303
a_min, a_max = a if a_min > a_max: a_min, a_max = a_max, a_min b_min, b_max = b if b_min > b_max: b_min, b_max = b_max, b_min if a_max + extend < b_min or b_max + extend < a_min: return None i_min = max(a_min, b_min) i_max = min(a_max, b_max) if i_min > i_ma...
def range_intersect(a, b, extend=0)
Returns the intersection between two reanges. >>> range_intersect((30, 45), (55, 65)) >>> range_intersect((48, 65), (45, 55)) [48, 55]
1.632901
1.791242
0.911602
if not rset: return None a = rset[0] for b in rset[1:]: if not a: return None a = range_intersect(a, b) return a
def ranges_intersect(rset)
Recursively calls the range_intersect() - pairwise version. >>> ranges_intersect([(48, 65), (45, 55), (50, 56)]) [50, 55]
2.908381
3.328662
0.873739