code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
from jcvi.formats.blast import chain_HSPs p = OptionParser(overlap.__doc__) p.add_option("--dir", default=os.getcwd(), help="Download sequences to dir [default: %default]") p.add_option("--suffix", default="fasta", help="Suffix of the sequence file in dir [default: %default...
def overlap(args)
%prog overlap <a|a.fasta> <b|b.fasta> Check overlaps between two fasta records. The arguments can be genBank IDs instead of FASTA files. In case of IDs, the sequences will be downloaded first.
2.918242
2.857532
1.021246
p = OptionParser(certificate.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) tpffile, certificatefile = args fastadir = "fasta" tpf = TPF(tpffile) data = check_certificate(certificatefile) fw = must_open(certificatefile, "w") ...
def certificate(args)
%prog certificate tpffile certificatefile Generate certificate file for all overlaps in tpffile. tpffile can be generated by jcvi.formats.agp.tpf(). North chr1 2 0 AC229737.8 telomere 58443 South chr1 2 1 AC229737.8 AC202463.29 58443 37835 58443 + Non-terminal Each line describe...
5.966173
5.004024
1.192275
p = OptionParser(neighbor.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) agpfile, componentID = args fastadir = "fasta" cmd = "grep" cmd += " --color -C2 {0} {1}".format(componentID, agpfile) sh(cmd) agp = AGP(agpfile) ao...
def neighbor(args)
%prog neighbor agpfile componentID Check overlaps of a particular component in agpfile.
4.249483
3.751676
1.132689
from jcvi.formats.base import DictFile p = OptionParser(agp.__doc__) opts, args = p.parse_args(args) if len(args) != 3: sys.exit(not p.print_help()) tpffile, certificatefile, agpfile = args orientationguide = DictFile(tpffile, valuepos=2) cert = Certificate(certificatefile) ...
def agp(args)
%prog agp tpffile certificatefile agpfile Build agpfile from overlap certificates. Tiling Path File (tpf) is a file that lists the component and the gaps. It is a three-column file similar to below, also see jcvi.formats.agp.tpf(): telomere chr1 na AC229737.8 chr1 + AC202463.29...
4.055129
3.119316
1.300006
aLhang, aRhang = self.qstart - 1, self.asize - self.qstop bLhang, bRhang = self.sstart - 1, self.bsize - self.sstop if self.orientation == '-': bLhang, bRhang = bRhang, bLhang if self.qreverse: aLhang, aRhang = aRhang, aLhang bLhang, bRhang = ...
def get_hangs(self)
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.782713
2.294577
1.212735
print(aclr, bclr, file=sys.stderr) otype = self.otype if otype == 1: if aclr.orientation == '+': aclr.end = self.qstop else: aclr.start = self.qstart if bclr.orientation == '+': bclr.start = self.sstop ...
def update_clr(self, aclr, bclr)
Zip the two sequences together, using "left-greedy" rule ============= seqA |||| ====(===============) seqB
2.925367
2.857793
1.023646
aLhang, aRhang, bLhang, bRhang = self.get_hangs() achar = ">" bchar = "<" if self.orientation == '-' else ">" if self.qreverse: achar = "<" bchar = {">" : "<", "<" : ">"}[bchar] print(aLhang, aRhang, bLhang, bRhang, file=sys.stderr) widt...
def print_graphic(self)
>>>>>>>>>>>>>>>>>>> seqA (alen) |||||||| <<<<<<<<<<<<<<<<<<<<< seqB (blen)
3.03035
2.87799
1.05294
fw = must_open(filename, "w") for aid, bb in groupby(self.lines, key=lambda x: x.aid): bb = list(bb) north, south = bb aid = north.aid assert aid == south.aid aphase = north.aphase chr = north.chr size = north....
def write_AGP(self, filename, orientationguide={})
For each component, we have two overlaps: North and South. ======= |||| South ====(=================) Current BAC North |||| =============== For the case that says "Non-terminal", the overlap will not be con...
3.652269
3.44891
1.058963
import hashlib from jcvi.algorithms.formula import MAD_interval as confidence_interval from jcvi.graphics.base import latex, plt, savefig, set2 p = OptionParser(gcdepth.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) sample_name, tag =...
def gcdepth(args)
%prog gcdepth sample_name tag Plot GC content vs depth vs genomnic bins. Inputs are mosdepth output: - NA12878_S1.mosdepth.global.dist.txt - NA12878_S1.mosdepth.region.dist.txt - NA12878_S1.regions.bed.gz - NA12878_S1.regions.bed.gz.csi - NA12878_S1.regions.gc.bed.gz A sample mosdepth.sh s...
3.979648
3.678486
1.081871
p = OptionParser(exonunion.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) gencodebed, = args beds = BedTool(gencodebed) # fields[3] is gene_id; fields[6] is gene_name for g, gb in groupby(beds, key=lambda x: x.fields[3]): gb = ...
def exonunion(args)
%prog exonunion gencode.v26.annotation.exon.bed Collapse overlapping exons within the same gene. File `gencode.v26.annotation.exon.bed` can be generated by: $ zcat gencode.v26.annotation.gtf.gz | awk 'OFS="\t" {if ($3=="exon") {print $1,$4-1,$5,$10,$12,$14,$16,$7}}' | tr -d '";'
4.141375
4.135713
1.001369
from cyvcf2 import VCF counter = Counter() for v in VCF(vcffile): tag = v.ID.split(":")[1] counter[tag] += 1 return counter
def get_gain_loss_summary(vcffile)
Extract Canvas:GAIN/LOSS/REF/LOH tags
4.46593
4.090415
1.091804
p = OptionParser(summarycanvas.__doc__) opts, args = p.parse_args(args) if len(args) < 1: sys.exit(not p.print_help()) for vcffile in args: counter = get_gain_loss_summary(vcffile) pf = op.basename(vcffile).split(".")[0] print(pf + " " + " ".join("{}:...
def summarycanvas(args)
%prog summarycanvas output.vcf.gz Generate tag counts (GAIN/LOSS/REF/LOH) of segments in Canvas output.
3.438965
2.698456
1.274419
from cStringIO import StringIO from cyvcf2 import VCF output = StringIO() for v in VCF(vcffile): chrom = v.CHROM start = v.start end = v.INFO.get('END') - 1 cn, = v.format('CN')[0] print("\t".join(str(x) for x in (chrom, start, end, cn)), file=output) b...
def parse_segments(vcffile)
Extract all copy number segments from a CANVAS file VCF line looks like: chr1 788879 Canvas:GAIN:chr1:788880-821005 N <CNV> 2 q10 SVTYPE=CNV;END=821005;CNVLEN=32126 RC:BC:CN:MCC 157:4:3:2
3.326536
3.468098
0.959182
if not counter: return np.nan, np.nan total = sum(v for k, v in counter.items()) mid = total / 2 weighted_sum = 0 items_seen = 0 median_found = False for k, v in sorted(counter.items()): weighted_sum += k * v items_seen += v if not median_found and items...
def counter_mean_and_median(counter)
Calculate the mean and median value of a counter
2.62955
2.703175
0.972764
if not counter: return "na" return ",".join("{}:{}".format(*z) for z in sorted(counter.items()))
def counter_format(counter)
Pretty print a counter so that it appears as: "2:200,3:100,4:20"
6.383723
4.84408
1.31784
p = OptionParser(gcn.__doc__) p.set_cpus() p.set_tmpdir(tmpdir="tmp") p.set_outfile() opts, args = p.parse_args(args) if len(args) < 2: sys.exit(not p.print_help()) exonbed = args[0] canvasvcfs = args[1:] tsvfile = opts.outfile tmpdir = opts.tmpdir mkdir(tmpdi...
def gcn(args)
%prog gcn gencode.v26.exonunion.bed data/*.vcf.gz Compile gene copy njumber based on CANVAS results.
4.104642
3.329911
1.232658
canvasvcf, exonbed, i = arg logging.debug("Working on job {}: {}".format(i, canvasvcf)) samplekey = op.basename(canvasvcf).split(".")[0].rsplit('_', 1)[0] d = {'SampleKey': samplekey} exons = BedTool(exonbed) cn = parse_segments(canvasvcf) overlaps = exons.intersect(cn, wao=True) g...
def vcf_to_df_worker(arg)
Convert CANVAS vcf to a dict, single thread
3.925836
3.826679
1.025912
df = pd.DataFrame() p = Pool(processes=cpus) results = [] args = [(x, exonbed, i) for (i, x) in enumerate(canvasvcfs)] r = p.map_async(vcf_to_df_worker, args, callback=results.append) r.wait() for res in results: df = df.append(res, ignore_index=True) re...
def vcf_to_df(canvasvcfs, exonbed, cpus)
Compile a number of vcf files into tsv file for easy manipulation
2.57602
2.50829
1.027002
tsvfile += suffix columns = ["SampleKey"] + sorted(x for x in df.columns if x.endswith(suffix)) tf = df.reindex_axis(columns, axis='columns') tf.sort_values("SampleKey") tf.to_csv(tsvfile, sep='\t', index=False, float_format='%.4g', na_rep="na") print("T...
def df_to_tsv(df, tsvfile, suffix)
Serialize the dataframe as a tsv
4.37793
4.508751
0.970985
from jcvi.graphics.base import savefig p = OptionParser(coverage.__doc__) opts, args, iopts = p.set_image_options(args, format="png") if len(args) != 1: sys.exit(not p.print_help()) covfile, = args df = pd.read_csv(covfile, sep='\t', names=["Ref", "Position", "Depth"]) xlabe...
def coverage(args)
%prog coverage *.coverage Plot coverage along chromosome. The coverage file can be generated with: $ samtools depth a.bam > a.coverage The plot is a simple line plot using matplotlib.
3.109315
2.936401
1.058886
from jcvi.graphics.base import savefig p = OptionParser(plot.__doc__) opts, args, iopts = p.set_image_options(args, figsize="8x7", format="png") if len(args) != 3: sys.exit(not p.print_help()) workdir, sample_key, chrs = args chrs = chrs.split(",") hmm = CopyNumberHMM(workdir...
def plot(args)
%prog plot workdir sample chr1,chr2 Plot some chromosomes for visual proof. Separate multiple chromosomes with comma. Must contain folder workdir/sample-cn/.
3.026196
2.73249
1.107487
p = OptionParser(sweep.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) workdir, sample_key = args golden_ratio = (1 + 5 ** .5) / 2 cmd = "python -m jcvi.variation.cnv hmm {} {}".format(workdir, sample_key) cmd += " --mu {:.5f} --sigma {...
def sweep(args)
%prog sweep workdir 102340_NA12878 Write a number of commands to sweep parameter space.
2.913815
2.771933
1.051185
p = OptionParser(compare.__doc__) p.set_cpus() opts, args = p.parse_args(args) if len(args) < 2: sys.exit(not p.print_help()) truths = args[0] cnvoutputs = args[1:] cpus = min(len(cnvoutputs), opts.cpus) p = Pool(processes=cpus) results = [] files = [(x, truths) fo...
def compare(args)
%prog compare NA12878_array_hg38.bed *.seg Compare cnv output to known ground truths.
2.985197
2.29318
1.301771
p = OptionParser(cib.__doc__) p.add_option("--prefix", help="Report seqids with this prefix only") p.set_cpus() opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) bamfile, samplekey = args mkdir(samplekey) bam = pysam.AlignmentFile(bamfile, "rb...
def cib(args)
%prog cib bamfile samplekey Convert BAM to CIB (a binary storage of int8 per base).
2.92452
2.636563
1.109217
p = OptionParser(batchcn.__doc__) p.add_option("--upload", default="s3://hli-mv-data-science/htang/ccn", help="Upload cn and seg results to s3") opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) workdir, samples = args upload = opts.u...
def batchcn(args)
%prog batchcn workdir samples.csv Run CNV segmentation caller in batch mode. Scans a workdir.
5.836182
5.249154
1.111833
p = OptionParser(hmm.__doc__) p.add_option("--mu", default=.003, type="float", help="Transition probability") p.add_option("--sigma", default=.1, type="float", help="Standard deviation of Gaussian emission distribution") p.add_option("--threshold", default=1, type=...
def hmm(args)
%prog hmm workdir sample_key Run CNV segmentation caller. The workdir must contain a subfolder called `sample_key-cn` that contains CN for each chromosome. A `beta` directory that contains scaler for each bin must also be present in the current directory.
3.635883
3.482521
1.044038
p = OptionParser(batchccn.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) csvfile, = args mm = MakeManager() pf = op.basename(csvfile).split(".")[0] mkdir(pf) header = next(open(csvfile)) header = None if header.strip().endswit...
def batchccn(args)
%prog batchccn test.csv Run CCN script in batch. Write makefile.
4.21366
4.039148
1.043205
p = OptionParser(mergecn.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) csvfile, = args samples = [x.replace("-cn", "").strip().strip("/") for x in open(csvfile)] betadir = "beta" mkdir(betadir) for seqid in allsomes: names...
def mergecn(args)
%prog mergecn FACE.csv Compile matrix of GC-corrected copy numbers. Place a bunch of folders in csv file. Each folder will be scanned, one chromosomes after another.
3.38746
3.30226
1.025801
# We need a way to go from compressed idices to original indices P = Z.copy() P[~np.isfinite(P)] = -1 _, mapping = np.unique(np.cumsum(P >= 0), return_index=True) dZ = Z.compressed() uniq, idx = np.unique(dZ, return_inverse=True) segments = [] fo...
def annotate_segments(self, Z)
Report the copy number and start-end segment
5.387792
5.424419
0.993248
if len(args) != 0: sys.exit(not p.print_help()) s = InstanceSkeleton() print("IP address:", s.private_ip_address, file=sys.stderr) print("Instance type:", s.instance_type, file=sys.stderr)
def ip(args)
%prog describe Show current IP address from JSON settings.
4.626322
4.821877
0.959444
p = OptionParser(start.__doc__) p.add_option("--ondemand", default=False, action="store_true", help="Do we want a more expensive on-demand instance") p.add_option("--profile", default="mvrad-datasci-role", help="Profile name") p.add_option("--price", default=4.0, type=float, help="...
def start(args)
%prog start Launch ec2 instance through command line.
2.33479
2.290347
1.019405
p = OptionParser(stop.__doc__) p.add_option("--profile", default="mvrad-datasci-role", help="Profile name") opts, args = p.parse_args(args) if len(args) != 0: sys.exit(not p.print_help()) role(["htang"]) session = boto3.Session(profile_name=opts.profile) client = session.clien...
def stop(args)
%prog stop Stop EC2 instance.
2.482464
2.418664
1.026378
p = OptionParser(rm.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) store, = args contents = glob_s3(store) for c in contents: rm_s3(c)
def rm(args)
%prog rm "s3://hli-mv-data-science/htang/str/*.csv" Remove a bunch of files.
3.196016
2.991917
1.068217
p = OptionParser(cp.__doc__) p.add_option("--force", default=False, action="store_true", help="Force overwrite if exists") p.set_cpus() opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) store, folder = args force = opts.force ...
def cp(args)
%prog cp "s3://hli-mv-data-science/htang/str/*.csv" . Copy files to folder. Accepts list of s3 addresses as input.
2.815552
2.672009
1.053721
p = OptionParser(ls.__doc__) p.add_option("--keys", help="List of keys to include") p.add_option("--recursive", default=False, action="store_true", help="Recursive search") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) store, = ar...
def ls(args)
%prog ls "s3://hli-mv-data-science/htang/str/*.vcf.gz" List files with support for wildcards.
3.102038
3.058249
1.014318
src_acct, src_username, dst_acct, dst_role = \ "205134639408 htang 114692162163 mvrad-datasci-role".split() p = OptionParser(role.__doc__) p.add_option("--profile", default="mvrad-datasci-role", help="Profile name") p.add_option('--device', default="arn:aws:iam::" + src...
def role(args)
%prog role htang Change aws role.
4.065366
3.827301
1.062202
p = OptionParser(query.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) locifile, contig = args idx = build_index(locifile) pos = idx[contig] logging.debug("Contig {0} found at pos {1}".format(contig, pos)) fp = open(locifile) fp...
def query(args)
%prog query out.loci contig Random access to loci file. This script helps speeding up debugging.
3.10677
2.718747
1.142721
from jcvi.assembly.geneticmap import bed as geneticmap_bed from jcvi.apps.align import blat from jcvi.formats.blast import bed as blast_bed, best p = OptionParser(synteny.__doc__) opts, args = p.parse_args(args) if len(args) != 3: sys.exit(not p.print_help()) mstmapout, novo,...
def synteny(args)
%prog synteny mstmap.out novo.final.fasta reference.fasta Plot MSTmap against reference genome.
3.214167
2.963747
1.084494
from jcvi.assembly.geneticmap import MSTMatrix p = OptionParser(mstmap.__doc__) p.add_option("--population_type", default="RIL6", help="Type of population, possible values are DH and RILd") p.add_option("--missing_threshold", default=.5, help="Missing threshold, ....
def mstmap(args)
%prog mstmap LMD50.snps.genotype.txt Convert LMDs to MSTMAP input.
4.208921
3.856867
1.09128
import numpy as np from jcvi.utils.progressbar import ProgressBar, Percentage, Bar, ETA p = OptionParser(weblogo.__doc__) p.add_option("-N", default=10, type="int", help="Count the first and last N bases") p.add_option("--nreads", default=1000000, type="int", ...
def weblogo(args)
%prog weblogo [fastafile|fastqfile] Extract base composition for reads
2.469165
2.417541
1.021354
from jcvi.graphics.histogram import stem_leaf_plot from jcvi.utils.cbook import SummaryStats p = OptionParser(count.__doc__) p.add_option("--csv", help="Write depth per contig to file") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) fastafile,...
def count(args)
%prog count cdhit.consensus.fasta Scan the headers for the consensus clusters and count the number of reads.
4.316698
4.190223
1.030183
from jcvi.assembly.kmer import jellyfish, histogram from jcvi.assembly.preprocess import diginorm from jcvi.formats.fasta import filter as fasta_filter, format from jcvi.apps.cdhit import filter as cdhit_filter p = OptionParser(novo.__doc__) p.add_option("--technology", choices=("illumina"...
def novo(args)
%prog novo reads.fastq Reference-free tGBS pipeline v1.
3.297657
3.249632
1.014779
p = OptionParser(novo2.__doc__) p.set_fastq_names() p.set_align(pctid=95) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) trimmed, pf = args pctid = opts.pctid reads, samples = scan_read_files(trimmed, opts.names) # Set up directory str...
def novo2(args)
%prog novo2 trimmed projectname Reference-free tGBS pipeline v2.
2.746471
2.677045
1.025934
p = OptionParser(snpplot.__doc__) opts, args, iopts = p.set_image_options(args, format="png") if len(args) != 1: sys.exit(not p.print_help()) datafile, = args # Read in CDT file fp = open(datafile) next(fp) next(fp) data = [] for row in fp: atoms = row.spli...
def snpplot(args)
%prog counts.cdt Illustrate the histogram per SNP site.
2.937291
2.811296
1.044817
p = OptionParser(filterm4.__doc__) p.add_option("--best", default=1, type="int", help="Only retain best N hits") p.set_outfile() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) m4file, = args best = opts.best fp = open(m4file) fw = must_...
def filterm4(args)
%prog filterm4 sample.m4 > filtered.m4 Filter .m4 file after blasr is run. As blasr takes a long time to run, changing -bestn is undesirable. This screens the m4 file to retain top hits.
2.586433
2.474248
1.045341
import json p = OptionParser(spancount.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) fof, = args fp = open(fof) flist = [row.strip() for row in fp] spanCount = "spanCount" avgSpanBases = "avgSpanBases" fw = open(spanCount...
def spancount(args)
%prog spancount list_of_fillingMetrics Count span support for each gap. A file with paths of all fillingMetrics can be built with Linux `find`. $ (find assembly -name "fillingMetrics.json" -print > list_of_fillMetrics 2> /dev/null &)
3.132198
2.988448
1.048102
from jcvi.formats.base import write_file from jcvi.formats.fasta import format p = OptionParser(patch.__doc__) p.add_option("--cleanfasta", default=False, action="store_true", help="Clean FASTA to remove description [default: %default]") p.add_option("--highqual", default=Fals...
def patch(args)
%prog patch reference.fasta reads.fasta Run PBJelly with reference and reads.
3.633767
3.456843
1.051181
p = OptionParser(prepare.__doc__ + FastqNamings) p.add_option("-K", default=51, type="int", help="K-mer size") p.set_cpus(cpus=32) opts, args = p.parse_args(args) if len(args) < 2: sys.exit(not p.print_help()) genomesize = float(args[0]) / 1000 fnames = args[1:] for x in f...
def prepare(args)
%prog prepare genomesize *.fastq Prepare MERACULOUS configuation file. Genome size should be entered in Mb.
4.636864
4.170582
1.111803
from jcvi.apps.fetch import batch_taxonomy list_of_taxids = [str(x) for x in list_of_taxids] return list(batch_taxonomy(list_of_taxids))
def get_names(list_of_taxids)
>>> mylist = [3702, 3649, 3694, 3880] >>> get_names(mylist) ['Arabidopsis thaliana', 'Carica papaya', 'Populus trichocarpa', 'Medicago truncatula']
4.343782
4.754012
0.913709
from jcvi.apps.fetch import batch_taxids return [int(x) for x in batch_taxids(list_of_names)]
def get_taxids(list_of_names)
>>> mylist = ['Arabidopsis thaliana', 'Carica papaya'] >>> get_taxids(mylist) [1, 2]
6.228539
6.724813
0.926203
from ete2 import Tree t = TaxIDTree(list_of_taxids) t = Tree(str(t), format=8) ancestor = t.get_common_ancestor(*t.get_leaves()) return ancestor.name
def MRCA(list_of_taxids)
This gets the most recent common ancester (MRCA) for a list of taxids >>> mylist = [3702, 3649, 3694, 3880] >>> MRCA(mylist) 'rosids'
4.877177
6.150789
0.792935
assert isinstance(taxid, int) t = TaxIDTree(taxid) try: return "Viridiplantae" in str(t) except AttributeError: raise ValueError("{0} is not a valid ID".format(taxid))
def isPlantOrigin(taxid)
Given a taxid, this gets the expanded tree which can then be checked to see if the organism is a plant or not >>> isPlantOrigin(29760) True
5.456123
5.706039
0.956201
p = OptionParser(newick.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) idsfile, = args mylist = [x.strip() for x in open(idsfile) if x.strip()] print(get_taxids(mylist)) t = TaxIDTree(mylist) print(t)
def newick(args)
%prog newick idslist Query a list of IDs to retrieve phylogeny.
3.213061
2.892598
1.110787
pf = op.basename(bedfile).split(".")[0] minibamfile = minibam or op.basename(bamfile).replace(".bam", ".{}.bam".format(pf)) minisamfile = minibam.replace(".bam", ".sam") baifile = minibamfile + ".bai" if op.exists(baifile): sh("rm {}".format(baifile)) cmd = "samtools view -H {} > {...
def get_minibam_bed(bamfile, bedfile, minibam=None)
samtools view -L could do the work, but it is NOT random access. Here we are processing multiple regions sequentially. See also: https://www.biostars.org/p/49306/
3.010196
3.125143
0.963219
p = OptionParser(fastq.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) bamfile, pf = args singletons = pf + ".se.fastq" a = pf + ".read1.fastq" b = pf + ".read2.fastq" cmd = "samtools collate -uOn 128 {} tmp-prefix".format(bamfile...
def fastq(args)
%prog fastq bamfile prefix Convert BAM files to paired FASTQ files.
4.154544
3.969392
1.046645
p = OptionParser(mini.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) bamfile, region = args get_minibam(bamfile, region)
def mini(args)
%prog mini bamfile region Extract mini-bam for a single region.
2.866166
2.009571
1.426258
p = OptionParser(noclip.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) bamfile, = args noclipbam = bamfile.replace(".bam", ".noclip.bam") cmd = "samtools view -h {} | awk -F '\t' '($6 !~ /H|S/)'".format(bamfile) cmd += " | samtools vie...
def noclip(args)
%prog noclip bamfile Remove clipped reads from BAM.
2.648163
2.466251
1.07376
p = OptionParser(append.__doc__) p.add_option("--prepend", help="Prepend string to read names") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) bamfile, = args prepend = opts.prepend icmd = "samtools view -h {0}".format(bamfile) bamfile = b...
def append(args)
%prog append bamfile Append /1 or /2 to read names. Useful for using the Tophat2 bam file for training AUGUSTUS gene models.
2.759181
2.551936
1.081211
p = OptionParser(bed.__doc__) opts, args = p.parse_args(args) if len(args) < 2: sys.exit(not p.print_help()) bedfile = args[0] bamfiles = args[1:] for bamfile in bamfiles: cmd = "bamToBed -i {0}".format(bamfile) sh(cmd, outfile=bedfile, append=True)
def bed(args)
%prog bed bedfile bamfiles Convert bam files to bed.
2.48405
2.17779
1.140629
from jcvi.apps.grid import MakeManager p = OptionParser(merge.__doc__) p.set_sep(sep="_", help="Separator to group per prefix") opts, args = p.parse_args(args) if len(args) < 2: sys.exit(not p.print_help()) merged_bams = args[0] bamdirs = args[1:] mkdir(merged_bams) ...
def merge(args)
%prog merge merged_bams bams1_dir bams2_dir ... Merge BAM files. Treat the bams with the same prefix as a set. Output the commands first.
2.943633
2.713904
1.084649
p = OptionParser(count.__doc__) p.add_option("--type", default="exon", help="Only count feature type") p.set_cpus(cpus=8) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) bamfile, gtf = args cpus = opts.cpus pf = bamfile.spli...
def count(args)
%prog count bamfile gtf Count the number of reads mapped using `htseq-count`.
2.699282
2.489758
1.084154
p = OptionParser(coverage.__doc__) p.add_option("--format", default="bigwig", choices=("bedgraph", "bigwig", "coverage"), help="Output format") p.add_option("--nosort", default=False, action="store_true", help="Do not sort BAM") p.set_outfile() ...
def coverage(args)
%prog coverage fastafile bamfile Calculate coverage for BAM file. BAM file will be sorted unless with --nosort.
2.754091
2.551785
1.07928
p = OptionParser(fpkm.__doc__) opts, args = p.parse_args(args) if len(args) < 2: sys.exit(not p.print_help()) fastafile = args[0] bamfiles = args[1:] # Create a DUMMY gff file for cuffdiff gffile = fastafile.rsplit(".", 1)[0] + ".gff" if need_update(fastafile, gffile): ...
def fpkm(args)
%prog fpkm fastafile *.bam Calculate FPKM values from BAM file.
3.197411
3.005013
1.064026
import jcvi.formats.bed p = OptionParser(pairs.__doc__) p.set_pairs() opts, targs = p.parse_args(args) if len(targs) != 1: sys.exit(not p.print_help()) samfile, = targs bedfile = samfile.rsplit(".", 1)[0] + ".bed" if need_update(samfile, bedfile): cmd = "bamToBed ...
def pairs(args)
See __doc__ for OptionParser.set_pairs().
3.201763
2.990763
1.070551
p = OptionParser(consensus.__doc__) p.add_option("--fasta", default=False, action="store_true", help="Generate consensus FASTA sequences [default: %default]") p.add_option("--mask", default=0, type="int", help="Mask bases with quality lower than") opts, args = p.parse_args(a...
def consensus(args)
%prog consensus fastafile bamfile Convert bam alignments to consensus FASTQ/FASTA.
3.445184
3.160402
1.09011
from jcvi.apps.grid import Jobs valid_callers = ("mpileup", "freebayes") p = OptionParser(vcf.__doc__) p.set_outfile(outfile="out.vcf.gz") p.add_option("--nosort", default=False, action="store_true", help="Do not sort the BAM files") p.add_option("--caller", default="mpile...
def vcf(args)
%prog vcf fastafile bamfiles > out.vcf.gz Call SNPs on bam files.
2.538849
2.377097
1.068046
import pysam from jcvi.utils.natsort import natsorted p = OptionParser(chimera.__doc__) p.set_verbose() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) samfile, = args samfile = pysam.AlignmentFile(samfile) rstore = defaultdict(list) ...
def chimera(args)
%prog chimera bamfile Parse BAM file from `bwasw` and list multi-hit reads and breakpoints.
2.972091
2.838223
1.047166
p = OptionParser(index.__doc__) p.add_option("--fasta", dest="fasta", default=None, help="add @SQ header to the BAM file [default: %default]") p.add_option("--unique", default=False, action="store_true", help="only retain uniquely mapped reads [default: %default]") p.set_cpu...
def index(args)
%prog index samfile/bamfile If SAM file, convert to BAM, sort and then index, using SAMTOOLS
2.178547
2.106593
1.034157
import pysam from jcvi.apps.grid import Jobs p = OptionParser(mapped.__doc__) p.set_sam_options(extra=False) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(p.print_help()) samfile, = args view_opts = [] oext, mopts = (".sam", ["-S"]) \ if sam...
def mapped(args)
%prog mapped sam/bamfile Given an input sam/bam file, output a sam/bam file containing only the mapped reads. Optionally, extract the unmapped reads into a separate file
3.412084
3.344686
1.020151
p = OptionParser(pair.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(p.print_help()) def callback(s): print(s.pairline) Sam(args[0], callback=callback)
def pair(args)
%prog pair samfile Parses the sam file and retrieve in pairs format, query:pos ref:pos
3.742981
3.943785
0.949083
seq, cigar = a.seq, a.cigar start = 0 subseqs = [] npadded = 0 if cigar is None: return None, npadded for operation, length in cigar: end = start if operation == 2 else start + length if operation == 0: # match subseq = seq[start:end] elif oper...
def cigar_to_seq(a, gap='*')
Accepts a pysam row. cigar alignment is presented as a list of tuples (operation,length). For example, the tuple [ (0,3), (1,5), (0,2) ] refers to an alignment with 3 matches, 5 insertions and another 2 matches. Op BAM Description M 0 alignment match (can be a sequence match or mismatch) I 1 i...
2.593589
2.645809
0.980263
p = OptionParser(dump.__doc__) p.add_option("--dir", help="Working directory [default: %default]") p.add_option("--nosim", default=False, action="store_true", help="Do not simulate qual to 50 [default: %default]") opts, args = p.parse_args(args) if len(args) !=...
def dump(args)
%prog dump fastbfile Export ALLPATHS fastb file to fastq file. Use --dir to indicate a previously run allpaths folder.
3.979665
3.703243
1.074643
p = OptionParser(fixpairs.__doc__) opts, args = p.parse_args(args) if len(args) != 3: sys.exit(not p.print_help()) pairsfile, sep, sd = args newpairsfile = pairsfile.rsplit(".", 1)[0] + ".new.pairs" sep = int(sep) sd = int(sd) p = PairsFile(pairsfile) p.fixLibraryStat...
def fixpairs(args)
%prog fixpairs pairsfile sep sd Fix pairs library stats. This is sometime useful to modify library stats, for example, the separation between paired reads after importing the data.
2.830066
2.018937
1.40176
p = OptionParser(fill.__doc__) p.add_option("--stretch", default=3, type="int", help="MAX_STRETCH to pass to FillFragments [default: %default]") p.set_cpus() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) fastb, = args assert ...
def fill(args)
%prog fill frag_reads_corr.fastb Run FillFragments on `frag_reads_corr.fastb`.
4.327679
3.523796
1.22813
fp = open(fastqfile) currentID = 0 npairs = nfrags = 0 for x, lib in izip(p.r1, p.libs): while currentID != x: fragsfw.writelines(islice(fp, 4)) # Exhaust the iterator currentID += 1 nfrags += 1 a = list(islice(fp, 4)) b = list(islice(fp,...
def extract_pairs(fastqfile, p1fw, p2fw, fragsfw, p, suffix=False)
Take fastqfile and array of pair ID, extract adjacent pairs to outfile. Perform check on numbers when done. p1fw, p2fw is a list of file handles, each for one end. p is a Pairs instance.
3.009779
2.886416
1.042739
from jcvi.assembly.preprocess import run_FastbAndQualb2Fastq p = OptionParser(pairs.__doc__) p.add_option("--header", default=False, action="store_true", help="Print header only [default: %default]") p.add_option("--suffix", default=False, action="store_true", help="Ad...
def pairs(args)
%prog pairs pairsfile <fastbfile|fastqfile> Parse ALLPATHS pairs file, and write pairs IDs and single read IDs in respective ids files: e.g. `lib1.pairs.fastq`, `lib2.pairs.fastq`, and single `frags.fastq` (with single reads from lib1/2).
3.058682
2.720573
1.124279
from jcvi.algorithms.graph import nx, topological_sort p = OptionParser(log.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) g = nx.DiGraph() logfile, = args fp = open(logfile) row = fp.readline() incalling = False basedb =...
def log(args)
%prog log logfile Prepare a log of created files, ordered by their creation data. The purpose for this script is to touch these files sequentially to reflect their build order. On the JCVI scratch area, the files are touched regularly to avoid getting deleted, losing their respective timestamps. Howeve...
3.025777
2.861281
1.05749
mapping = self._mapping set_a = mapping.setdefault(a, [a]) for arg in args: set_b = mapping.get(arg) if set_b is None: set_a.append(arg) mapping[arg] = set_a elif set_b is not set_a: if len(set_b) > len...
def join(self, a, *args)
Join given arguments into the same set. Accepts one or more arguments.
2.136494
2.066672
1.033785
mapping = self._mapping try: return mapping[a] is mapping[b] except KeyError: return False
def joined(self, a, b)
Returns True if a and b are members of the same set.
5.1512
4.301717
1.197475
from csv import reader from xlwt import Workbook, easyxf from jcvi.formats.base import flexible_cast p = OptionParser(fromcsv.__doc__) p.add_option("--noheader", default=False, action="store_true", help="Do not treat the first row as header") p.add_option("--rgb", default=...
def fromcsv(args)
%prog fromcsv csvfile Convert csv file to EXCEL.
2.425553
2.346614
1.033639
from xlrd import open_workbook p = OptionParser(csv.__doc__) p.set_sep(sep=',') opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) excelfile, = args sep = opts.sep csvfile = excelfile.rsplit(".", 1)[0] + ".csv" wb = open_workbook(excelfile...
def csv(args)
%prog csv excelfile Convert EXCEL to csv file.
2.162119
1.981444
1.091184
from jcvi.utils.webcolors import color_diff if isinstance(color, int): return color if color: if isinstance(color, six.string_types): rgb = map(int, color.split(',')) else: rgb = color.Get() logging.disable(...
def match_color_index(self, color)
Takes an "R,G,B" string or wx.Color and returns a matching xlwt color.
3.932989
3.219529
1.221604
if not self.unused_colors: # If we somehow run out of colors, reset the color matcher. self.reset() used_colors = [c for c in self.xlwt_colors if c not in self.unused_colors] result_color = max(self.unused_colors, key=lambda c: min(self...
def get_unused_color(self)
Returns an xlwt color index that has not been previously returned by this instance. Attempts to maximize the distance between the color and all previously used colors.
3.634894
3.011501
1.207004
import pyfasta p = OptionParser(validate.__doc__) p.add_option("--prefix", help="Add prefix to seqid") opts, args = p.parse_args(args) vcffile, fastafile = args pf = opts.prefix genome = pyfasta.Fasta(fastafile, record_class=pyfasta.MemoryRecord) fp = must_open(vcffile) match_...
def validate(args)
%prog validate input.vcf genome.fasta Fasta validation of vcf file.
3.212683
2.987828
1.075257
from six.moves.urllib.parse import parse_qs p = OptionParser(uniq.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) vcffile, = args fp = must_open(vcffile) data = [] for row in fp: if row[0] == '#': print(row.stri...
def uniq(args)
%prog uniq vcffile Retain only the first entry in vcf file.
2.859519
2.571161
1.112151
from random import random p = OptionParser(sample.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) vcffile, ratio = args ratio = float(ratio) fp = open(vcffile) pf = vcffile.rsplit(".", 1)[0] kept = pf + ".kept.vcf" withheld...
def sample(args)
%prog sample vcffile 0.9 Sample subset of vcf file.
2.277628
2.11774
1.075499
p = OptionParser(fromimpute2.__doc__) opts, args = p.parse_args(args) if len(args) != 3: sys.exit(not p.print_help()) impute2file, fastafile, chr = args fasta = Fasta(fastafile) print(get_vcfstanza(fastafile, fasta)) fp = open(impute2file) seen = set() for row in fp: ...
def fromimpute2(args)
%prog fromimpute2 impute2file fastafile 1 Convert impute2 output to vcf file. Imputed file looks like: --- 1:10177:A:AC 10177 A AC 0.451 0.547 0.002
3.936787
3.635537
1.082862
p = OptionParser(refallele.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) vcffile, = args fp = open(vcffile) for row in fp: if row[0] == '#': continue atoms = row.split() marker = "{0}:{1}".format(*atoms...
def refallele(args)
%prog refallele vcffile > out.refAllele Make refAllele file which can be used to convert PLINK file to VCF file.
2.737516
2.509386
1.090911
from jcvi.formats.bed import BedLine from jcvi.graphics.histogram import stem_leaf_plot p = OptionParser(location.__doc__) p.add_option("--dist", default=100, type="int", help="Distance cutoff to call 5` and 3` [default: %default]") opts, args = p.parse_args(args) if len(...
def location(args)
%prog location bedfile fastafile Given SNP locations, summarize the locations in the sequences. For example, find out if there are more 3`-SNPs than 5`-SNPs.
2.937487
2.825239
1.039731
atoms = s.split(":") if len(atoms) < 3: return g2x[atoms[0]] inferred = atoms[0] depth = int(atoms[depth_index]) if depth < mindepth: return '-' if inferred == '0/0': return 'A' if inferred == '0/1': return '-' if nohet else 'X' if inferred == '1/1':...
def encode_genotype(s, mindepth=3, depth_index=2, nohet=False)
>>> encode_genotype("1/1:128,18,0:6:18") # homozygote B 'B' >>> encode_genotype("0/1:0,0,0:0:3") # missing data '-' >>> encode_genotype("0/1:128,0,26:7:22") # heterozygous A/B 'X'
3.569856
3.442067
1.037126
from jcvi.assembly.geneticmap import MSTMatrix p = OptionParser(mstmap.__doc__) p.add_option("--dh", default=False, action="store_true", help="Double haploid population, no het [default: %default]") p.add_option("--freq", default=.2, type="float", help="Allele mus...
def mstmap(args)
%prog mstmap bcffile/vcffile > matrixfile Convert bcf/vcf format to mstmap input.
3.727462
3.636404
1.025041
p = OptionParser(liftover.__doc__) p.add_option("--newid", default=False, action="store_true", help="Make new identifiers") opts, args = p.parse_args(args) if len(args) != 3: sys.exit(not p.print_help()) oldvcf, chainfile, newvcf = args ul = UniqueLiftover(chainfi...
def liftover(args)
%prog liftover old.vcf hg19ToHg38.over.chain.gz new.vcf Lift over coordinates in vcf file.
2.872588
2.736664
1.049668
chromosome = str(chromosome) position = int(position) # Perform the liftover lookup, shift the position by 1 as pyliftover deals in 0-based co-ords new = self.liftover.convert_coordinate(chromosome, position - 1) # This has to be here as new will be NoneType when the c...
def liftover_cpra(self, chromosome, position, verbose=False)
Given chromosome, position in 1-based co-ordinates, This will use pyliftover to liftover a CPRA, will return a (c,p) tuple or raise NonUniqueLiftover if no unique and strand maintaining liftover is possible :param chromosome: string with the chromosome as it's represented in the from_genome ...
4.2365
4.229952
1.001548
p = OptionParser(multilineplot.__doc__) p.add_option("--lines", help="Features to plot in lineplot [default: %default]") p.add_option("--colors", help="List of colors matching number of input bed files") p.add_option("--mode", default="span", choices=("span", "coun...
def multilineplot(args)
%prog multilineplot fastafile chr1 Combine multiple line plots in one vertical stack Inputs must be BED-formatted. --lines: traditional line plots, useful for plotting feature freq
3.482716
3.383953
1.029186
p = OptionParser(stack.__doc__) p.add_option("--top", default=10, type="int", help="Draw the first N chromosomes [default: %default]") p.add_option("--stacks", default="Exons,Introns,DNA_transposons,Retrotransposons", help="Features to plot in stackplo...
def stack(args)
%prog stack fastafile Create landscape plots that show the amounts of genic sequences, and repetitive sequences along the chromosomes.
3.598276
3.525384
1.020676
from Bio.Emboss.Applications import NeedleCommandline needle_cline = NeedleCommandline(asequence=fa, bsequence=fb, gapopen=10, gapextend=0.5, outfile=needlefile) stdout, stderr = needle_cline() nh = NeedleHeader(needlefile) FileShredder([fa, fb, needlefile], verbose=Fal...
def _needle(fa, fb, needlefile, a, b, results)
Run single needle job
4.473867
4.529823
0.987647
from jcvi.formats.fasta import Fasta, SeqIO p = OptionParser(needle.__doc__) opts, args = p.parse_args(args) if len(args) != 3: sys.exit(not p.print_help()) manager = mp.Manager() results = manager.list() needle_pool = mp.Pool(processes=mp.cpu_count()) pairsfile, apep, ...
def needle(args)
%prog needle nw.pairs a.pep.fasta b.pep.fasta Take protein pairs and needle them Automatically writes output file `nw.scores`
2.380315
2.229596
1.067599
from jcvi.formats.base import SetFile, FileShredder A, T, P = "ABINITIO_PREDICTION", "TRANSCRIPT", "PROTEIN" # Stores default weights and types Registry = {\ "maker": (A, 5), "augustus_masked": (A, 1), "snap_masked": (A, 1), "genemark": (A, 1), "est2genome":...
def maker(args)
%prog maker maker.gff3 genome.fasta Prepare EVM inputs by separating tracks from MAKER.
4.634776
4.281867
1.082419
p = OptionParser(tigrload.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) db, ev_type = args runfile = "load.sh" contents = EVMLOAD.format(db, ev_type) write_file(runfile, contents)
def tigrload(args)
%prog tigrload db ev_type Load EVM results into TIGR db. Actually, just write a load.sh script. The ev_type should be set, e.g. "EVM1", "EVM2", etc.
3.745573
2.443922
1.532608
p = OptionParser(pasa.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) pasa_db, fastafile = args termexons = "pasa.terminal_exons.gff3" if need_update(fastafile, termexons): cmd = "$ANNOT_DEVEL/PASA2/scripts/pasa_asmbls_to_training_...
def pasa(args)
%prog pasa pasa_db fastafile Run EVM in TIGR-only mode.
7.071276
6.192741
1.141865