code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
from jcvi.assembly.soap import prepare logging.debug("Work on {0} ({1})".format(pf, ','.join(p))) asm = "{0}.closed.scafSeq".format(pf) if not need_update(p, asm): logging.debug("Assembly found: {0}. Skipped.".format(asm)) return slink(p, pf, tag, extra) cwd = os.getcwd()...
def soap_trios(p, pf, tag, extra)
Take one pair of reads and 'widow' reads after correction and run SOAP.
6.864745
6.688527
1.026346
p = OptionParser(soapX.__doc__) opts, args = p.parse_args(args) if len(args) < 2: sys.exit(not p.print_help()) folder, tag = args[:2] extra = args[2:] extra = [get_abs_path(x) for x in extra] tag = tag.split(",") for p, pf in iter_project(folder, n=3): soap_trios(p...
def soapX(args)
%prog soapX folder tag [*.fastq] Run SOAP on a folder of paired reads and apply tag before assembly. Optional *.fastq in the argument list will be symlinked in each folder and co-assembled.
4.510181
3.695247
1.220536
p = OptionParser(correctX.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) folder, tag = args tag = tag.split(",") for p, pf in iter_project(folder): correct_pairs(p, pf, tag)
def correctX(args)
%prog correctX folder tag Run ALLPATHS correction on a folder of paired reads and apply tag.
3.86094
2.920025
1.322228
p = OptionParser(allpathsX.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) folder, tag = args tag = tag.split(",") for p, pf in iter_project(folder): assemble_pairs(p, pf, tag)
def allpathsX(args)
%prog allpathsX folder tag Run assembly on a folder of paired reads and apply tag (PE-200, PE-500). Allow multiple tags separated by comma, e.g. PE-350,TT-1050
3.991196
3.081041
1.295405
p = OptionParser(stats.__doc__) p.set_outfile() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) folder, = args statsfiles = iglob(folder, "*.stats") after_equal = lambda x: x.split("=")[-1] header = "Library Assembled_reads Contigs".split() ...
def stats(args)
%prog stats folder Generate table summarizing .stats files.
3.521761
3.418794
1.030118
p = OptionParser(mcluster.__doc__) add_consensus_options(p) p.set_cpus() opts, args = p.parse_args(args) if len(args) < 1: sys.exit(not p.print_help()) consensusfiles = args minlength = opts.minlength cpus = opts.cpus pf = opts.prefix pctid = find_pctid(consensusfi...
def mcluster(args)
%prog mcluster *.consensus Cluster across samples using consensus sequences.
3.205901
3.124623
1.026012
p = OptionParser(mconsensus.__doc__) p.add_option("--allele_counts", default="allele_counts", help="Directory to generate allele counts") add_consensus_options(p) opts, args = p.parse_args(args) if len(args) < 1: sys.exit(not p.print_help()) consensusfiles = args ...
def mconsensus(args)
%prog mconsensus *.consensus Call consensus along the stacks from cross-sample clustering.
3.582958
3.552646
1.008532
p = OptionParser(consensus.__doc__) p.add_option("--ploidy", default=2, type="int", help="Number of haplotypes per locus") add_consensus_options(p) p.set_verbose() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) clustSfile, = ar...
def consensus(args)
%prog consensus clustSfile Call consensus along the stacks. Tabulate bases at each site, tests for errors according to error rate, calls consensus.
3.478853
3.35002
1.038458
S, nreps = zip(*S) S = np.array([list(x) for x in S]) rows, cols = S.shape counts = [] for c in xrange(cols): freq = [0] * NBASES for b, nrep in zip(S[:, c], nreps): freq[BASES.index(b)] += nrep counts.append(freq) return counts
def stack(S)
From list of bases at a site D, make counts of bases
4.259558
3.903899
1.091103
cseq = seq.strip(GAPS) leftjust = seq.index(cseq[0]) rightjust = seq.rindex(cseq[-1]) return leftjust, rightjust
def get_left_right(seq)
Find position of the first and last base
4.899249
4.555274
1.075511
C = ClustFile(f) for data in C: names, seqs, nreps = zip(*data) total_nreps = sum(nreps) # Depth filter if total_nreps < mindepth: continue S = [] for name, seq, nrep in data: # Append sequence * number of dereps S.append(...
def cons(f, mindepth)
Makes a list of lists of reads at each site
8.61644
7.891144
1.091913
C = defaultdict(int) for d in N: C[tuple(d)] += 1 return [i for i in C.items() if (0, 0, 0, 0) not in i]
def makeC(N)
Makes a dictionary with counts of base counts [x,x,x,x]:x, speeds up Likelihood calculation
4.219463
4.384814
0.96229
p = OptionParser(estimateHE.__doc__) add_consensus_options(p) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) clustSfile, = args HEfile = clustSfile.rsplit(".", 1)[0] + ".HE" if not need_update(clustSfile, HEfile): logging.debug("File `{...
def estimateHE(args)
%prog estimateHE clustSfile Estimate heterozygosity (H) and error rate (E). Idea borrowed heavily from the PyRad paper.
4.077169
3.660784
1.113742
matfile = op.join(datadir, "blosum80.mat") cmd = "poa -read_fasta - -pir stdout {0} -tolower -silent -hb -fuse_all".format(matfile) p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) s = "" for i, j in zip(names, seqs): s += "\n".join((i, j)) + "\n" r...
def alignfast(names, seqs)
Performs MUSCLE alignments on cluster and returns output as string
5.51488
5.646791
0.97664
seen = set() filtered_names, filtered_seqs = [], [] for name, seq in zip(names, seqs): samp = name.split(sep, 1)[0] if samp in seen: continue seen.add(samp) filtered_names.append(name) filtered_seqs.append(seq) nfiltered, nnames = len(filtered_na...
def filter_samples(names, seqs, sep='.')
When there are uncollapsed contigs within the same sample, only retain the first seq, or the seq that is most abundant (with cluster_size).
2.492549
2.494484
0.999224
p = OptionParser(cluster.__doc__) add_consensus_options(p) p.set_align(pctid=95) p.set_outdir() p.set_cpus() opts, args = p.parse_args(args) if len(args) < 2: sys.exit(not p.print_help()) prefix = args[0] fastqfiles = args[1:] cpus = opts.cpus pctid = opts.pcti...
def cluster(args)
%prog cluster prefix fastqfiles Use `vsearch` to remove duplicate reads. This routine is heavily influenced by PyRAD: <https://github.com/dereneaton/pyrad>.
3.203557
3.118106
1.027405
p = OptionParser(align.__doc__) p.set_cpus() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) clustfile, = args parallel_musclewrap(clustfile, opts.cpus)
def align(args)
%prog align clustfile Align clustfile to clustSfile. Useful for benchmarking aligners.
3.97606
3.353732
1.185563
ax = np.array(x) ay = np.array(y) if title: print(dark(title), file=sys.stderr) az = ay * width / ay.max() tx = [asciiaxis(x, digit=digit) for x in ax] rjust = max([len(x) for x in tx]) + 1 for x, y, z in zip(tx, ay, az): x = x.rjust(rjust) y = y or "" ...
def asciiplot(x, y, digit=1, width=50, title=None, char="=")
Print out a horizontal plot using ASCII chars. width is the textwidth (height) of the plot.
4.347342
4.389501
0.990396
fig = plt.figure() ax = fig.add_subplot(111) xmax = 20 * (len(palette) + 1) x1s = np.arange(0, xmax, 20) xintervals = [10] * len(palette) xx = zip(x1s, xintervals) ax.broken_barh(xx, (5, 10), facecolors=palette) ax.set_ylim(0, 20) ax.set_xlim(0, xmax) ax.set_axis_off() ...
def print_colors(palette, outfile="Palette.png")
print color palette (a tuple) to a PNG file for quick check
2.762453
2.736808
1.00937
import random from scipy import interpolate if usepreset: if 0 < N <= 5: cmap = cm.gist_rainbow elif N <= 20: cmap = cm.Set1 else: sys.exit(discrete_rainbow.__doc__) cdict = cmap._segmentdata.copy() # N colors colors_i = np.linsp...
def discrete_rainbow(N=7, cmap=cm.Set1, usepreset=True, shuffle=False, \ plot=False)
Return a discrete colormap and the set of colors. modified from <http://www.scipy.org/Cookbook/Matplotlib/ColormapTransformations> cmap: colormap instance, eg. cm.jet. N: Number of colors. Example >>> x = resize(arange(100), (5,100)) >>> djet = cmap_discretize(cm.jet, 5) >>> imshow(x,...
3.428185
3.527971
0.971716
tc = "gray" axt = ax.transAxes yy = .95 for msg in messages: ax.text(.95, yy, msg, color=tc, transform=axt, ha="right") yy -= .05
def write_messages(ax, messages)
Write text on canvas, usually on the top right corner.
4.923167
4.442501
1.108197
''' TODO: redundant with quickplot(), need to be refactored. ''' if percentage: total_length = sum(data.values()) data = dict((k, v * 100. / total_length) for (k, v) in data.items()) left, height = zip(*sorted(data.items())) pad = max(height) * .01 c1, c2 = "darkslategray", ...
def quickplot_ax(ax, data, xmin, xmax, xlabel, title=None, ylabel="Counts", counts=True, percentage=True, highlight=None)
TODO: redundant with quickplot(), need to be refactored.
3.137947
2.916985
1.07575
plt.figure(1, (6, 6)) left, height = zip(*sorted(data.items())) pad = max(height) * .01 if counts: for l, h in zip(left, height): if xmax and l > xmax: break plt.text(l, h + pad, str(h), color="darkslategray", size=8, ha="center",...
def quickplot(data, xmin, xmax, xlabel, title, ylabel="Counts", figname="plot.pdf", counts=True, print_stats=True)
Simple plotting function - given a dictionary of data, produce a bar plot with the counts shown on the plot.
2.888687
2.865021
1.00826
parts = au.split() first = parts[0] middle = [x for x in parts if x[-1] == '.'] middle = "".join(middle) last = [x for x in parts[1:] if x[-1] != '.'] last = " ".join(last) initials = "{0}.{1}".format(first[0], middle) if first[-1] == '.': # Some people use full middle name ...
def get_name_parts(au)
Fares Z. Najar => last, first, initials >>> get_name_parts("Fares Z. Najar") ('Najar', 'Fares', 'F.Z.')
3.601522
3.718673
0.968496
from jcvi.formats.base import read_block fp = open(lstfile) all_authors = [] for header, seq in read_block(fp, "["): seq = " ".join(seq) authors = [] for au in seq.split(","): au = au.strip() if not au: continue au = strin...
def parse_names(lstfile)
This is the alternative format `lstfile`. In this format, there are two sections, starting with [Sequence] and [Manuscript], respectively, then followed by authors separated by comma.
3.367142
3.314739
1.015809
p = OptionParser(names.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(p.print_help()) namelist, templatefile = args # First check the alternative format if open(namelist).read()[0] == '[': out = parse_names(namelist) make_template(templatefil...
def names(args)
%prog names namelist templatefile Generate name blocks from the `namelist` file. The `namelist` file is tab-delimited that contains >=4 columns of data. Three columns are mandatory. First name, middle initial and last name. First row is table header. For the extra columns, the first column will go in t...
3.867542
3.425513
1.12904
p = OptionParser(main.__doc__) p.add_option("-g", "--graphic", default=False, action="store_true", help="Create boilerplate for a graphic script") opts, args = p.parse_args() if len(args) != 1: sys.exit(not p.print_help()) script, = args imports = graphic_imports if op...
def main()
%prog scriptname.py create a minimal boilerplate for a new script
3.494385
3.375291
1.035284
sd = [ambiguous_dna_values[x] for x in s] return ["".join(x) for x in list(product(*sd))]
def unpack_ambiguous(s)
List sequences with ambiguous characters in all possibilities.
5.841689
4.912655
1.18911
p = OptionParser(split.__doc__) p.set_outdir(outdir="deconv") p.add_option("--nocheckprefix", default=False, action="store_true", help="Don't check shared prefix [default: %default]") p.add_option("--paired", default=False, action="store_true", help="Paired-end dat...
def split(args)
%prog split barcodefile fastqfile1 .. Deconvolute fastq files into subsets of fastq reads, based on the barcodes in the barcodefile, which is a two-column file like: ID01 AGTCCAG Input fastqfiles can be several files. Output files are ID01.fastq, ID02.fastq, one file per line in barcodefile. ...
3.162382
3.047901
1.03756
p = OptionParser(merge.__doc__) p.set_outdir(outdir="outdir") opts, args = p.parse_args(args) if len(args) < 1: sys.exit(not p.print_help()) folders = args outdir = opts.outdir mkdir(outdir) files = flatten(glob("{0}/*.*.fastq".format(x)) for x in folders) files = lis...
def merge(args)
%prog merge folder1 ... Consolidate split contents in the folders. The folders can be generated by the split() process and several samples may be in separate fastq files. This program merges them.
3.191673
2.864713
1.114134
_p = set() for x in p: _p |= set(range(x - tolerance, x + tolerance + 1)) return _p
def expand_alleles(p, tolerance=0)
Returns expanded allele set given the tolerance.
3.958681
3.49059
1.134101
_p1 = expand_alleles(p1, tolerance=tolerance) _p2 = expand_alleles(p2, tolerance=tolerance) possible_progenies = set(tuple(sorted(x)) for x in product(_p1, _p2)) if x_linked: # Add all hemizygotes possible_progenies |= set((x, x) for x in (set(_p1) | set(_p2))) return possible_progenie...
def get_progenies(p1, p2, x_linked=False, tolerance=0)
Returns possible progenies in a trio.
3.126399
2.886915
1.082955
p = OptionParser(mendelian_errors2.__doc__) opts, args, iopts = p.set_image_options(args, figsize="7x7", format="png") if len(args) != 1: sys.exit(not p.print_help()) csvfile, = args fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(iopts.w, iopts.h)) ro...
def mendelian_errors2(args)
%prog mendelian_errors2 Trios.summary.csv Plot Mendelian errors as calculated by mendelian(). File `Trios.summary.csv` looks like: Name,Motif,Inheritance,N_Correct,N_Error,N_missing,ErrorRate [N_Error / (N_Correct + N_Error))] DM1,CTG,AD,790,12,0,1.5% DM2,CCTG,AD,757,45,0,5.6% DRPLA,CAG,AD,791...
3.437916
3.297673
1.042528
call_to_ints = lambda x: tuple(int(_) for _ in x.split("|") if _ != ".") tp1_sex, tp1_call = tp1[:2] tp2_sex, tp2_call = tp2[:2] tpp_sex, tpp_call = tpp[:2] # tp1_evidence = sum(int(x) for x in tp1[2:]) # tp2_evidence = sum(int(x) for x in tp2[2:]) # tpp_evidence = sum(int(x) for x in t...
def mendelian_check(tp1, tp2, tpp, is_xlinked=False)
Compare TRED calls for Parent1, Parent2 and Proband.
2.425333
2.359935
1.027712
return (rname == target_chr) and \ (target_start <= rstart <= target_end)
def in_region(rname, rstart, target_chr, target_start, target_end)
Quick check if a point is within the target region.
2.752519
2.604005
1.057033
import pysam from jcvi.utils.iter import pairwise from jcvi.utils.grouper import Grouper p = OptionParser(alts.__doc__) p.set_outfile(outfile="TREDs.alts.csv") opts, args = p.parse_args(args) if len(args) < 1: sys.exit(not p.print_help()) treds = args repo = TREDsRepo...
def alts(args)
%prog alts HD Build alternative loci based on simulation data.
3.054109
3.034291
1.006531
import seaborn as sns p = OptionParser(depth.__doc__) opts, args, iopts = p.set_image_options(args, figsize="14x14") if len(args) != 1: sys.exit(not p.print_help()) tsvfile, = args fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(ncols=2, nrows=2, ...
def depth(args)
%prog depth DP.tsv Plot read depths across all TREDs.
3.201663
3.04475
1.051536
p = OptionParser(mendelian_errors.__doc__) opts, args, iopts = p.set_image_options(args, figsize="6x6") if len(args) != 1: sys.exit(not p.print_help()) csvfile, = args fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(iopts.w, iopts.h)) root = fig.add_ax...
def mendelian_errors(args)
%prog mendelian_errors STR-Mendelian-errors.csv Plot Mendelian errors as calculated by mendelian(). File `STR-Mendelian-errors.csv` looks like: ,Duos - Mendelian errors,Trios - Mendelian errors SCA36,1.40%,0.60% ULD,0.30%,1.50% BPES,0.00%,1.80% One TRED disease per line, followed by duo ...
2.710426
2.58465
1.048663
self_key = ["ChildSelf"] keys = family.keys() spouse_key = [x for x in keys if ("spouse" in x.lower())] assert len(spouse_key) <= 1 parent_keys = [x for x in keys if \ ("parent" in x.lower()) and ("grand" not in x.lower())] sib_keys = [x for x in keys if ("sibling" in x....
def extract_trios(family)
Identify all trios/duos inside a family, where a family contains dictionary of relationship: individual, for example: { "ChildSelf": "176531498", "DzTwin": "176531497", "Parent": "176449143" }
3.457097
3.008599
1.149072
df = pd.read_csv(tsvfile, sep="\t", index_col=0, dtype={"SampleKey": str}) return df
def read_tred_tsv(tsvfile)
Read the TRED table into a dataframe.
3.893492
3.781091
1.029727
p = OptionParser(mendelian.__doc__) p.add_option("--tolerance", default=0, type="int", help="Tolernace for differences") p.set_verbose() opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) triosjson, tredtsv = args verbose = opts.ve...
def mendelian(args)
%prog mendelian trios_candidate.json hli.20170424.tred.tsv Calculate Mendelian errors based on trios and duos.
2.93967
2.717172
1.081886
p = OptionParser(mini.__doc__) p.add_option("--pad", default=20000, type="int", help="Add padding to the STR reigons") p.add_option("--treds", default=None, help="Extract specific treds, use comma to separate") p.set_outfile() opts, args = p.parse_args(args) ...
def mini(args)
%prog mini bamfile minibamfile Prepare mini-BAMs that contain only the STR loci.
3.494931
2.879089
1.213902
p = OptionParser(likelihood.__doc__) opts, args, iopts = p.set_image_options(args, figsize="10x5", style="white", cmap="coolwarm") if len(args) != 0: sys.exit(not p.print_help()) fig, (ax1, ax2) = plt.subplots(ncols=2, nrows=1, ...
def likelihood(args)
%prog likelihood Plot likelihood surface. Look for two files in the current folder: - 100_100.log, haploid model - 100_20.log, diploid model
3.072207
2.815662
1.091114
from matplotlib import gridspec p = OptionParser(likelihood2.__doc__) opts, args, iopts = p.set_image_options(args, figsize="10x5", style="white", cmap="coolwarm") if len(args) != 1: sys.exit(not p.print_help()) jsonfile, = args fig = plt.figure(fi...
def likelihood2(args)
%prog likelihood2 100_20.json Plot the likelihood surface and marginal distributions.
2.750187
2.524802
1.089268
from matplotlib import gridspec p = OptionParser(likelihood3.__doc__) opts, args, iopts = p.set_image_options(args, figsize="10x10", style="white", cmap="coolwarm") if len(args) != 2: sys.exit(not p.print_help()) jsonfile1, jsonfile2 = args fig = pl...
def likelihood3(args)
%prog likelihood3 140_20.json 140_70.json Plot the likelihood surface and marginal distributions for two settings.
2.457937
2.289191
1.073714
p = OptionParser(diagram.__doc__) opts, args, iopts = p.set_image_options(args, figsize="8x4", format="png") if len(args) != 0: sys.exit(not p.print_help()) fig = plt.figure(1, (iopts.w, iopts.h)) root = fig.add_axes([0, 0, 1, 1]) # Gauge on top, this is log-scale yy = .7 ...
def diagram(args)
%prog diagram Plot the predictive power of various evidences.
3.933568
3.89674
1.009451
p = OptionParser(allelefreqall.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) reportfile, = args treds, df = read_treds(reportfile) # Prepare 5 pages, each page with 6 distributions treds = sorted(treds) count = 6 pdfs = [] ...
def allelefreqall(args)
%prog allelefreqall HN_Platinum_Gold.20180525.tsv.report.txt Plot all 30 STR allele frequencies.
4.114099
4.084572
1.007229
p = OptionParser(allelefreq.__doc__) p.add_option("--nopanels", default=False, action="store_true", help="No panel labels A, B, ...") p.add_option("--usereport", help="Use allele frequency in report file") opts, args, iopts = p.set_image_options(args, figsize="9x13") if len(ar...
def allelefreq(args)
%prog allelefreq HD,DM1,SCA1,SCA17,FXTAS,FRAXE Plot the allele frequencies of some STRs.
2.65593
2.625992
1.011401
p = OptionParser(simulate.__doc__) p.add_option("--method", choices=("wgsim", "eagle"), default="eagle", help="Read simulator") p.add_option("--ref", default="hg38", choices=("hg38", "hg19"), help="Reference genome version") p.add_option("--tred", default="HD", hel...
def simulate(args)
%prog simulate run_dir 1 300 Simulate BAMs with varying inserts with dwgsim. The above command will simulate between 1 to 300 CAGs in the HD region, in a directory called `run_dir`.
3.401989
3.316764
1.025695
p = OptionParser(mergebam.__doc__) p.set_cpus() opts, args = p.parse_args(args) if len(args) not in (2, 3): sys.exit(not p.print_help()) if len(args) == 2: idir1, outdir = args dir1 = [idir1] if idir1.endswith(".bam") else iglob(idir1, "*.bam") logging.debug("H...
def mergebam(args)
%prog mergebam dir1 homo_outdir or %prog mergebam dir1 dir2/20.bam het_outdir Merge sets of BAMs to make diploid. Two modes: - Homozygous mode: pair-up the bams in the two folders and merge - Heterozygous mode: pair the bams in first folder with a particular bam
2.362583
2.285603
1.033681
p = OptionParser(batchlobstr.__doc__) p.add_option("--haploid", default="chrY,chrM", help="Use haploid model for these chromosomes") p.set_cpus() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) bamlist, = args cmd = "python -m j...
def batchlobstr(args)
%prog batchlobstr bamlist Run lobSTR on a list of BAMs. The corresponding batch command for TREDPARSE: $ tred.py bamlist --haploid chr4 --workdir tredparse_results
3.976732
3.606621
1.10262
from jcvi.variation.str import LobSTRvcf p = OptionParser(compilevcf.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) folder, = args vcf_files = iglob(folder, "*.vcf,*.vcf.gz") for vcf_file in vcf_files: try: p = Lob...
def compilevcf(args)
%prog compilevcf dir Compile vcf outputs into lists.
4.953265
4.859082
1.019383
p = OptionParser(evidences.__doc__) p.add_option("--csv", default="hli.20170328.tred.tsv", help="TRED csv output to plot") opts, args, iopts = p.set_image_options(args, format="pdf") if len(args) != 0: sys.exit(not p.print_help()) format = iopts.format # Extract ...
def evidences(args)
%prog evidences Plot distribution of evidences against two factors: - Sample mean coverage - Longer allele
2.590734
2.572255
1.007184
import seaborn as sns sns.set_context('talk') plt.clf() register = {"MeanCoverage": "Sample Mean Coverage", "HD.FDP": "Depth of full spanning reads", "HD.PDP": "Depth of partial spanning reads", "HD.PEDP": "Depth of paired-end reads", ...
def draw_jointplot(figname, x, y, data=None, kind="reg", color=None, xlim=None, ylim=None, format="pdf")
Wraps around sns.jointplot
4.202741
4.260574
0.986426
a, b = s.split("|") ai, aj = a.split("-") bi, bj = b.split("-") los = [int(ai), int(bi)] his = [int(aj), int(bj)] if exclude and exclude in los: los.remove(exclude) if exclude and exclude in his: his.remove(exclude) return max(los), max(his)
def get_lo_hi_from_CI(s, exclude=None)
Parse the confidence interval from CI. >>> get_lo_hi_from_CI("20-20/40-60") (40, 60)
2.461694
2.867074
0.858608
p = OptionParser(compare.__doc__) opts, args, iopts = p.set_image_options(args, figsize="10x10") if len(args) != 1: sys.exit(not p.print_help()) datafile, = args pf = datafile.rsplit(".", 1)[0] fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(ncols=2, nrows=2, ...
def compare(args)
%prog compare Evaluation.csv Compare performances of various variant callers on simulated STR datasets.
3.800547
3.429311
1.108254
p = OptionParser(compare2.__doc__) p.add_option('--maxinsert', default=300, type="int", help="Maximum number of repeats") add_simulate_options(p) opts, args, iopts = p.set_image_options(args, figsize="10x5") if len(args) != 0: sys.exit(not p.print_help()) depth = ...
def compare2(args)
%prog compare2 Compare performances of various variant callers on simulated STR datasets.
2.679372
2.579708
1.038634
p = OptionParser(power.__doc__) p.add_option('--maxinsert', default=300, type="int", help="Maximum number of repeats") add_simulate_options(p) opts, args, iopts = p.set_image_options(args, figsize="10x10", format="png") if len(args) != 0: sys.exit(not p.print_help()) ...
def power(args)
%prog power Compare performances of various variant callers on simulated STR datasets. This compares the power of various evidence types.
2.410269
2.356353
1.022881
p = OptionParser(tredparse.__doc__) p.add_option('--maxinsert', default=300, type="int", help="Maximum number of repeats") add_simulate_options(p) opts, args, iopts = p.set_image_options(args, figsize="10x10") if len(args) != 0: sys.exit(not p.print_help()) depth ...
def tredparse(args)
%prog tredparse Compare performances of various variant callers on simulated STR datasets. Adds coverage comparisons as panel C and D.
1.910129
1.86906
1.021973
from jcvi.utils.cbook import percentage if summary: unique = len(data) total = sum(data) # Print out a distribution print("Unique: {0}".format(percentage(unique, total)), file=sys.stderr) bins = defaultdict(int) for d in data: logd = int(log(d, base)) ...
def loghistogram(data, base=2, ascii=True, title="Counts", summary=False)
bins is a dictionary with key: log(x, base), value: counts.
3.783378
3.657698
1.03436
''' Generate stem and leaf plot given a collection of numbers ''' assert bins > 0 range = vmax - vmin step = range * 1. / bins if isinstance(range, int): step = int(ceil(step)) step = step or 1 bins = np.arange(vmin, vmax + step, step) hist, bin_edges = np.histogram(dat...
def stem_leaf_plot(data, vmin, vmax, bins, digit=1, title=None)
Generate stem and leaf plot given a collection of numbers
4.550087
3.976255
1.144315
if ascii: return texthistogram([numberfile], vmin, vmax, title=title, bins=bins, skip=skip, col=col, base=base) data, vmin, vmax = get_data(numberfile, vmin, vmax, skip=skip, col=col) outfile = numberfile + ".base{0}.{1}".format(base, outfmt) \ if base else numb...
def histogram(numberfile, vmin, vmax, xlabel, title, outfmt="pdf", bins=50, skip=0, col=0, ascii=False, base=0, fill="white")
Generate histogram using number from numberfile, and only numbers in the range of (vmin, vmax)
4.436201
4.62039
0.960136
if ascii: return texthistogram(numberfiles, vmin, vmax, title=title, bins=bins, skip=skip) newfile = "_".join(op.basename(x).split(".")[0] for x in numberfiles) fw = open(newfile, "w") print("{0}\tgrp".format(xlabel), file=fw) if tags: tags = tags.split(",") ...
def histogram_multiple(numberfiles, vmin, vmax, xlabel, title, outfmt="pdf", tags=None, bins=20, skip=0, ascii=False, facet=False, fill="white", prefix="")
Generate histogram using number from numberfile, and only numbers in the range of (vmin, vmax). First combining multiple files.
3.785789
3.727287
1.015696
allowed_format = ("emf", "eps", "pdf", "png", "ps", \ "raw", "rgba", "svg", "svgz") p = OptionParser(main.__doc__) p.add_option("--skip", default=0, type="int", help="skip the first several lines [default: %default]") p.add_option("--col", default=0, type="int", he...
def main()
%prog numbers1.txt number2.txt ... Print histogram of the data files. The data files contain one number per line. If more than one file is inputted, the program will combine the histograms into the same plot.
3.243381
3.203633
1.012407
tlx, brx = [canvas2px(x, w, dpi) for x in (tlx, brx)] tly, bry = [canvas2px(y, h, dpi) for y in (tly, bry)] chr, bac_list = chr.split(':') return '<area shape="rect" coords="' + \ ",".join(str(x) for x in (tlx, tly, brx, bry)) \ + '" href="#' + chr + '"' \ + ' title...
def write_ImageMapLine(tlx, tly, brx, bry, w, h, dpi, chr, segment_start, segment_end)
Write out an image map area line with the coordinates passed to this function <area shape="rect" coords="tlx,tly,brx,bry" href="#chr7" title="chr7:100001..500001">
2.795164
2.469708
1.131779
p = OptionParser(batch.__doc__) set_align_options(p) p.set_sam_options() opts, args = p.parse_args(args) if len(args) != 3: sys.exit(not p.print_help()) ref_fasta, proj_dir, outdir = args outdir = outdir.rstrip("/") s3dir = None if outdir.startswith("s3://"): s...
def batch(args)
%proj batch database.fasta project_dir output_dir Run bwa in batch mode.
3.554724
3.451203
1.029995
p = OptionParser(index.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) dbfile, = args check_index(dbfile)
def index(args)
%prog index database.fasta Wrapper for `bwa index`. Same interface.
2.642164
2.345026
1.12671
p.add_option("--bwa", default="bwa", help="Run bwa at this path") p.add_option("--rg", help="Read group") p.add_option("--readtype", choices=("pacbio", "pbread", "ont2d", "intractg"), help="Read type in bwa-mem") p.set_cutoff(cutoff=800)
def set_align_options(p)
Used in align() and batch()
7.068439
6.908607
1.023135
valid_modes = ("bwasw", "aln", "mem") p = OptionParser(align.__doc__) p.add_option("--mode", default="mem", choices=valid_modes, help="BWA mode") set_align_options(p) p.set_sam_options() opts, args = p.parse_args(args) mode = opts.mode nargs = len(args) if nargs not in (2, 3):...
def align(args)
%prog align database.fasta read1.fq [read2.fq] Wrapper for three modes of BWA - mem (default), aln, bwasw (long reads).
4.495648
4.058228
1.107786
dbfile, readfile = args dbfile = check_index(dbfile) saifile = check_aln(dbfile, readfile, cpus=opts.cpus) samfile, _, unmapped = get_samfile(readfile, dbfile, bam=opts.bam, unmapped=opts.unmapped) if not need_update((dbfile, saifile), samfile): l...
def samse(args, opts)
%prog samse database.fasta short_read.fastq Wrapper for `bwa samse`. Output will be short_read.sam.
5.516506
5.280905
1.044614
dbfile, read1file, read2file = args dbfile = check_index(dbfile) sai1file = check_aln(dbfile, read1file, cpus=opts.cpus) sai2file = check_aln(dbfile, read2file, cpus=opts.cpus) samfile, _, unmapped = get_samfile(read1file, dbfile, bam=opts.bam, unmapped=o...
def sampe(args, opts)
%prog sampe database.fasta read1.fq read2.fq Wrapper for `bwa sampe`. Output will be read1.sam.
4.284782
3.892195
1.100865
dbfile, read1file = args[:2] readtype = opts.readtype pl = readtype or "illumina" pf = op.basename(read1file).split(".")[0] rg = opts.rg or r"@RG\tID:{0}\tSM:sm\tLB:lb\tPL:{1}".format(pf, pl) dbfile = check_index(dbfile) args[0] = dbfile samfile, _, unmapped = get_samfile(read1file...
def mem(args, opts)
%prog mem database.fasta read1.fq [read2.fq] Wrapper for `bwa mem`. Output will be read1.sam.
5.403132
5.113921
1.056554
dbfile, readfile = args dbfile = check_index(dbfile) samfile, _, unmapped = get_samfile(readfile, dbfile, bam=opts.bam, unmapped=opts.unmapped) if not need_update(dbfile, samfile): logging.error("`{0}` exists. `bwa bwasw` already run.".format(samfile)...
def bwasw(args, opts)
%prog bwasw database.fasta long_read.fastq Wrapper for `bwa bwasw`. Output will be long_read.sam.
5.497244
4.815858
1.141488
from jcvi.apps.base import mkdir p = OptionParser(link.__doc__) p.add_option("--dir", help="Place links in a subdirectory [default: %default]") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) meta, = args d = opts.dir if d:...
def link(args)
%prog link metafile Link source to target based on a tabular file.
3.16386
2.964539
1.067235
p = OptionParser(touch.__doc__) opts, args = p.parse_args(args) fp = sys.stdin for link_name in fp: link_name = link_name.strip() if not op.islink(link_name): continue if not op.exists(link_name): continue source = get_abs_path(link_name) ...
def touch(args)
find . -type l | %prog touch Linux commands `touch` wouldn't modify mtime for links, this script can. Use find to pipe in all the symlinks.
4.039889
3.726762
1.084021
p = OptionParser(clean.__doc__) opts, args = p.parse_args(args) for link_name in os.listdir(os.getcwd()): if not op.islink(link_name): continue logging.debug("remove symlink `{0}`".format(link_name)) os.unlink(link_name)
def clean(args)
%prog clean Removes all symlinks from current folder
3.776274
3.18476
1.185733
p = OptionParser(cp.__doc__) fp = sys.stdin for link_name in fp: link_name = link_name.strip() if not op.exists(link_name): continue source = get_abs_path(link_name) link_name = op.basename(link_name) if not op.exists(link_name): os.syml...
def cp(args)
find folder -type l | %prog cp Copy all the softlinks to the current folder, using absolute paths
4.025498
3.663697
1.098753
from jcvi.utils.cbook import human_size p = OptionParser(size.__doc__) fp = sys.stdin results = [] for link_name in fp: link_name = link_name.strip() if not op.islink(link_name): continue source = get_abs_path(link_name) link_name = op.basename(li...
def size(args)
find folder -type l | %prog size Get the size for all the paths that are pointed by the links
3.46027
3.501798
0.988141
p = OptionParser(nucmer.__doc__) opts, args = p.parse_args(args) if len(args) != 5: sys.exit(not p.print_help()) mapbed, mtrfasta, asmfasta, chr, idx = args idx = int(idx) m1 = 1000000 bedfile = "sample.bed" bed = Bed() bed.add("\t".join(str(x) for x in (chr, (idx - 1)...
def nucmer(args)
%prog nucmer mappings.bed MTR.fasta assembly.fasta chr1 3 Select specific chromosome region based on MTR mapping. The above command will extract chr1:2,000,001-3,000,000.
4.470879
3.997421
1.118441
from jcvi.apps.base import download so_file_url = "http://obo.cvs.sourceforge.net/viewvc/obo/obo/ontology/genomic-proteomic/so.obo" so_file = download(so_file_url, debug=False) return GODag(so_file)
def load_GODag()
OBO file retrieved from http://obo.cvs.sourceforge.net/viewvc/obo/obo/ontology/genomic-proteomic/so.obo
4.203075
2.188285
1.920716
if so is None: so = load_GODag() oterm = term if term not in so.valid_names: if "resolve" in method: if "_" in term: tparts = deque(term.split("_")) tparts.pop() if "prefix" in method else tparts.popleft() nterm = "_".join(tpa...
def validate_term(term, so=None, method="verify")
Validate an SO term against so.obo
3.740386
3.688168
1.014158
p = OptionParser(agp.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) tablefile, = args fp = open(tablefile) for row in fp: atoms = row.split() hr = atoms[0] scaf = atoms[1] scaf_start = int(atoms[2]) + 1 ...
def agp(args)
%prog agp Siirt_Female_pistachio_23May2017_table.txt The table file, as prepared by Dovetail Genomics, is not immediately useful to convert gene model coordinates, as assumed by formats.chain.fromagp(). This is a quick script to do such conversion. The file structure of this table file is described in ...
2.531113
2.428292
1.042343
p = OptionParser(traits.__doc__) opts, args = p.parse_args(args) if len(args) < 1: sys.exit(not p.print_help()) samples = [] for folder in args: targets = iglob(folder, "*-traits.json") if not targets: continue filename = targets[0] js = jso...
def traits(args)
%prog traits directory Make HTML page that reports eye and skin color.
2.771375
2.53951
1.091303
p = OptionParser(regression.__doc__) opts, args, iopts = p.set_image_options(args, figsize="8x8") if len(args) != 1: sys.exit(not p.print_help()) tsvfile, = args df = pd.read_csv(tsvfile, sep="\t") chrono = "Chronological age (yr)" pred = "Predicted age (yr)" resdf = pd.Da...
def regression(args)
%prog regression postgenomic-s.tsv Plot chronological vs. predicted age.
3.351095
2.852391
1.174837
fig = plt.figure(1, size) ax1 = plt.subplot2grid((2, 2), (0, 0)) ax2 = plt.subplot2grid((2, 2), (0, 1)) ax3 = plt.subplot2grid((2, 2), (1, 0)) ax4 = plt.subplot2grid((2, 2), (1, 1)) chemistry = ["V1", "V2", "V2.5", float("nan")] colors = sns.color_palette("Set2", 8) color_map = dict...
def composite_correlation(df, size=(12, 8))
Plot composite correlation figure
2.47629
2.4897
0.994613
p = OptionParser(correlation.__doc__) opts, args, iopts = p.set_image_options(args, figsize="12x8") if len(args) != 1: sys.exit(not p.print_help()) tsvfile, = args df = pd.read_csv(tsvfile, sep="\t") composite_correlation(df, size=(iopts.w, iopts.h)) outfile = tsvfile.rsplit("...
def correlation(args)
%prog correlation postgenomic-s.tsv Plot correlation of age vs. postgenomic features.
2.920494
2.444711
1.194617
df = df_orig.rename(columns={"hli_calc_age_sample_taken": "Age", "hli_calc_gender": "Gender", "eth7_max": "Ethnicity", "MeanCoverage": "Mean coverage", "Chemistry": "Sequencing chemistry", "Releas...
def composite_qc(df_orig, size=(16, 12))
Plot composite QC figures
2.241422
2.233944
1.003347
# Construct the pairs of trait values traitValuesAbsent = 0 nanValues = 0 genderSkipped = 0 twinValues = [] for a, b, t in triples: if gender is not None and t != gender: genderSkipped += 1 continue if not (a in traits and b in traits): tr...
def extract_twin_values(triples, traits, gender=None)
Calculate the heritability of certain traits in triplets. Parameters ========== triples: (a, b, "Female/Male") triples. The sample IDs are then used to query the traits dictionary. traits: sample_id => value dictionary Returns ======= tuples of size 2, that contain paired trai...
2.99838
3.107881
0.964767
p = OptionParser(heritability.__doc__) opts, args, iopts = p.set_image_options(args, figsize="12x18") if len(args) != 3: sys.exit(not p.print_help()) combined, mz, dz = args # Prepare twins data def get_pairs(filename): with open(filename) as fp: for row in fp...
def heritability(args)
%prog pg.tsv MZ-twins.csv DZ-twins.csv Plot composite figures ABCD on absolute difference of 4 traits, EFGH on heritability of 4 traits. The 4 traits are: telomere length, ccn.chrX, ccn.chrY, TRA.PPM
4.214524
3.593874
1.172696
p = OptionParser(compile.__doc__) p.set_outfile(outfile="age.tsv") opts, args = p.parse_args(args) if len(args) < 1: sys.exit(not p.print_help()) dfs = [] for folder in args: ofolder = os.listdir(folder) # telomeres subdir = [x for x in ofolder if x.starts...
def compile(args)
%prog compile directory Extract telomere length and ccn.
2.904848
2.554879
1.13698
from random import choice seq = Seq(''.join(choice('ACGT') for _ in xrange(size))) s = SeqRecord(seq, id=name, description="Fake sequence") SeqIO.write([s], fw, "fasta")
def simulate_one(fw, name, size)
Simulate a random sequence with name and size
4.169788
3.774137
1.104832
p = OptionParser(simulate.__doc__) p.set_outfile() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) idsfile, = args fp = open(idsfile) fw = must_open(opts.outfile, "w") for row in fp: name, size = row.split() size = int(size) ...
def simulate(args)
%prog simulate idsfile Simulate random FASTA file based on idsfile, which is a two-column tab-separated file with sequence name and size.
2.820316
2.221859
1.26935
p = OptionParser(gc.__doc__) p.add_option("--binsize", default=500, type="int", help="Bin size to use") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) fastafile, = args binsize = opts.binsize allbins = [] for name, seq in p...
def gc(args)
%prog gc fastafile Plot G+C content distribution.
2.657827
2.550005
1.042283
from jcvi.utils.cbook import SummaryStats p = OptionParser(trimsplit.__doc__) p.add_option("--minlength", default=1000, type="int", help="Min length of contigs to keep") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) fastafile, = ...
def trimsplit(args)
%prog trimsplit fastafile Split sequences at lower-cased letters and stretch of Ns. This is useful at cleaning up the low quality bases for the QUIVER output.
2.472383
2.359091
1.048024
from jcvi.formats.sizes import Sizes p = OptionParser(qual.__doc__) p.add_option("--qv", default=31, type="int", help="Dummy qv score for extended bases") p.set_outfile() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) fastafil...
def qual(args)
%prog qual fastafile Generate dummy .qual file based on FASTA file.
3.199175
2.91505
1.097468
p = OptionParser(info.__doc__) p.add_option("--gaps", default=False, action="store_true", help="Count number of gaps [default: %default]") p.set_table() p.set_outfile() opts, args = p.parse_args(args) if len(args) == 0: sys.exit(not p.print_help()) fastafiles ...
def info(args)
%prog info *.fasta Run `sequence_info` on FASTA files. Generate a report per file.
3.0887
2.713368
1.138327
p = OptionParser(fromtab.__doc__) p.set_sep(sep=None) p.add_option("--noheader", default=False, action="store_true", help="Ignore first line") p.add_option("--replace", help="Replace spaces in name to char [default: %default]") opts, args = p.parse_args(args) ...
def fromtab(args)
%prog fromtab tabfile fastafile Convert 2-column sequence file to FASTA format. One usage for this is to generatea `adapters.fasta` for TRIMMOMATIC.
2.520715
2.327374
1.083072
p = OptionParser(longestorf.__doc__) p.add_option("--ids", action="store_true", help="Generate table with ORF info [default: %default]") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) fastafile, = args pf = fastafile.rsplit(".", 1)...
def longestorf(args)
%prog longestorf fastafile Find longest ORF for each sequence in fastafile.
2.897203
2.803077
1.03358
from jcvi.utils.iter import grouper p = OptionParser(ispcr.__doc__) p.add_option("-r", dest="rclip", default=1, type="int", help="pair ID is derived from rstrip N chars [default: %default]") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) ...
def ispcr(args)
%prog ispcr fastafile Reformat paired primers into isPcr query format, which is three column format: name, forward, reverse
3.108526
3.072927
1.011585
''' parse a fasta-formatted file and returns header can be a fasta file that contains multiple records. ''' try: fp = must_open(infile) except: fp = infile # keep header fa_iter = (x[1] for x in groupby(fp, lambda row: row[0] == '>')) for header in fa_iter: he...
def parse_fasta(infile, upper=False)
parse a fasta-formatted file and returns header can be a fasta file that contains multiple records.
4.364554
3.360394
1.298822