repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
tanghaibao/jcvi
jcvi/variation/str.py
filtervcf
def filtervcf(args): """ %prog filtervcf NA12878.hg38.vcf.gz Filter lobSTR VCF using script shipped in lobSTR. Input file can be a list of vcf files. """ p = OptionParser(filtervcf.__doc__) p.set_home("lobstr", default="/mnt/software/lobSTR") p.set_aws_opts(store="hli-mv-data-science/htang/str") p.set_cpus() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) samples, = args lhome = opts.lobstr_home store = opts.output_path if samples.endswith((".vcf", ".vcf.gz")): vcffiles = [samples] else: vcffiles = [x.strip() for x in must_open(samples)] vcffiles = [x for x in vcffiles if ".filtered." not in x] run_args = [(x, lhome, x.startswith("s3://") and store) for x in vcffiles] cpus = min(opts.cpus, len(run_args)) p = Pool(processes=cpus) for res in p.map_async(run_filter, run_args).get(): continue
python
def filtervcf(args): """ %prog filtervcf NA12878.hg38.vcf.gz Filter lobSTR VCF using script shipped in lobSTR. Input file can be a list of vcf files. """ p = OptionParser(filtervcf.__doc__) p.set_home("lobstr", default="/mnt/software/lobSTR") p.set_aws_opts(store="hli-mv-data-science/htang/str") p.set_cpus() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) samples, = args lhome = opts.lobstr_home store = opts.output_path if samples.endswith((".vcf", ".vcf.gz")): vcffiles = [samples] else: vcffiles = [x.strip() for x in must_open(samples)] vcffiles = [x for x in vcffiles if ".filtered." not in x] run_args = [(x, lhome, x.startswith("s3://") and store) for x in vcffiles] cpus = min(opts.cpus, len(run_args)) p = Pool(processes=cpus) for res in p.map_async(run_filter, run_args).get(): continue
[ "def", "filtervcf", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "filtervcf", ".", "__doc__", ")", "p", ".", "set_home", "(", "\"lobstr\"", ",", "default", "=", "\"/mnt/software/lobSTR\"", ")", "p", ".", "set_aws_opts", "(", "store", "=", "\"hli-m...
%prog filtervcf NA12878.hg38.vcf.gz Filter lobSTR VCF using script shipped in lobSTR. Input file can be a list of vcf files.
[ "%prog", "filtervcf", "NA12878", ".", "hg38", ".", "vcf", ".", "gz" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/str.py#L490-L521
train
200,500
tanghaibao/jcvi
jcvi/variation/str.py
meta
def meta(args): """ %prog meta data.bin samples STR.ids STR-exons.wo.bed Compute allele frequencies and prune sites based on missingness. Filter subset of loci that satisfy: 1. no redundancy (unique chr:pos) 2. variable (n_alleles > 1) 3. low level of missing data (>= 50% autosomal + X, > 25% for Y) Write meta file with the following infor: 1. id 2. title 3. gene_name 4. variant_type 5. motif 6. allele_frequency `STR-exons.wo.bed` can be generated like this: $ tail -n 694105 /mnt/software/lobSTR/hg38/index.tab | cut -f1-3 > all-STR.bed $ intersectBed -a all-STR.bed -b all-exons.bed -wo > STR-exons.wo.bed """ p = OptionParser(meta.__doc__) p.add_option("--cutoff", default=.5, type="float", help="Percent observed required (chrY half cutoff)") p.set_cpus() opts, args = p.parse_args(args) if len(args) != 4: sys.exit(not p.print_help()) binfile, sampleids, strids, wobed = args cutoff = opts.cutoff af_file = "allele_freq" if need_update(binfile, af_file): df, m, samples, loci = read_binfile(binfile, sampleids, strids) nalleles = len(samples) fw = must_open(af_file, "w") for i, locus in enumerate(loci): a = m[:, i] counts = alleles_to_counts(a) af = counts_to_af(counts) seqid = locus.split("_")[0] remove = counts_filter(counts, nalleles, seqid, cutoff=cutoff) print("\t".join((locus, af, remove)), file=fw) fw.close() logging.debug("Load gene intersections from `{}`".format(wobed)) fp = open(wobed) gene_map = defaultdict(set) for row in fp: chr1, start1, end1, chr2, start2, end2, name, ov = row.split() gene_map[(chr1, start1)] |= set(name.split(",")) for k, v in gene_map.items(): non_enst = sorted(x for x in v if not x.startswith("ENST")) #enst = sorted(x.rsplit(".", 1)[0] for x in v if x.startswith("ENST")) gene_map[k] = ",".join(non_enst) TREDS, df = read_treds() metafile = "STRs_{}_SEARCH.meta.tsv".format(timestamp()) write_meta(af_file, gene_map, TREDS, filename=metafile) logging.debug("File `{}` written.".format(metafile))
python
def meta(args): """ %prog meta data.bin samples STR.ids STR-exons.wo.bed Compute allele frequencies and prune sites based on missingness. Filter subset of loci that satisfy: 1. no redundancy (unique chr:pos) 2. variable (n_alleles > 1) 3. low level of missing data (>= 50% autosomal + X, > 25% for Y) Write meta file with the following infor: 1. id 2. title 3. gene_name 4. variant_type 5. motif 6. allele_frequency `STR-exons.wo.bed` can be generated like this: $ tail -n 694105 /mnt/software/lobSTR/hg38/index.tab | cut -f1-3 > all-STR.bed $ intersectBed -a all-STR.bed -b all-exons.bed -wo > STR-exons.wo.bed """ p = OptionParser(meta.__doc__) p.add_option("--cutoff", default=.5, type="float", help="Percent observed required (chrY half cutoff)") p.set_cpus() opts, args = p.parse_args(args) if len(args) != 4: sys.exit(not p.print_help()) binfile, sampleids, strids, wobed = args cutoff = opts.cutoff af_file = "allele_freq" if need_update(binfile, af_file): df, m, samples, loci = read_binfile(binfile, sampleids, strids) nalleles = len(samples) fw = must_open(af_file, "w") for i, locus in enumerate(loci): a = m[:, i] counts = alleles_to_counts(a) af = counts_to_af(counts) seqid = locus.split("_")[0] remove = counts_filter(counts, nalleles, seqid, cutoff=cutoff) print("\t".join((locus, af, remove)), file=fw) fw.close() logging.debug("Load gene intersections from `{}`".format(wobed)) fp = open(wobed) gene_map = defaultdict(set) for row in fp: chr1, start1, end1, chr2, start2, end2, name, ov = row.split() gene_map[(chr1, start1)] |= set(name.split(",")) for k, v in gene_map.items(): non_enst = sorted(x for x in v if not x.startswith("ENST")) #enst = sorted(x.rsplit(".", 1)[0] for x in v if x.startswith("ENST")) gene_map[k] = ",".join(non_enst) TREDS, df = read_treds() metafile = "STRs_{}_SEARCH.meta.tsv".format(timestamp()) write_meta(af_file, gene_map, TREDS, filename=metafile) logging.debug("File `{}` written.".format(metafile))
[ "def", "meta", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "meta", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--cutoff\"", ",", "default", "=", ".5", ",", "type", "=", "\"float\"", ",", "help", "=", "\"Percent observed required (chrY ha...
%prog meta data.bin samples STR.ids STR-exons.wo.bed Compute allele frequencies and prune sites based on missingness. Filter subset of loci that satisfy: 1. no redundancy (unique chr:pos) 2. variable (n_alleles > 1) 3. low level of missing data (>= 50% autosomal + X, > 25% for Y) Write meta file with the following infor: 1. id 2. title 3. gene_name 4. variant_type 5. motif 6. allele_frequency `STR-exons.wo.bed` can be generated like this: $ tail -n 694105 /mnt/software/lobSTR/hg38/index.tab | cut -f1-3 > all-STR.bed $ intersectBed -a all-STR.bed -b all-exons.bed -wo > STR-exons.wo.bed
[ "%prog", "meta", "data", ".", "bin", "samples", "STR", ".", "ids", "STR", "-", "exons", ".", "wo", ".", "bed" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/str.py#L559-L623
train
200,501
tanghaibao/jcvi
jcvi/variation/str.py
bin
def bin(args): """ %prog bin data.tsv Conver tsv to binary format. """ p = OptionParser(bin.__doc__) p.add_option("--dtype", choices=("float32", "int32"), help="dtype of the matrix") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) tsvfile, = args dtype = opts.dtype if dtype is None: # Guess dtype = np.int32 if "data" in tsvfile else np.float32 else: dtype = np.int32 if dtype == "int32" else np.float32 print("dtype: {}".format(dtype), file=sys.stderr) fp = open(tsvfile) next(fp) arrays = [] for i, row in enumerate(fp): a = np.fromstring(row, sep="\t", dtype=dtype) a = a[1:] arrays.append(a) print(i, a, file=sys.stderr) print("Merging", file=sys.stderr) b = np.concatenate(arrays) print("Binary shape: {}".format(b.shape), file=sys.stderr) binfile = tsvfile.rsplit(".", 1)[0] + ".bin" b.tofile(binfile)
python
def bin(args): """ %prog bin data.tsv Conver tsv to binary format. """ p = OptionParser(bin.__doc__) p.add_option("--dtype", choices=("float32", "int32"), help="dtype of the matrix") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) tsvfile, = args dtype = opts.dtype if dtype is None: # Guess dtype = np.int32 if "data" in tsvfile else np.float32 else: dtype = np.int32 if dtype == "int32" else np.float32 print("dtype: {}".format(dtype), file=sys.stderr) fp = open(tsvfile) next(fp) arrays = [] for i, row in enumerate(fp): a = np.fromstring(row, sep="\t", dtype=dtype) a = a[1:] arrays.append(a) print(i, a, file=sys.stderr) print("Merging", file=sys.stderr) b = np.concatenate(arrays) print("Binary shape: {}".format(b.shape), file=sys.stderr) binfile = tsvfile.rsplit(".", 1)[0] + ".bin" b.tofile(binfile)
[ "def", "bin", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "bin", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--dtype\"", ",", "choices", "=", "(", "\"float32\"", ",", "\"int32\"", ")", ",", "help", "=", "\"dtype of the matrix\"", ")", ...
%prog bin data.tsv Conver tsv to binary format.
[ "%prog", "bin", "data", ".", "tsv" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/str.py#L650-L685
train
200,502
tanghaibao/jcvi
jcvi/variation/str.py
data
def data(args): """ %prog data data.bin samples.ids STR.ids meta.tsv Make data.tsv based on meta.tsv. """ p = OptionParser(data.__doc__) p.add_option("--notsv", default=False, action="store_true", help="Do not write data.tsv") opts, args = p.parse_args(args) if len(args) != 4: sys.exit(not p.print_help()) databin, sampleids, strids, metafile = args final_columns, percentiles = read_meta(metafile) df, m, samples, loci = read_binfile(databin, sampleids, strids) # Clean the data m %= 1000 # Get the larger of the two alleles m[m == 999] = -1 # Missing data final = set(final_columns) remove = [] for i, locus in enumerate(loci): if locus not in final: remove.append(locus) continue pf = "STRs_{}_SEARCH".format(timestamp()) filteredstrids = "{}.STR.ids".format(pf) fw = open(filteredstrids, "w") print("\n".join(final_columns), file=fw) fw.close() logging.debug("Dropped {} columns; Retained {} columns (`{}`)".\ format(len(remove), len(final_columns), filteredstrids)) # Remove low-quality columns! df.drop(remove, inplace=True, axis=1) df.columns = final_columns filtered_bin = "{}.data.bin".format(pf) if need_update(databin, filtered_bin): m = df.as_matrix() m.tofile(filtered_bin) logging.debug("Filtered binary matrix written to `{}`".format(filtered_bin)) # Write data output filtered_tsv = "{}.data.tsv".format(pf) if not opts.notsv and need_update(databin, filtered_tsv): df.to_csv(filtered_tsv, sep="\t", index_label="SampleKey")
python
def data(args): """ %prog data data.bin samples.ids STR.ids meta.tsv Make data.tsv based on meta.tsv. """ p = OptionParser(data.__doc__) p.add_option("--notsv", default=False, action="store_true", help="Do not write data.tsv") opts, args = p.parse_args(args) if len(args) != 4: sys.exit(not p.print_help()) databin, sampleids, strids, metafile = args final_columns, percentiles = read_meta(metafile) df, m, samples, loci = read_binfile(databin, sampleids, strids) # Clean the data m %= 1000 # Get the larger of the two alleles m[m == 999] = -1 # Missing data final = set(final_columns) remove = [] for i, locus in enumerate(loci): if locus not in final: remove.append(locus) continue pf = "STRs_{}_SEARCH".format(timestamp()) filteredstrids = "{}.STR.ids".format(pf) fw = open(filteredstrids, "w") print("\n".join(final_columns), file=fw) fw.close() logging.debug("Dropped {} columns; Retained {} columns (`{}`)".\ format(len(remove), len(final_columns), filteredstrids)) # Remove low-quality columns! df.drop(remove, inplace=True, axis=1) df.columns = final_columns filtered_bin = "{}.data.bin".format(pf) if need_update(databin, filtered_bin): m = df.as_matrix() m.tofile(filtered_bin) logging.debug("Filtered binary matrix written to `{}`".format(filtered_bin)) # Write data output filtered_tsv = "{}.data.tsv".format(pf) if not opts.notsv and need_update(databin, filtered_tsv): df.to_csv(filtered_tsv, sep="\t", index_label="SampleKey")
[ "def", "data", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "data", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--notsv\"", ",", "default", "=", "False", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Do not write data.tsv\"",...
%prog data data.bin samples.ids STR.ids meta.tsv Make data.tsv based on meta.tsv.
[ "%prog", "data", "data", ".", "bin", "samples", ".", "ids", "STR", ".", "ids", "meta", ".", "tsv" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/str.py#L749-L799
train
200,503
tanghaibao/jcvi
jcvi/variation/str.py
mask
def mask(args): """ %prog mask data.bin samples.ids STR.ids meta.tsv OR %prog mask data.tsv meta.tsv Compute P-values based on meta and data. The `data.bin` should be the matrix containing filtered loci and the output mask.tsv will have the same dimension. """ p = OptionParser(mask.__doc__) opts, args = p.parse_args(args) if len(args) not in (2, 4): sys.exit(not p.print_help()) if len(args) == 4: databin, sampleids, strids, metafile = args df, m, samples, loci = read_binfile(databin, sampleids, strids) mode = "STRs" elif len(args) == 2: databin, metafile = args df = pd.read_csv(databin, sep="\t", index_col=0) m = df.as_matrix() samples = df.index loci = list(df.columns) mode = "TREDs" pf = "{}_{}_SEARCH".format(mode, timestamp()) final_columns, percentiles = read_meta(metafile) maskfile = pf + ".mask.tsv" run_args = [] for i, locus in enumerate(loci): a = m[:, i] percentile = percentiles[locus] run_args.append((i, a, percentile)) if mode == "TREDs" or need_update(databin, maskfile): cpus = min(8, len(run_args)) write_mask(cpus, samples, final_columns, run_args, filename=maskfile) logging.debug("File `{}` written.".format(maskfile))
python
def mask(args): """ %prog mask data.bin samples.ids STR.ids meta.tsv OR %prog mask data.tsv meta.tsv Compute P-values based on meta and data. The `data.bin` should be the matrix containing filtered loci and the output mask.tsv will have the same dimension. """ p = OptionParser(mask.__doc__) opts, args = p.parse_args(args) if len(args) not in (2, 4): sys.exit(not p.print_help()) if len(args) == 4: databin, sampleids, strids, metafile = args df, m, samples, loci = read_binfile(databin, sampleids, strids) mode = "STRs" elif len(args) == 2: databin, metafile = args df = pd.read_csv(databin, sep="\t", index_col=0) m = df.as_matrix() samples = df.index loci = list(df.columns) mode = "TREDs" pf = "{}_{}_SEARCH".format(mode, timestamp()) final_columns, percentiles = read_meta(metafile) maskfile = pf + ".mask.tsv" run_args = [] for i, locus in enumerate(loci): a = m[:, i] percentile = percentiles[locus] run_args.append((i, a, percentile)) if mode == "TREDs" or need_update(databin, maskfile): cpus = min(8, len(run_args)) write_mask(cpus, samples, final_columns, run_args, filename=maskfile) logging.debug("File `{}` written.".format(maskfile))
[ "def", "mask", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "mask", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "not", "in", "(", "2", ",", "4", ")", ":", "s...
%prog mask data.bin samples.ids STR.ids meta.tsv OR %prog mask data.tsv meta.tsv Compute P-values based on meta and data. The `data.bin` should be the matrix containing filtered loci and the output mask.tsv will have the same dimension.
[ "%prog", "mask", "data", ".", "bin", "samples", ".", "ids", "STR", ".", "ids", "meta", ".", "tsv" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/str.py#L802-L845
train
200,504
tanghaibao/jcvi
jcvi/variation/str.py
compilevcf
def compilevcf(args): """ %prog compilevcf samples.csv Compile vcf results into master spreadsheet. """ p = OptionParser(compilevcf.__doc__) p.add_option("--db", default="hg38", help="Use these lobSTR db") p.add_option("--nofilter", default=False, action="store_true", help="Do not filter the variants") p.set_home("lobstr") p.set_cpus() p.set_aws_opts(store="hli-mv-data-science/htang/str-data") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) samples, = args workdir = opts.workdir store = opts.output_path cleanup = not opts.nocleanup filtered = not opts.nofilter dbs = opts.db.split(",") cwd = os.getcwd() mkdir(workdir) os.chdir(workdir) samples = op.join(cwd, samples) stridsfile = "STR.ids" if samples.endswith((".vcf", ".vcf.gz")): vcffiles = [samples] else: vcffiles = [x.strip() for x in must_open(samples)] if not op.exists(stridsfile): ids = [] for db in dbs: ids.extend(STRFile(opts.lobstr_home, db=db).ids) uids = uniqify(ids) logging.debug("Combined: {} Unique: {}".format(len(ids), len(uids))) fw = open(stridsfile, "w") print("\n".join(uids), file=fw) fw.close() run_args = [(x, filtered, cleanup, store) for x in vcffiles] cpus = min(opts.cpus, len(run_args)) p = Pool(processes=cpus) for res in p.map_async(run_compile, run_args).get(): continue
python
def compilevcf(args): """ %prog compilevcf samples.csv Compile vcf results into master spreadsheet. """ p = OptionParser(compilevcf.__doc__) p.add_option("--db", default="hg38", help="Use these lobSTR db") p.add_option("--nofilter", default=False, action="store_true", help="Do not filter the variants") p.set_home("lobstr") p.set_cpus() p.set_aws_opts(store="hli-mv-data-science/htang/str-data") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) samples, = args workdir = opts.workdir store = opts.output_path cleanup = not opts.nocleanup filtered = not opts.nofilter dbs = opts.db.split(",") cwd = os.getcwd() mkdir(workdir) os.chdir(workdir) samples = op.join(cwd, samples) stridsfile = "STR.ids" if samples.endswith((".vcf", ".vcf.gz")): vcffiles = [samples] else: vcffiles = [x.strip() for x in must_open(samples)] if not op.exists(stridsfile): ids = [] for db in dbs: ids.extend(STRFile(opts.lobstr_home, db=db).ids) uids = uniqify(ids) logging.debug("Combined: {} Unique: {}".format(len(ids), len(uids))) fw = open(stridsfile, "w") print("\n".join(uids), file=fw) fw.close() run_args = [(x, filtered, cleanup, store) for x in vcffiles] cpus = min(opts.cpus, len(run_args)) p = Pool(processes=cpus) for res in p.map_async(run_compile, run_args).get(): continue
[ "def", "compilevcf", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "compilevcf", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--db\"", ",", "default", "=", "\"hg38\"", ",", "help", "=", "\"Use these lobSTR db\"", ")", "p", ".", "add_option"...
%prog compilevcf samples.csv Compile vcf results into master spreadsheet.
[ "%prog", "compilevcf", "samples", ".", "csv" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/str.py#L947-L996
train
200,505
tanghaibao/jcvi
jcvi/variation/str.py
ystr
def ystr(args): """ %prog ystr chrY.vcf Print out Y-STR info given VCF. Marker name extracted from tabfile. """ from jcvi.utils.table import write_csv p = OptionParser(ystr.__doc__) p.set_home("lobstr") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) vcffile, = args si = STRFile(opts.lobstr_home, db="hg38-named") register = si.register header = "Marker|Reads|Ref|Genotype|Motif".split("|") contents = [] fp = must_open(vcffile) reader = vcf.Reader(fp) simple_register = {} for record in reader: name = register[(record.CHROM, record.POS)] info = record.INFO ref = int(float(info["REF"])) rpa = info.get("RPA", ref) if isinstance(rpa, list): rpa = "|".join(str(int(float(x))) for x in rpa) ru = info["RU"] simple_register[name] = rpa for sample in record.samples: contents.append((name, sample["ALLREADS"], ref, rpa, ru)) # Multi-part markers a, b, c = "DYS389I", "DYS389B.1", "DYS389B" if a in simple_register and b in simple_register: simple_register[c] = int(simple_register[a]) + int(simple_register[b]) # Multi-copy markers mm = ["DYS385", "DYS413", "YCAII"] for m in mm: ma, mb = m + 'a', m + 'b' if ma not in simple_register or mb not in simple_register: simple_register[ma] = simple_register[mb] = None del simple_register[ma] del simple_register[mb] continue if simple_register[ma] > simple_register[mb]: simple_register[ma], simple_register[mb] = \ simple_register[mb], simple_register[ma] write_csv(header, contents, sep=" ") print("[YSEARCH]") build_ysearch_link(simple_register) print("[YFILER]") build_yhrd_link(simple_register, panel=YHRD_YFILER) print("[YFILERPLUS]") build_yhrd_link(simple_register, panel=YHRD_YFILERPLUS) print("[YSTR-ALL]") build_yhrd_link(simple_register, panel=USYSTR_ALL)
python
def ystr(args): """ %prog ystr chrY.vcf Print out Y-STR info given VCF. Marker name extracted from tabfile. """ from jcvi.utils.table import write_csv p = OptionParser(ystr.__doc__) p.set_home("lobstr") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) vcffile, = args si = STRFile(opts.lobstr_home, db="hg38-named") register = si.register header = "Marker|Reads|Ref|Genotype|Motif".split("|") contents = [] fp = must_open(vcffile) reader = vcf.Reader(fp) simple_register = {} for record in reader: name = register[(record.CHROM, record.POS)] info = record.INFO ref = int(float(info["REF"])) rpa = info.get("RPA", ref) if isinstance(rpa, list): rpa = "|".join(str(int(float(x))) for x in rpa) ru = info["RU"] simple_register[name] = rpa for sample in record.samples: contents.append((name, sample["ALLREADS"], ref, rpa, ru)) # Multi-part markers a, b, c = "DYS389I", "DYS389B.1", "DYS389B" if a in simple_register and b in simple_register: simple_register[c] = int(simple_register[a]) + int(simple_register[b]) # Multi-copy markers mm = ["DYS385", "DYS413", "YCAII"] for m in mm: ma, mb = m + 'a', m + 'b' if ma not in simple_register or mb not in simple_register: simple_register[ma] = simple_register[mb] = None del simple_register[ma] del simple_register[mb] continue if simple_register[ma] > simple_register[mb]: simple_register[ma], simple_register[mb] = \ simple_register[mb], simple_register[ma] write_csv(header, contents, sep=" ") print("[YSEARCH]") build_ysearch_link(simple_register) print("[YFILER]") build_yhrd_link(simple_register, panel=YHRD_YFILER) print("[YFILERPLUS]") build_yhrd_link(simple_register, panel=YHRD_YFILERPLUS) print("[YSTR-ALL]") build_yhrd_link(simple_register, panel=USYSTR_ALL)
[ "def", "ystr", "(", "args", ")", ":", "from", "jcvi", ".", "utils", ".", "table", "import", "write_csv", "p", "=", "OptionParser", "(", "ystr", ".", "__doc__", ")", "p", ".", "set_home", "(", "\"lobstr\"", ")", "opts", ",", "args", "=", "p", ".", "...
%prog ystr chrY.vcf Print out Y-STR info given VCF. Marker name extracted from tabfile.
[ "%prog", "ystr", "chrY", ".", "vcf" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/str.py#L1022-L1084
train
200,506
tanghaibao/jcvi
jcvi/variation/str.py
liftover
def liftover(args): """ %prog liftover lobstr_v3.0.2_hg38_ref.bed hg38.upper.fa LiftOver CODIS/Y-STR markers. """ p = OptionParser(liftover.__doc__) p.add_option("--checkvalid", default=False, action="store_true", help="Check minscore, period and length") opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) refbed, fastafile = args genome = pyfasta.Fasta(fastafile) edits = [] fp = open(refbed) for i, row in enumerate(fp): s = STRLine(row) seq = genome[s.seqid][s.start - 1: s.end].upper() s.motif = get_motif(seq, len(s.motif)) s.fix_counts(seq) if opts.checkvalid and not s.is_valid(): continue edits.append(s) if i % 10000 == 0: print(i, "lines read", file=sys.stderr) edits = natsorted(edits, key=lambda x: (x.seqid, x.start)) for e in edits: print(str(e))
python
def liftover(args): """ %prog liftover lobstr_v3.0.2_hg38_ref.bed hg38.upper.fa LiftOver CODIS/Y-STR markers. """ p = OptionParser(liftover.__doc__) p.add_option("--checkvalid", default=False, action="store_true", help="Check minscore, period and length") opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) refbed, fastafile = args genome = pyfasta.Fasta(fastafile) edits = [] fp = open(refbed) for i, row in enumerate(fp): s = STRLine(row) seq = genome[s.seqid][s.start - 1: s.end].upper() s.motif = get_motif(seq, len(s.motif)) s.fix_counts(seq) if opts.checkvalid and not s.is_valid(): continue edits.append(s) if i % 10000 == 0: print(i, "lines read", file=sys.stderr) edits = natsorted(edits, key=lambda x: (x.seqid, x.start)) for e in edits: print(str(e))
[ "def", "liftover", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "liftover", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--checkvalid\"", ",", "default", "=", "False", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Check minsco...
%prog liftover lobstr_v3.0.2_hg38_ref.bed hg38.upper.fa LiftOver CODIS/Y-STR markers.
[ "%prog", "liftover", "lobstr_v3", ".", "0", ".", "2_hg38_ref", ".", "bed", "hg38", ".", "upper", ".", "fa" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/str.py#L1102-L1133
train
200,507
tanghaibao/jcvi
jcvi/variation/str.py
trf
def trf(args): """ %prog trf outdir Run TRF on FASTA files. """ from jcvi.apps.base import iglob cparams = "1 1 2 80 5 200 2000" p = OptionParser(trf.__doc__) p.add_option("--mismatch", default=31, type="int", help="Mismatch and gap penalty") p.add_option("--minscore", default=MINSCORE, type="int", help="Minimum score to report") p.add_option("--period", default=6, type="int", help="Maximum period to report") p.add_option("--lobstr", default=False, action="store_true", help="Generate output for lobSTR") p.add_option("--telomeres", default=False, action="store_true", help="Run telomere search: minscore=140 period=7") p.add_option("--centromeres", default=False, action="store_true", help="Run centromere search: {}".format(cparams)) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) outdir, = args minlength = opts.minscore / 2 mm = MakeManager() if opts.telomeres: opts.minscore, opts.period = 140, 7 params = "2 {0} {0} 80 10 {1} {2}".\ format(opts.mismatch, opts.minscore, opts.period).split() if opts.centromeres: params = cparams.split() bedfiles = [] for fastafile in natsorted(iglob(outdir, "*.fa,*.fasta")): pf = op.basename(fastafile).split(".")[0] cmd1 = "trf {0} {1} -d -h".format(fastafile, " ".join(params)) datfile = op.basename(fastafile) + "." + ".".join(params) + ".dat" bedfile = "{0}.trf.bed".format(pf) cmd2 = "cat {} | grep -v ^Parameters".format(datfile) if opts.lobstr: cmd2 += " | awk '($8 >= {} && $8 <= {})'".\ format(minlength, READLEN - minlength) else: cmd2 += " | awk '($8 >= 0)'" cmd2 += " | sed 's/ /\\t/g'" cmd2 += " | awk '{{print \"{0}\\t\" $0}}' > {1}".format(pf, bedfile) mm.add(fastafile, datfile, cmd1) mm.add(datfile, bedfile, cmd2) bedfiles.append(bedfile) bedfile = "trf.bed" cmd = "cat {0} > {1}".format(" ".join(natsorted(bedfiles)), bedfile) mm.add(bedfiles, bedfile, cmd) mm.write()
python
def trf(args): """ %prog trf outdir Run TRF on FASTA files. """ from jcvi.apps.base import iglob cparams = "1 1 2 80 5 200 2000" p = OptionParser(trf.__doc__) p.add_option("--mismatch", default=31, type="int", help="Mismatch and gap penalty") p.add_option("--minscore", default=MINSCORE, type="int", help="Minimum score to report") p.add_option("--period", default=6, type="int", help="Maximum period to report") p.add_option("--lobstr", default=False, action="store_true", help="Generate output for lobSTR") p.add_option("--telomeres", default=False, action="store_true", help="Run telomere search: minscore=140 period=7") p.add_option("--centromeres", default=False, action="store_true", help="Run centromere search: {}".format(cparams)) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) outdir, = args minlength = opts.minscore / 2 mm = MakeManager() if opts.telomeres: opts.minscore, opts.period = 140, 7 params = "2 {0} {0} 80 10 {1} {2}".\ format(opts.mismatch, opts.minscore, opts.period).split() if opts.centromeres: params = cparams.split() bedfiles = [] for fastafile in natsorted(iglob(outdir, "*.fa,*.fasta")): pf = op.basename(fastafile).split(".")[0] cmd1 = "trf {0} {1} -d -h".format(fastafile, " ".join(params)) datfile = op.basename(fastafile) + "." + ".".join(params) + ".dat" bedfile = "{0}.trf.bed".format(pf) cmd2 = "cat {} | grep -v ^Parameters".format(datfile) if opts.lobstr: cmd2 += " | awk '($8 >= {} && $8 <= {})'".\ format(minlength, READLEN - minlength) else: cmd2 += " | awk '($8 >= 0)'" cmd2 += " | sed 's/ /\\t/g'" cmd2 += " | awk '{{print \"{0}\\t\" $0}}' > {1}".format(pf, bedfile) mm.add(fastafile, datfile, cmd1) mm.add(datfile, bedfile, cmd2) bedfiles.append(bedfile) bedfile = "trf.bed" cmd = "cat {0} > {1}".format(" ".join(natsorted(bedfiles)), bedfile) mm.add(bedfiles, bedfile, cmd) mm.write()
[ "def", "trf", "(", "args", ")", ":", "from", "jcvi", ".", "apps", ".", "base", "import", "iglob", "cparams", "=", "\"1 1 2 80 5 200 2000\"", "p", "=", "OptionParser", "(", "trf", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--mismatch\"", ",", "d...
%prog trf outdir Run TRF on FASTA files.
[ "%prog", "trf", "outdir" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/str.py#L1136-L1196
train
200,508
tanghaibao/jcvi
jcvi/variation/str.py
batchlobstr
def batchlobstr(args): """ %prog batchlobstr samples.csv Run lobSTR sequentially on list of samples. Each line contains: sample-name,s3-location """ p = OptionParser(batchlobstr.__doc__) p.add_option("--sep", default=",", help="Separator for building commandline") p.set_home("lobstr", default="s3://hli-mv-data-science/htang/str-build/lobSTR/") p.set_aws_opts(store="hli-mv-data-science/htang/str-data") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) samplesfile, = args store = opts.output_path computed = ls_s3(store) fp = open(samplesfile) skipped = total = 0 for row in fp: total += 1 sample, s3file = row.strip().split(",")[:2] exec_id, sample_id = sample.split("_") bamfile = s3file.replace(".gz", "").replace(".vcf", ".bam") gzfile = sample + ".{0}.vcf.gz".format("hg38") if gzfile in computed: skipped += 1 continue print(opts.sep.join("python -m jcvi.variation.str lobstr".split() + \ ["hg38", "--input_bam_path", bamfile, "--output_path", store, "--sample_id", sample_id, "--workflow_execution_id", exec_id, "--lobstr_home", opts.lobstr_home, "--workdir", opts.workdir])) fp.close() logging.debug("Total skipped: {0}".format(percentage(skipped, total)))
python
def batchlobstr(args): """ %prog batchlobstr samples.csv Run lobSTR sequentially on list of samples. Each line contains: sample-name,s3-location """ p = OptionParser(batchlobstr.__doc__) p.add_option("--sep", default=",", help="Separator for building commandline") p.set_home("lobstr", default="s3://hli-mv-data-science/htang/str-build/lobSTR/") p.set_aws_opts(store="hli-mv-data-science/htang/str-data") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) samplesfile, = args store = opts.output_path computed = ls_s3(store) fp = open(samplesfile) skipped = total = 0 for row in fp: total += 1 sample, s3file = row.strip().split(",")[:2] exec_id, sample_id = sample.split("_") bamfile = s3file.replace(".gz", "").replace(".vcf", ".bam") gzfile = sample + ".{0}.vcf.gz".format("hg38") if gzfile in computed: skipped += 1 continue print(opts.sep.join("python -m jcvi.variation.str lobstr".split() + \ ["hg38", "--input_bam_path", bamfile, "--output_path", store, "--sample_id", sample_id, "--workflow_execution_id", exec_id, "--lobstr_home", opts.lobstr_home, "--workdir", opts.workdir])) fp.close() logging.debug("Total skipped: {0}".format(percentage(skipped, total)))
[ "def", "batchlobstr", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "batchlobstr", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--sep\"", ",", "default", "=", "\",\"", ",", "help", "=", "\"Separator for building commandline\"", ")", "p", ".",...
%prog batchlobstr samples.csv Run lobSTR sequentially on list of samples. Each line contains: sample-name,s3-location
[ "%prog", "batchlobstr", "samples", ".", "csv" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/str.py#L1199-L1240
train
200,509
tanghaibao/jcvi
jcvi/variation/str.py
locus
def locus(args): """ %prog locus bamfile Extract selected locus from a list of TREDs for validation, and run lobSTR. """ from jcvi.formats.sam import get_minibam # See `Format-lobSTR-database.ipynb` for a list of TREDs for validation INCLUDE = ["HD", "SBMA", "SCA1", "SCA2", "SCA8", "SCA17", "DM1", "DM2", "FXTAS"] db_choices = ("hg38", "hg19") p = OptionParser(locus.__doc__) p.add_option("--tred", choices=INCLUDE, help="TRED name") p.add_option("--ref", choices=db_choices, default="hg38", help="Reference genome") p.set_home("lobstr") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) bamfile, = args ref = opts.ref lhome = opts.lobstr_home tred = opts.tred tredsfile = datafile("TREDs.meta.csv") tf = pd.read_csv(tredsfile, index_col=0) row = tf.ix[tred] tag = "repeat_location" ldb = "TREDs" if ref == "hg19": tag += "." + ref ldb += "-" + ref seqid, start_end = row[tag].split(":") PAD = 1000 start, end = start_end.split('-') start, end = int(start) - PAD, int(end) + PAD region = "{}:{}-{}".format(seqid, start, end) minibamfile = get_minibam(bamfile, region) c = seqid.replace("chr", "") cmd, vcf = allelotype_on_chr(minibamfile, c, lhome, ldb) sh(cmd) parser = LobSTRvcf(columnidsfile=None) parser.parse(vcf, filtered=False) items = parser.items() if not items: print("No entry found!", file=sys.stderr) return k, v = parser.items()[0] print("{} => {}".format(tred, v.replace(',', '/')), file=sys.stderr)
python
def locus(args): """ %prog locus bamfile Extract selected locus from a list of TREDs for validation, and run lobSTR. """ from jcvi.formats.sam import get_minibam # See `Format-lobSTR-database.ipynb` for a list of TREDs for validation INCLUDE = ["HD", "SBMA", "SCA1", "SCA2", "SCA8", "SCA17", "DM1", "DM2", "FXTAS"] db_choices = ("hg38", "hg19") p = OptionParser(locus.__doc__) p.add_option("--tred", choices=INCLUDE, help="TRED name") p.add_option("--ref", choices=db_choices, default="hg38", help="Reference genome") p.set_home("lobstr") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) bamfile, = args ref = opts.ref lhome = opts.lobstr_home tred = opts.tred tredsfile = datafile("TREDs.meta.csv") tf = pd.read_csv(tredsfile, index_col=0) row = tf.ix[tred] tag = "repeat_location" ldb = "TREDs" if ref == "hg19": tag += "." + ref ldb += "-" + ref seqid, start_end = row[tag].split(":") PAD = 1000 start, end = start_end.split('-') start, end = int(start) - PAD, int(end) + PAD region = "{}:{}-{}".format(seqid, start, end) minibamfile = get_minibam(bamfile, region) c = seqid.replace("chr", "") cmd, vcf = allelotype_on_chr(minibamfile, c, lhome, ldb) sh(cmd) parser = LobSTRvcf(columnidsfile=None) parser.parse(vcf, filtered=False) items = parser.items() if not items: print("No entry found!", file=sys.stderr) return k, v = parser.items()[0] print("{} => {}".format(tred, v.replace(',', '/')), file=sys.stderr)
[ "def", "locus", "(", "args", ")", ":", "from", "jcvi", ".", "formats", ".", "sam", "import", "get_minibam", "# See `Format-lobSTR-database.ipynb` for a list of TREDs for validation", "INCLUDE", "=", "[", "\"HD\"", ",", "\"SBMA\"", ",", "\"SCA1\"", ",", "\"SCA2\"", "...
%prog locus bamfile Extract selected locus from a list of TREDs for validation, and run lobSTR.
[ "%prog", "locus", "bamfile" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/str.py#L1368-L1424
train
200,510
tanghaibao/jcvi
jcvi/variation/str.py
lobstrindex
def lobstrindex(args): """ %prog lobstrindex hg38.trf.bed hg38.upper.fa Make lobSTR index. Make sure the FASTA contain only upper case (so use fasta.format --upper to convert from UCSC fasta). The bed file is generated by str(). """ p = OptionParser(lobstrindex.__doc__) p.add_option("--notreds", default=False, action="store_true", help="Remove TREDs from the bed file") p.set_home("lobstr") opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) trfbed, fastafile = args pf = fastafile.split(".")[0] lhome = opts.lobstr_home mkdir(pf) if opts.notreds: newbedfile = trfbed + ".new" newbed = open(newbedfile, "w") fp = open(trfbed) retained = total = 0 seen = set() for row in fp: r = STRLine(row) total += 1 name = r.longname if name in seen: continue seen.add(name) print(r, file=newbed) retained += 1 newbed.close() logging.debug("Retained: {0}".format(percentage(retained, total))) else: newbedfile = trfbed mm = MakeManager() cmd = "python {0}/scripts/lobstr_index.py".format(lhome) cmd += " --str {0} --ref {1} --out {2}".format(newbedfile, fastafile, pf) mm.add((newbedfile, fastafile), op.join(pf, "lobSTR_ref.fasta.rsa"), cmd) tabfile = "{0}/index.tab".format(pf) cmd = "python {0}/scripts/GetSTRInfo.py".format(lhome) cmd += " {0} {1} > {2}".format(newbedfile, fastafile, tabfile) mm.add((newbedfile, fastafile), tabfile, cmd) infofile = "{0}/index.info".format(pf) cmd = "cp {0} {1}".format(newbedfile, infofile) mm.add(trfbed, infofile, cmd) mm.write()
python
def lobstrindex(args): """ %prog lobstrindex hg38.trf.bed hg38.upper.fa Make lobSTR index. Make sure the FASTA contain only upper case (so use fasta.format --upper to convert from UCSC fasta). The bed file is generated by str(). """ p = OptionParser(lobstrindex.__doc__) p.add_option("--notreds", default=False, action="store_true", help="Remove TREDs from the bed file") p.set_home("lobstr") opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) trfbed, fastafile = args pf = fastafile.split(".")[0] lhome = opts.lobstr_home mkdir(pf) if opts.notreds: newbedfile = trfbed + ".new" newbed = open(newbedfile, "w") fp = open(trfbed) retained = total = 0 seen = set() for row in fp: r = STRLine(row) total += 1 name = r.longname if name in seen: continue seen.add(name) print(r, file=newbed) retained += 1 newbed.close() logging.debug("Retained: {0}".format(percentage(retained, total))) else: newbedfile = trfbed mm = MakeManager() cmd = "python {0}/scripts/lobstr_index.py".format(lhome) cmd += " --str {0} --ref {1} --out {2}".format(newbedfile, fastafile, pf) mm.add((newbedfile, fastafile), op.join(pf, "lobSTR_ref.fasta.rsa"), cmd) tabfile = "{0}/index.tab".format(pf) cmd = "python {0}/scripts/GetSTRInfo.py".format(lhome) cmd += " {0} {1} > {2}".format(newbedfile, fastafile, tabfile) mm.add((newbedfile, fastafile), tabfile, cmd) infofile = "{0}/index.info".format(pf) cmd = "cp {0} {1}".format(newbedfile, infofile) mm.add(trfbed, infofile, cmd) mm.write()
[ "def", "lobstrindex", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "lobstrindex", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--notreds\"", ",", "default", "=", "False", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Remove TR...
%prog lobstrindex hg38.trf.bed hg38.upper.fa Make lobSTR index. Make sure the FASTA contain only upper case (so use fasta.format --upper to convert from UCSC fasta). The bed file is generated by str().
[ "%prog", "lobstrindex", "hg38", ".", "trf", ".", "bed", "hg38", ".", "upper", ".", "fa" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/str.py#L1427-L1482
train
200,511
tanghaibao/jcvi
jcvi/assembly/sspace.py
agp
def agp(args): """ %prog agp evidencefile contigs.fasta Convert SSPACE scaffold structure to AGP format. """ p = OptionParser(agp.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) evidencefile, contigs = args ef = EvidenceFile(evidencefile, contigs) agpfile = evidencefile.replace(".evidence", ".agp") ef.write_agp(agpfile)
python
def agp(args): """ %prog agp evidencefile contigs.fasta Convert SSPACE scaffold structure to AGP format. """ p = OptionParser(agp.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) evidencefile, contigs = args ef = EvidenceFile(evidencefile, contigs) agpfile = evidencefile.replace(".evidence", ".agp") ef.write_agp(agpfile)
[ "def", "agp", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "agp", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", "2", ":", "sys", ".", "exit", "(", "not", ...
%prog agp evidencefile contigs.fasta Convert SSPACE scaffold structure to AGP format.
[ "%prog", "agp", "evidencefile", "contigs", ".", "fasta" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/sspace.py#L194-L210
train
200,512
tanghaibao/jcvi
jcvi/assembly/automaton.py
spades
def spades(args): """ %prog spades folder Run automated SPADES. """ from jcvi.formats.fastq import readlen p = OptionParser(spades.__doc__) opts, args = p.parse_args(args) if len(args) == 0: sys.exit(not p.print_help()) folder, = args for p, pf in iter_project(folder): rl = readlen([p[0], "--silent"]) # <http://spades.bioinf.spbau.ru/release3.1.0/manual.html#sec3.4> kmers = None if rl >= 150: kmers = "21,33,55,77" elif rl >= 250: kmers = "21,33,55,77,99,127" cmd = "spades.py" if kmers: cmd += " -k {0}".format(kmers) cmd += " --careful" cmd += " --pe1-1 {0} --pe1-2 {1}".format(*p) cmd += " -o {0}_spades".format(pf) print(cmd)
python
def spades(args): """ %prog spades folder Run automated SPADES. """ from jcvi.formats.fastq import readlen p = OptionParser(spades.__doc__) opts, args = p.parse_args(args) if len(args) == 0: sys.exit(not p.print_help()) folder, = args for p, pf in iter_project(folder): rl = readlen([p[0], "--silent"]) # <http://spades.bioinf.spbau.ru/release3.1.0/manual.html#sec3.4> kmers = None if rl >= 150: kmers = "21,33,55,77" elif rl >= 250: kmers = "21,33,55,77,99,127" cmd = "spades.py" if kmers: cmd += " -k {0}".format(kmers) cmd += " --careful" cmd += " --pe1-1 {0} --pe1-2 {1}".format(*p) cmd += " -o {0}_spades".format(pf) print(cmd)
[ "def", "spades", "(", "args", ")", ":", "from", "jcvi", ".", "formats", ".", "fastq", "import", "readlen", "p", "=", "OptionParser", "(", "spades", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", ...
%prog spades folder Run automated SPADES.
[ "%prog", "spades", "folder" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/automaton.py#L98-L129
train
200,513
tanghaibao/jcvi
jcvi/assembly/automaton.py
contamination
def contamination(args): """ %prog contamination folder Ecoli.fasta Remove contaminated reads. The FASTQ files in the folder will automatically pair and filtered against Ecoli.fasta to remove contaminants using BOWTIE2. """ from jcvi.apps.bowtie import align p = OptionParser(contamination.__doc__) p.add_option("--mapped", default=False, action="store_true", help="Retain contaminated reads instead [default: %default]") p.set_cutoff(cutoff=800) p.set_mateorientation(mateorientation="+-") opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) folder, ecoli = args ecoli = get_abs_path(ecoli) tag = "--mapped" if opts.mapped else "--unmapped" for p, pf in iter_project(folder): align_opts = [ecoli] + p + [tag] align_opts += ["--cutoff={0}".format(opts.cutoff), "--null"] if opts.mateorientation: align_opts += ["--mateorientation={0}".format(opts.mateorientation)] samfile, logfile = align(align_opts)
python
def contamination(args): """ %prog contamination folder Ecoli.fasta Remove contaminated reads. The FASTQ files in the folder will automatically pair and filtered against Ecoli.fasta to remove contaminants using BOWTIE2. """ from jcvi.apps.bowtie import align p = OptionParser(contamination.__doc__) p.add_option("--mapped", default=False, action="store_true", help="Retain contaminated reads instead [default: %default]") p.set_cutoff(cutoff=800) p.set_mateorientation(mateorientation="+-") opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) folder, ecoli = args ecoli = get_abs_path(ecoli) tag = "--mapped" if opts.mapped else "--unmapped" for p, pf in iter_project(folder): align_opts = [ecoli] + p + [tag] align_opts += ["--cutoff={0}".format(opts.cutoff), "--null"] if opts.mateorientation: align_opts += ["--mateorientation={0}".format(opts.mateorientation)] samfile, logfile = align(align_opts)
[ "def", "contamination", "(", "args", ")", ":", "from", "jcvi", ".", "apps", ".", "bowtie", "import", "align", "p", "=", "OptionParser", "(", "contamination", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--mapped\"", ",", "default", "=", "False", ...
%prog contamination folder Ecoli.fasta Remove contaminated reads. The FASTQ files in the folder will automatically pair and filtered against Ecoli.fasta to remove contaminants using BOWTIE2.
[ "%prog", "contamination", "folder", "Ecoli", ".", "fasta" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/automaton.py#L132-L159
train
200,514
tanghaibao/jcvi
jcvi/assembly/automaton.py
pairs
def pairs(args): """ %prog pairs folder reference.fasta Estimate insert size distribution. Compatible with a variety of aligners, including BOWTIE and BWA. """ p = OptionParser(pairs.__doc__) p.set_firstN() p.set_mates() p.set_aligner() opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) cwd = os.getcwd() aligner = opts.aligner work = "-".join(("pairs", aligner)) mkdir(work) from jcvi.formats.sam import pairs as ps if aligner == "bowtie": from jcvi.apps.bowtie import align elif aligner == "bwa": from jcvi.apps.bwa import align folder, ref = args ref = get_abs_path(ref) messages = [] for p, prefix in iter_project(folder): samplefq = [] for i in range(2): samplefq.append(op.join(work, prefix + "_{0}.first.fastq".format(i+1))) first([str(opts.firstN)] + [p[i]] + ["-o", samplefq[i]]) os.chdir(work) align_args = [ref] + [op.basename(fq) for fq in samplefq] outfile, logfile = align(align_args) bedfile, stats = ps([outfile, "--rclip={0}".format(opts.rclip)]) os.chdir(cwd) median = stats.median tag = "MP" if median > 1000 else "PE" median = str(median) pf, sf = median[:2], median[2:] if sf and int(sf) != 0: pf = str(int(pf) + 1) # Get the first two effective digits lib = "{0}-{1}".format(tag, pf + '0' * len(sf)) for i, xp in enumerate(p): suffix = "fastq.gz" if xp.endswith(".gz") else "fastq" link = "{0}-{1}.{2}.{3}".format(lib, prefix.replace("-", ""), i + 1, suffix) m = "\t".join(str(x) for x in (xp, link)) messages.append(m) messages = "\n".join(messages) write_file("f.meta", messages, tee=True)
python
def pairs(args): """ %prog pairs folder reference.fasta Estimate insert size distribution. Compatible with a variety of aligners, including BOWTIE and BWA. """ p = OptionParser(pairs.__doc__) p.set_firstN() p.set_mates() p.set_aligner() opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) cwd = os.getcwd() aligner = opts.aligner work = "-".join(("pairs", aligner)) mkdir(work) from jcvi.formats.sam import pairs as ps if aligner == "bowtie": from jcvi.apps.bowtie import align elif aligner == "bwa": from jcvi.apps.bwa import align folder, ref = args ref = get_abs_path(ref) messages = [] for p, prefix in iter_project(folder): samplefq = [] for i in range(2): samplefq.append(op.join(work, prefix + "_{0}.first.fastq".format(i+1))) first([str(opts.firstN)] + [p[i]] + ["-o", samplefq[i]]) os.chdir(work) align_args = [ref] + [op.basename(fq) for fq in samplefq] outfile, logfile = align(align_args) bedfile, stats = ps([outfile, "--rclip={0}".format(opts.rclip)]) os.chdir(cwd) median = stats.median tag = "MP" if median > 1000 else "PE" median = str(median) pf, sf = median[:2], median[2:] if sf and int(sf) != 0: pf = str(int(pf) + 1) # Get the first two effective digits lib = "{0}-{1}".format(tag, pf + '0' * len(sf)) for i, xp in enumerate(p): suffix = "fastq.gz" if xp.endswith(".gz") else "fastq" link = "{0}-{1}.{2}.{3}".format(lib, prefix.replace("-", ""), i + 1, suffix) m = "\t".join(str(x) for x in (xp, link)) messages.append(m) messages = "\n".join(messages) write_file("f.meta", messages, tee=True)
[ "def", "pairs", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "pairs", ".", "__doc__", ")", "p", ".", "set_firstN", "(", ")", "p", ".", "set_mates", "(", ")", "p", ".", "set_aligner", "(", ")", "opts", ",", "args", "=", "p", ".", "parse_a...
%prog pairs folder reference.fasta Estimate insert size distribution. Compatible with a variety of aligners, including BOWTIE and BWA.
[ "%prog", "pairs", "folder", "reference", ".", "fasta" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/automaton.py#L162-L219
train
200,515
tanghaibao/jcvi
jcvi/assembly/automaton.py
allpaths
def allpaths(args): """ %prog allpaths folder1 folder2 ... Run automated ALLPATHS on list of dirs. """ p = OptionParser(allpaths.__doc__) p.add_option("--ploidy", default="1", choices=("1", "2"), help="Ploidy [default: %default]") opts, args = p.parse_args(args) if len(args) == 0: sys.exit(not p.print_help()) folders = args for pf in folders: if not op.isdir(pf): continue assemble_dir(pf, target=["final.contigs.fasta", "final.assembly.fasta"], ploidy=opts.ploidy)
python
def allpaths(args): """ %prog allpaths folder1 folder2 ... Run automated ALLPATHS on list of dirs. """ p = OptionParser(allpaths.__doc__) p.add_option("--ploidy", default="1", choices=("1", "2"), help="Ploidy [default: %default]") opts, args = p.parse_args(args) if len(args) == 0: sys.exit(not p.print_help()) folders = args for pf in folders: if not op.isdir(pf): continue assemble_dir(pf, target=["final.contigs.fasta", "final.assembly.fasta"], ploidy=opts.ploidy)
[ "def", "allpaths", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "allpaths", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--ploidy\"", ",", "default", "=", "\"1\"", ",", "choices", "=", "(", "\"1\"", ",", "\"2\"", ")", ",", "help", "=...
%prog allpaths folder1 folder2 ... Run automated ALLPATHS on list of dirs.
[ "%prog", "allpaths", "folder1", "folder2", "..." ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/automaton.py#L222-L241
train
200,516
tanghaibao/jcvi
jcvi/assembly/automaton.py
prepare
def prepare(args): """ %prog prepare jira.txt Parse JIRA report and prepare input. Look for all FASTQ files in the report and get the prefix. Assign fastq to a folder and a new file name indicating the library type (e.g. PE-500, MP-5000, etc.). Note that JIRA report can also be a list of FASTQ files. """ p = OptionParser(prepare.__doc__) p.add_option("--first", default=0, type="int", help="Use only first N reads [default: %default]") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) jfile, = args metafile = jfile + ".meta" if need_update(jfile, metafile): fp = open(jfile) fastqfiles = [x.strip() for x in fp if ".fastq" in x] metas = [Meta(x) for x in fastqfiles] fw = open(metafile, "w") print("\n".join(str(x) for x in metas), file=fw) print("Now modify `{0}`, and restart this script.".\ format(metafile), file=sys.stderr) print("Each line is : genome library fastqfile", file=sys.stderr) fw.close() return mf = MetaFile(metafile) for m in mf: m.make_link(firstN=opts.first)
python
def prepare(args): """ %prog prepare jira.txt Parse JIRA report and prepare input. Look for all FASTQ files in the report and get the prefix. Assign fastq to a folder and a new file name indicating the library type (e.g. PE-500, MP-5000, etc.). Note that JIRA report can also be a list of FASTQ files. """ p = OptionParser(prepare.__doc__) p.add_option("--first", default=0, type="int", help="Use only first N reads [default: %default]") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) jfile, = args metafile = jfile + ".meta" if need_update(jfile, metafile): fp = open(jfile) fastqfiles = [x.strip() for x in fp if ".fastq" in x] metas = [Meta(x) for x in fastqfiles] fw = open(metafile, "w") print("\n".join(str(x) for x in metas), file=fw) print("Now modify `{0}`, and restart this script.".\ format(metafile), file=sys.stderr) print("Each line is : genome library fastqfile", file=sys.stderr) fw.close() return mf = MetaFile(metafile) for m in mf: m.make_link(firstN=opts.first)
[ "def", "prepare", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "prepare", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--first\"", ",", "default", "=", "0", ",", "type", "=", "\"int\"", ",", "help", "=", "\"Use only first N reads [default:...
%prog prepare jira.txt Parse JIRA report and prepare input. Look for all FASTQ files in the report and get the prefix. Assign fastq to a folder and a new file name indicating the library type (e.g. PE-500, MP-5000, etc.). Note that JIRA report can also be a list of FASTQ files.
[ "%prog", "prepare", "jira", ".", "txt" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/automaton.py#L244-L280
train
200,517
tanghaibao/jcvi
jcvi/assembly/automaton.py
assemble_pairs
def assemble_pairs(p, pf, tag, target=["final.contigs.fasta"]): """ Take one pair of reads and assemble to contigs.fasta. """ slink(p, pf, tag) assemble_dir(pf, target)
python
def assemble_pairs(p, pf, tag, target=["final.contigs.fasta"]): """ Take one pair of reads and assemble to contigs.fasta. """ slink(p, pf, tag) assemble_dir(pf, target)
[ "def", "assemble_pairs", "(", "p", ",", "pf", ",", "tag", ",", "target", "=", "[", "\"final.contigs.fasta\"", "]", ")", ":", "slink", "(", "p", ",", "pf", ",", "tag", ")", "assemble_dir", "(", "pf", ",", "target", ")" ]
Take one pair of reads and assemble to contigs.fasta.
[ "Take", "one", "pair", "of", "reads", "and", "assemble", "to", "contigs", ".", "fasta", "." ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/automaton.py#L307-L312
train
200,518
tanghaibao/jcvi
jcvi/assembly/automaton.py
soap_trios
def soap_trios(p, pf, tag, extra): """ Take one pair of reads and 'widow' reads after correction and run SOAP. """ 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() os.chdir(pf) prepare(sorted(glob("*.fastq") + glob("*.fastq.gz")) + \ ["--assemble_1st_rank_only", "-K 31"]) sh("./run.sh") sh("cp asm31.closed.scafSeq ../{0}".format(asm)) logging.debug("Assembly finished: {0}".format(asm)) os.chdir(cwd)
python
def soap_trios(p, pf, tag, extra): """ Take one pair of reads and 'widow' reads after correction and run SOAP. """ 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() os.chdir(pf) prepare(sorted(glob("*.fastq") + glob("*.fastq.gz")) + \ ["--assemble_1st_rank_only", "-K 31"]) sh("./run.sh") sh("cp asm31.closed.scafSeq ../{0}".format(asm)) logging.debug("Assembly finished: {0}".format(asm)) os.chdir(cwd)
[ "def", "soap_trios", "(", "p", ",", "pf", ",", "tag", ",", "extra", ")", ":", "from", "jcvi", ".", "assembly", ".", "soap", "import", "prepare", "logging", ".", "debug", "(", "\"Work on {0} ({1})\"", ".", "format", "(", "pf", ",", "','", ".", "join", ...
Take one pair of reads and 'widow' reads after correction and run SOAP.
[ "Take", "one", "pair", "of", "reads", "and", "widow", "reads", "after", "correction", "and", "run", "SOAP", "." ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/automaton.py#L365-L387
train
200,519
tanghaibao/jcvi
jcvi/assembly/automaton.py
correctX
def correctX(args): """ %prog correctX folder tag Run ALLPATHS correction on a folder of paired reads and apply tag. """ 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)
python
def correctX(args): """ %prog correctX folder tag Run ALLPATHS correction on a folder of paired reads and apply tag. """ 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", ")", ":", "p", "=", "OptionParser", "(", "correctX", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", "2", ":", "sys", ".", "exit", "(", ...
%prog correctX folder tag Run ALLPATHS correction on a folder of paired reads and apply tag.
[ "%prog", "correctX", "folder", "tag" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/automaton.py#L425-L440
train
200,520
tanghaibao/jcvi
jcvi/assembly/automaton.py
allpathsX
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 """ 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)
python
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 """ 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", ")", ":", "p", "=", "OptionParser", "(", "allpathsX", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", "2", ":", "sys", ".", "exit", "("...
%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
[ "%prog", "allpathsX", "folder", "tag" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/automaton.py#L443-L459
train
200,521
tanghaibao/jcvi
jcvi/apps/uclust.py
stats
def stats(args): """ %prog stats folder Generate table summarizing .stats files. """ 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() contents = [] # label=M0096 total=7443 cnts=948 mean=7.851 std=35.96 for statsfile in statsfiles: fp = open(statsfile) for row in fp: if row.startswith("label="): break label, total, cnts = row.split()[:3] label = after_equal(label) reads = int(after_equal(total)) contigs = int(after_equal(cnts)) contents.append((label, reads, contigs)) all_labels, all_reads, all_contigs = zip(*contents) contents.append(("SUM", sum(all_reads), sum(all_contigs))) contents.append(("AVERAGE (per sample)", \ int(np.mean(all_reads)), int(np.mean(all_contigs)))) contents.append(("MEDIAN (per sample)", \ int(np.median(all_reads)), int(np.median(all_contigs)))) write_csv(header, contents, filename=opts.outfile)
python
def stats(args): """ %prog stats folder Generate table summarizing .stats files. """ 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() contents = [] # label=M0096 total=7443 cnts=948 mean=7.851 std=35.96 for statsfile in statsfiles: fp = open(statsfile) for row in fp: if row.startswith("label="): break label, total, cnts = row.split()[:3] label = after_equal(label) reads = int(after_equal(total)) contigs = int(after_equal(cnts)) contents.append((label, reads, contigs)) all_labels, all_reads, all_contigs = zip(*contents) contents.append(("SUM", sum(all_reads), sum(all_contigs))) contents.append(("AVERAGE (per sample)", \ int(np.mean(all_reads)), int(np.mean(all_contigs)))) contents.append(("MEDIAN (per sample)", \ int(np.median(all_reads)), int(np.median(all_contigs)))) write_csv(header, contents, filename=opts.outfile)
[ "def", "stats", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "stats", ".", "__doc__", ")", "p", ".", "set_outfile", "(", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", "1", ...
%prog stats folder Generate table summarizing .stats files.
[ "%prog", "stats", "folder" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/uclust.py#L181-L217
train
200,522
tanghaibao/jcvi
jcvi/apps/uclust.py
stack
def stack(S): """ From list of bases at a site D, make counts of bases """ 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
python
def stack(S): """ From list of bases at a site D, make counts of bases """ 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", ")", ":", "S", ",", "nreps", "=", "zip", "(", "*", "S", ")", "S", "=", "np", ".", "array", "(", "[", "list", "(", "x", ")", "for", "x", "in", "S", "]", ")", "rows", ",", "cols", "=", "S", ".", "shape", "counts", ...
From list of bases at a site D, make counts of bases
[ "From", "list", "of", "bases", "at", "a", "site", "D", "make", "counts", "of", "bases" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/uclust.py#L612-L625
train
200,523
tanghaibao/jcvi
jcvi/apps/uclust.py
get_left_right
def get_left_right(seq): """ Find position of the first and last base """ cseq = seq.strip(GAPS) leftjust = seq.index(cseq[0]) rightjust = seq.rindex(cseq[-1]) return leftjust, rightjust
python
def get_left_right(seq): """ Find position of the first and last base """ cseq = seq.strip(GAPS) leftjust = seq.index(cseq[0]) rightjust = seq.rindex(cseq[-1]) return leftjust, rightjust
[ "def", "get_left_right", "(", "seq", ")", ":", "cseq", "=", "seq", ".", "strip", "(", "GAPS", ")", "leftjust", "=", "seq", ".", "index", "(", "cseq", "[", "0", "]", ")", "rightjust", "=", "seq", ".", "rindex", "(", "cseq", "[", "-", "1", "]", "...
Find position of the first and last base
[ "Find", "position", "of", "the", "first", "and", "last", "base" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/uclust.py#L628-L636
train
200,524
tanghaibao/jcvi
jcvi/apps/uclust.py
cons
def cons(f, mindepth): """ Makes a list of lists of reads at each site """ 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([seq, nrep]) # Make list for each site in sequences res = stack(S) yield [x[:4] for x in res if sum(x[:4]) >= mindepth]
python
def cons(f, mindepth): """ Makes a list of lists of reads at each site """ 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([seq, nrep]) # Make list for each site in sequences res = stack(S) yield [x[:4] for x in res if sum(x[:4]) >= mindepth]
[ "def", "cons", "(", "f", ",", "mindepth", ")", ":", "C", "=", "ClustFile", "(", "f", ")", "for", "data", "in", "C", ":", "names", ",", "seqs", ",", "nreps", "=", "zip", "(", "*", "data", ")", "total_nreps", "=", "sum", "(", "nreps", ")", "# Dep...
Makes a list of lists of reads at each site
[ "Makes", "a", "list", "of", "lists", "of", "reads", "at", "each", "site" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/uclust.py#L639-L658
train
200,525
tanghaibao/jcvi
jcvi/apps/uclust.py
estimateHE
def estimateHE(args): """ %prog estimateHE clustSfile Estimate heterozygosity (H) and error rate (E). Idea borrowed heavily from the PyRad paper. """ 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 `{0}` found. Computation skipped.".format(HEfile)) return HEfile D = [] for d in cons(clustSfile, opts.mindepth): D.extend(d) logging.debug("Computing base frequencies ...") P = makeP(D) C = makeC(D) logging.debug("Solving log-likelihood function ...") x0 = [.01, .001] # initital values H, E = scipy.optimize.fmin(LL, x0, args=(P, C)) fw = must_open(HEfile, "w") print(H, E, file=fw) fw.close() return HEfile
python
def estimateHE(args): """ %prog estimateHE clustSfile Estimate heterozygosity (H) and error rate (E). Idea borrowed heavily from the PyRad paper. """ 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 `{0}` found. Computation skipped.".format(HEfile)) return HEfile D = [] for d in cons(clustSfile, opts.mindepth): D.extend(d) logging.debug("Computing base frequencies ...") P = makeP(D) C = makeC(D) logging.debug("Solving log-likelihood function ...") x0 = [.01, .001] # initital values H, E = scipy.optimize.fmin(LL, x0, args=(P, C)) fw = must_open(HEfile, "w") print(H, E, file=fw) fw.close() return HEfile
[ "def", "estimateHE", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "estimateHE", ".", "__doc__", ")", "add_consensus_options", "(", "p", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "...
%prog estimateHE clustSfile Estimate heterozygosity (H) and error rate (E). Idea borrowed heavily from the PyRad paper.
[ "%prog", "estimateHE", "clustSfile" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/uclust.py#L733-L768
train
200,526
tanghaibao/jcvi
jcvi/apps/uclust.py
alignfast
def alignfast(names, seqs): """ Performs MUSCLE alignments on cluster and returns output as string """ 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" return p.communicate(s)[0]
python
def alignfast(names, seqs): """ Performs MUSCLE alignments on cluster and returns output as string """ 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" return p.communicate(s)[0]
[ "def", "alignfast", "(", "names", ",", "seqs", ")", ":", "matfile", "=", "op", ".", "join", "(", "datadir", ",", "\"blosum80.mat\"", ")", "cmd", "=", "\"poa -read_fasta - -pir stdout {0} -tolower -silent -hb -fuse_all\"", ".", "format", "(", "matfile", ")", "p", ...
Performs MUSCLE alignments on cluster and returns output as string
[ "Performs", "MUSCLE", "alignments", "on", "cluster", "and", "returns", "output", "as", "string" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/uclust.py#L771-L781
train
200,527
tanghaibao/jcvi
jcvi/apps/uclust.py
cluster
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>. """ 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.pctid mindepth = opts.mindepth minlength = opts.minlength fastafile, qualfile = fasta(fastqfiles + ["--seqtk", "--outdir={0}".format(opts.outdir), "--outfile={0}".format(prefix + ".fasta")]) prefix = op.join(opts.outdir, prefix) pf = prefix + ".P{0}".format(pctid) derepfile = prefix + ".derep" if need_update(fastafile, derepfile): derep(fastafile, derepfile, minlength, cpus) userfile = pf + ".u" notmatchedfile = pf + ".notmatched" if need_update(derepfile, userfile): cluster_smallmem(derepfile, userfile, notmatchedfile, minlength, pctid, cpus) clustfile = pf + ".clust" if need_update((derepfile, userfile, notmatchedfile), clustfile): makeclust(derepfile, userfile, notmatchedfile, clustfile, mindepth=mindepth) clustSfile = pf + ".clustS" if need_update(clustfile, clustSfile): parallel_musclewrap(clustfile, cpus) statsfile = pf + ".stats" if need_update(clustSfile, statsfile): makestats(clustSfile, statsfile, mindepth=mindepth)
python
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>. """ 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.pctid mindepth = opts.mindepth minlength = opts.minlength fastafile, qualfile = fasta(fastqfiles + ["--seqtk", "--outdir={0}".format(opts.outdir), "--outfile={0}".format(prefix + ".fasta")]) prefix = op.join(opts.outdir, prefix) pf = prefix + ".P{0}".format(pctid) derepfile = prefix + ".derep" if need_update(fastafile, derepfile): derep(fastafile, derepfile, minlength, cpus) userfile = pf + ".u" notmatchedfile = pf + ".notmatched" if need_update(derepfile, userfile): cluster_smallmem(derepfile, userfile, notmatchedfile, minlength, pctid, cpus) clustfile = pf + ".clust" if need_update((derepfile, userfile, notmatchedfile), clustfile): makeclust(derepfile, userfile, notmatchedfile, clustfile, mindepth=mindepth) clustSfile = pf + ".clustS" if need_update(clustfile, clustSfile): parallel_musclewrap(clustfile, cpus) statsfile = pf + ".stats" if need_update(clustSfile, statsfile): makestats(clustSfile, statsfile, mindepth=mindepth)
[ "def", "cluster", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "cluster", ".", "__doc__", ")", "add_consensus_options", "(", "p", ")", "p", ".", "set_align", "(", "pctid", "=", "95", ")", "p", ".", "set_outdir", "(", ")", "p", ".", "set_cpus...
%prog cluster prefix fastqfiles Use `vsearch` to remove duplicate reads. This routine is heavily influenced by PyRAD: <https://github.com/dereneaton/pyrad>.
[ "%prog", "cluster", "prefix", "fastqfiles" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/uclust.py#L972-L1022
train
200,528
tanghaibao/jcvi
jcvi/apps/uclust.py
align
def align(args): """ %prog align clustfile Align clustfile to clustSfile. Useful for benchmarking aligners. """ 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)
python
def align(args): """ %prog align clustfile Align clustfile to clustSfile. Useful for benchmarking aligners. """ 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", ")", ":", "p", "=", "OptionParser", "(", "align", ".", "__doc__", ")", "p", ".", "set_cpus", "(", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", "1", ":...
%prog align clustfile Align clustfile to clustSfile. Useful for benchmarking aligners.
[ "%prog", "align", "clustfile" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/uclust.py#L1025-L1039
train
200,529
tanghaibao/jcvi
jcvi/graphics/base.py
discrete_rainbow
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, cmap=djet) See available matplotlib colormaps at: <http://dept.astro.lsa.umich.edu/~msshin/science/code/matplotlib_cm/> If N>20 the sampled colors might not be very distinctive. If you want to error and try anyway, set usepreset=False """ 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.linspace(0,1.,N) # N+1 indices indices = np.linspace(0,1.,N+1) rgbs = [] for key in ('red','green','blue'): # Find the N colors D = np.array(cdict[key]) I = interpolate.interp1d(D[:,0], D[:,1]) colors = I(colors_i) rgbs.append(colors) # Place these colors at the correct indices. A = np.zeros((N+1,3), float) A[:,0] = indices A[1:,1] = colors A[:-1,2] = colors # Create a tuple for the dictionary. L = [] for l in A: L.append(tuple(l)) cdict[key] = tuple(L) palette = zip(*rgbs) if shuffle: random.shuffle(palette) if plot: print_colors(palette) # Return (colormap object, RGB tuples) return mpl.colors.LinearSegmentedColormap('colormap',cdict,1024), palette
python
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, cmap=djet) See available matplotlib colormaps at: <http://dept.astro.lsa.umich.edu/~msshin/science/code/matplotlib_cm/> If N>20 the sampled colors might not be very distinctive. If you want to error and try anyway, set usepreset=False """ 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.linspace(0,1.,N) # N+1 indices indices = np.linspace(0,1.,N+1) rgbs = [] for key in ('red','green','blue'): # Find the N colors D = np.array(cdict[key]) I = interpolate.interp1d(D[:,0], D[:,1]) colors = I(colors_i) rgbs.append(colors) # Place these colors at the correct indices. A = np.zeros((N+1,3), float) A[:,0] = indices A[1:,1] = colors A[:-1,2] = colors # Create a tuple for the dictionary. L = [] for l in A: L.append(tuple(l)) cdict[key] = tuple(L) palette = zip(*rgbs) if shuffle: random.shuffle(palette) if plot: print_colors(palette) # Return (colormap object, RGB tuples) return mpl.colors.LinearSegmentedColormap('colormap',cdict,1024), palette
[ "def", "discrete_rainbow", "(", "N", "=", "7", ",", "cmap", "=", "cm", ".", "Set1", ",", "usepreset", "=", "True", ",", "shuffle", "=", "False", ",", "plot", "=", "False", ")", ":", "import", "random", "from", "scipy", "import", "interpolate", "if", ...
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, cmap=djet) See available matplotlib colormaps at: <http://dept.astro.lsa.umich.edu/~msshin/science/code/matplotlib_cm/> If N>20 the sampled colors might not be very distinctive. If you want to error and try anyway, set usepreset=False
[ "Return", "a", "discrete", "colormap", "and", "the", "set", "of", "colors", "." ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/graphics/base.py#L348-L413
train
200,530
tanghaibao/jcvi
jcvi/graphics/base.py
write_messages
def write_messages(ax, messages): """ Write text on canvas, usually on the top right corner. """ tc = "gray" axt = ax.transAxes yy = .95 for msg in messages: ax.text(.95, yy, msg, color=tc, transform=axt, ha="right") yy -= .05
python
def write_messages(ax, messages): """ Write text on canvas, usually on the top right corner. """ 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", ")", ":", "tc", "=", "\"gray\"", "axt", "=", "ax", ".", "transAxes", "yy", "=", ".95", "for", "msg", "in", "messages", ":", "ax", ".", "text", "(", ".95", ",", "yy", ",", "msg", ",", "color", "...
Write text on canvas, usually on the top right corner.
[ "Write", "text", "on", "canvas", "usually", "on", "the", "top", "right", "corner", "." ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/graphics/base.py#L469-L478
train
200,531
tanghaibao/jcvi
jcvi/graphics/base.py
quickplot
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. """ 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", va="bottom", rotation=90) if xmax is None: xmax = max(left) plt.bar(left, height, align="center") plt.xlabel(markup(xlabel)) plt.ylabel(markup(ylabel)) plt.title(markup(title)) plt.xlim((xmin - .5, xmax + .5)) # Basic statistics messages = [] counts_over_xmax = sum([v for k, v in data.items() if k > xmax]) if counts_over_xmax: messages += ["Counts over xmax({0}): {1}".format(xmax, counts_over_xmax)] kk = [] for k, v in data.items(): kk += [k] * v messages += ["Total: {0}".format(np.sum(height))] messages += ["Maximum: {0}".format(np.max(kk))] messages += ["Minimum: {0}".format(np.min(kk))] messages += ["Average: {0:.2f}".format(np.mean(kk))] messages += ["Median: {0}".format(np.median(kk))] ax = plt.gca() if print_stats: write_messages(ax, messages) set_human_axis(ax) set_ticklabels_helvetica(ax) savefig(figname)
python
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. """ 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", va="bottom", rotation=90) if xmax is None: xmax = max(left) plt.bar(left, height, align="center") plt.xlabel(markup(xlabel)) plt.ylabel(markup(ylabel)) plt.title(markup(title)) plt.xlim((xmin - .5, xmax + .5)) # Basic statistics messages = [] counts_over_xmax = sum([v for k, v in data.items() if k > xmax]) if counts_over_xmax: messages += ["Counts over xmax({0}): {1}".format(xmax, counts_over_xmax)] kk = [] for k, v in data.items(): kk += [k] * v messages += ["Total: {0}".format(np.sum(height))] messages += ["Maximum: {0}".format(np.max(kk))] messages += ["Minimum: {0}".format(np.min(kk))] messages += ["Average: {0:.2f}".format(np.mean(kk))] messages += ["Median: {0}".format(np.median(kk))] ax = plt.gca() if print_stats: write_messages(ax, messages) set_human_axis(ax) set_ticklabels_helvetica(ax) savefig(figname)
[ "def", "quickplot", "(", "data", ",", "xmin", ",", "xmax", ",", "xlabel", ",", "title", ",", "ylabel", "=", "\"Counts\"", ",", "figname", "=", "\"plot.pdf\"", ",", "counts", "=", "True", ",", "print_stats", "=", "True", ")", ":", "plt", ".", "figure", ...
Simple plotting function - given a dictionary of data, produce a bar plot with the counts shown on the plot.
[ "Simple", "plotting", "function", "-", "given", "a", "dictionary", "of", "data", "produce", "a", "bar", "plot", "with", "the", "counts", "shown", "on", "the", "plot", "." ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/graphics/base.py#L525-L568
train
200,532
tanghaibao/jcvi
jcvi/formats/sbt.py
get_name_parts
def get_name_parts(au): """ Fares Z. Najar => last, first, initials >>> get_name_parts("Fares Z. Najar") ('Najar', 'Fares', 'F.Z.') """ 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 middle, last = last.split(None, 1) initials = "{0}.{1}.".format(first[0], middle) return last, first, initials
python
def get_name_parts(au): """ Fares Z. Najar => last, first, initials >>> get_name_parts("Fares Z. Najar") ('Najar', 'Fares', 'F.Z.') """ 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 middle, last = last.split(None, 1) initials = "{0}.{1}.".format(first[0], middle) return last, first, initials
[ "def", "get_name_parts", "(", "au", ")", ":", "parts", "=", "au", ".", "split", "(", ")", "first", "=", "parts", "[", "0", "]", "middle", "=", "[", "x", "for", "x", "in", "parts", "if", "x", "[", "-", "1", "]", "==", "'.'", "]", "middle", "="...
Fares Z. Najar => last, first, initials >>> get_name_parts("Fares Z. Najar") ('Najar', 'Fares', 'F.Z.')
[ "Fares", "Z", ".", "Najar", "=", ">", "last", "first", "initials" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/sbt.py#L41-L60
train
200,533
tanghaibao/jcvi
jcvi/formats/sbt.py
names
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 the `$N0` field in the template file, second to the `$N1` field, etc. In the alternative mode, the namelist just contains several sections. First row will go in the `$N0` in the template file, second to the `$N1` field. The namelist may look like: [Sequence] Bruce A. Roe, Frederic Debelle, Giles Oldroyd, Rene Geurts [Manuscript] Haibao Tang1, Vivek Krishnakumar1, Shelby Bidwell1, Benjamin Rosen1 Then in this example Sequence section goes into N0, Manuscript goes into N1. Useful hints for constructing the template file can be found in: <http://www.ncbi.nlm.nih.gov/IEB/ToolBox/CPP_DOC/asn_spec/seq.asn.html> Often the template file can be retrieved from web form: <http://www.ncbi.nlm.nih.gov/WebSub/template.cgi> """ 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(templatefile, out) return reader = csv.reader(open(namelist), delimiter="\t") header = next(reader) ncols = len(header) assert ncols > 3 nextras = ncols - 3 blocks = [] bools = [] for row in reader: first, middle, last = row[:3] extras = row[3:] bools.append([(x.upper() == 'Y') for x in extras]) middle = middle.strip() if middle != "": middle = middle.rstrip('.') + '.' initials = "{0}.{1}".format(first[0], middle) suffix = "" nameblock = NameTemplate.format(last=last, first=first, initials=initials, suffix=suffix) blocks.append(nameblock) selected_idx = zip(*bools) out = [] * nextras for i, sbools in enumerate(selected_idx): selected = [] for b, ss in zip(blocks, sbools): if ss: selected.append(b) bigblock = ",\n".join(selected) out.append(bigblock) logging.debug("List N{0} contains a total of {1} names.".format(i, len(selected))) make_template(templatefile, out)
python
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 the `$N0` field in the template file, second to the `$N1` field, etc. In the alternative mode, the namelist just contains several sections. First row will go in the `$N0` in the template file, second to the `$N1` field. The namelist may look like: [Sequence] Bruce A. Roe, Frederic Debelle, Giles Oldroyd, Rene Geurts [Manuscript] Haibao Tang1, Vivek Krishnakumar1, Shelby Bidwell1, Benjamin Rosen1 Then in this example Sequence section goes into N0, Manuscript goes into N1. Useful hints for constructing the template file can be found in: <http://www.ncbi.nlm.nih.gov/IEB/ToolBox/CPP_DOC/asn_spec/seq.asn.html> Often the template file can be retrieved from web form: <http://www.ncbi.nlm.nih.gov/WebSub/template.cgi> """ 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(templatefile, out) return reader = csv.reader(open(namelist), delimiter="\t") header = next(reader) ncols = len(header) assert ncols > 3 nextras = ncols - 3 blocks = [] bools = [] for row in reader: first, middle, last = row[:3] extras = row[3:] bools.append([(x.upper() == 'Y') for x in extras]) middle = middle.strip() if middle != "": middle = middle.rstrip('.') + '.' initials = "{0}.{1}".format(first[0], middle) suffix = "" nameblock = NameTemplate.format(last=last, first=first, initials=initials, suffix=suffix) blocks.append(nameblock) selected_idx = zip(*bools) out = [] * nextras for i, sbools in enumerate(selected_idx): selected = [] for b, ss in zip(blocks, sbools): if ss: selected.append(b) bigblock = ",\n".join(selected) out.append(bigblock) logging.debug("List N{0} contains a total of {1} names.".format(i, len(selected))) make_template(templatefile, out)
[ "def", "names", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "names", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", "2", ":", "sys", ".", "exit", "(", "p",...
%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 the `$N0` field in the template file, second to the `$N1` field, etc. In the alternative mode, the namelist just contains several sections. First row will go in the `$N0` in the template file, second to the `$N1` field. The namelist may look like: [Sequence] Bruce A. Roe, Frederic Debelle, Giles Oldroyd, Rene Geurts [Manuscript] Haibao Tang1, Vivek Krishnakumar1, Shelby Bidwell1, Benjamin Rosen1 Then in this example Sequence section goes into N0, Manuscript goes into N1. Useful hints for constructing the template file can be found in: <http://www.ncbi.nlm.nih.gov/IEB/ToolBox/CPP_DOC/asn_spec/seq.asn.html> Often the template file can be retrieved from web form: <http://www.ncbi.nlm.nih.gov/WebSub/template.cgi>
[ "%prog", "names", "namelist", "templatefile" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/sbt.py#L108-L182
train
200,534
tanghaibao/jcvi
jcvi/apps/script.py
main
def main(): """ %prog scriptname.py create a minimal boilerplate for a new script """ 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 opts.graphic else default_imports app = graphic_app if opts.graphic else default_app template = default_template.format(imports, app) write_file(script, template) message = "template writes to `{0}`".format(script) if opts.graphic: message = "graphic " + message message = message[0].upper() + message[1:] logging.debug(message)
python
def main(): """ %prog scriptname.py create a minimal boilerplate for a new script """ 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 opts.graphic else default_imports app = graphic_app if opts.graphic else default_app template = default_template.format(imports, app) write_file(script, template) message = "template writes to `{0}`".format(script) if opts.graphic: message = "graphic " + message message = message[0].upper() + message[1:] logging.debug(message)
[ "def", "main", "(", ")", ":", "p", "=", "OptionParser", "(", "main", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"-g\"", ",", "\"--graphic\"", ",", "default", "=", "False", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Create boilerp...
%prog scriptname.py create a minimal boilerplate for a new script
[ "%prog", "scriptname", ".", "py" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/script.py#L79-L103
train
200,535
tanghaibao/jcvi
jcvi/variation/deconvolute.py
unpack_ambiguous
def unpack_ambiguous(s): """ List sequences with ambiguous characters in all possibilities. """ sd = [ambiguous_dna_values[x] for x in s] return ["".join(x) for x in list(product(*sd))]
python
def unpack_ambiguous(s): """ List sequences with ambiguous characters in all possibilities. """ sd = [ambiguous_dna_values[x] for x in s] return ["".join(x) for x in list(product(*sd))]
[ "def", "unpack_ambiguous", "(", "s", ")", ":", "sd", "=", "[", "ambiguous_dna_values", "[", "x", "]", "for", "x", "in", "s", "]", "return", "[", "\"\"", ".", "join", "(", "x", ")", "for", "x", "in", "list", "(", "product", "(", "*", "sd", ")", ...
List sequences with ambiguous characters in all possibilities.
[ "List", "sequences", "with", "ambiguous", "characters", "in", "all", "possibilities", "." ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/deconvolute.py#L39-L44
train
200,536
tanghaibao/jcvi
jcvi/variation/deconvolute.py
split
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. When --paired is set, the number of input fastqfiles must be two. Output file (the deconvoluted reads) will be in interleaved format. """ 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 data [default: %default]") p.add_option("--append", default=False, action="store_true", help="Append barcode to 2nd read [default: %default]") p.set_cpus() opts, args = p.parse_args(args) if len(args) < 2: sys.exit(not p.print_help()) barcodefile = args[0] fastqfile = args[1:] paired = opts.paired append = opts.append if append: assert paired, "--append only works with --paired" nfiles = len(fastqfile) barcodes = [] fp = open(barcodefile) for row in fp: id, seq = row.split() for s in unpack_ambiguous(seq): barcodes.append(BarcodeLine._make((id, s))) nbc = len(barcodes) logging.debug("Imported {0} barcodes (ambiguous codes expanded).".format(nbc)) checkprefix = not opts.nocheckprefix if checkprefix: # Sanity check of shared prefix excludebarcodes = [] for bc in barcodes: exclude = [] for s in barcodes: if bc.id == s.id: continue assert bc.seq != s.seq if s.seq.startswith(bc.seq) and len(s.seq) > len(bc.seq): logging.error("{0} shares same prefix as {1}.".format(s, bc)) exclude.append(s) excludebarcodes.append(exclude) else: excludebarcodes = nbc * [[]] outdir = opts.outdir mkdir(outdir) cpus = opts.cpus logging.debug("Create a pool of {0} workers.".format(cpus)) pool = Pool(cpus) if paired: assert nfiles == 2, "You asked for --paired, but sent in {0} files".\ format(nfiles) split_fun = append_barcode_paired if append else split_barcode_paired mode = "paired" else: split_fun = split_barcode mode = "single" logging.debug("Mode: {0}".format(mode)) pool.map(split_fun, \ zip(barcodes, excludebarcodes, nbc * [outdir], nbc * [fastqfile]))
python
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. When --paired is set, the number of input fastqfiles must be two. Output file (the deconvoluted reads) will be in interleaved format. """ 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 data [default: %default]") p.add_option("--append", default=False, action="store_true", help="Append barcode to 2nd read [default: %default]") p.set_cpus() opts, args = p.parse_args(args) if len(args) < 2: sys.exit(not p.print_help()) barcodefile = args[0] fastqfile = args[1:] paired = opts.paired append = opts.append if append: assert paired, "--append only works with --paired" nfiles = len(fastqfile) barcodes = [] fp = open(barcodefile) for row in fp: id, seq = row.split() for s in unpack_ambiguous(seq): barcodes.append(BarcodeLine._make((id, s))) nbc = len(barcodes) logging.debug("Imported {0} barcodes (ambiguous codes expanded).".format(nbc)) checkprefix = not opts.nocheckprefix if checkprefix: # Sanity check of shared prefix excludebarcodes = [] for bc in barcodes: exclude = [] for s in barcodes: if bc.id == s.id: continue assert bc.seq != s.seq if s.seq.startswith(bc.seq) and len(s.seq) > len(bc.seq): logging.error("{0} shares same prefix as {1}.".format(s, bc)) exclude.append(s) excludebarcodes.append(exclude) else: excludebarcodes = nbc * [[]] outdir = opts.outdir mkdir(outdir) cpus = opts.cpus logging.debug("Create a pool of {0} workers.".format(cpus)) pool = Pool(cpus) if paired: assert nfiles == 2, "You asked for --paired, but sent in {0} files".\ format(nfiles) split_fun = append_barcode_paired if append else split_barcode_paired mode = "paired" else: split_fun = split_barcode mode = "single" logging.debug("Mode: {0}".format(mode)) pool.map(split_fun, \ zip(barcodes, excludebarcodes, nbc * [outdir], nbc * [fastqfile]))
[ "def", "split", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "split", ".", "__doc__", ")", "p", ".", "set_outdir", "(", "outdir", "=", "\"deconv\"", ")", "p", ".", "add_option", "(", "\"--nocheckprefix\"", ",", "default", "=", "False", ",", "a...
%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. When --paired is set, the number of input fastqfiles must be two. Output file (the deconvoluted reads) will be in interleaved format.
[ "%prog", "split", "barcodefile", "fastqfile1", ".." ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/deconvolute.py#L131-L216
train
200,537
tanghaibao/jcvi
jcvi/variation/deconvolute.py
merge
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. """ 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 = list(files) key = lambda x: op.basename(x).split(".")[0] files.sort(key=key) for id, fns in groupby(files, key=key): fns = list(fns) outfile = op.join(outdir, "{0}.fastq".format(id)) FileMerger(fns, outfile=outfile).merge(checkexists=True)
python
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. """ 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 = list(files) key = lambda x: op.basename(x).split(".")[0] files.sort(key=key) for id, fns in groupby(files, key=key): fns = list(fns) outfile = op.join(outdir, "{0}.fastq".format(id)) FileMerger(fns, outfile=outfile).merge(checkexists=True)
[ "def", "merge", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "merge", ".", "__doc__", ")", "p", ".", "set_outdir", "(", "outdir", "=", "\"outdir\"", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(",...
%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.
[ "%prog", "merge", "folder1", "..." ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/deconvolute.py#L219-L245
train
200,538
tanghaibao/jcvi
jcvi/projects/str.py
expand_alleles
def expand_alleles(p, tolerance=0): """ Returns expanded allele set given the tolerance. """ _p = set() for x in p: _p |= set(range(x - tolerance, x + tolerance + 1)) return _p
python
def expand_alleles(p, tolerance=0): """ Returns expanded allele set given the tolerance. """ _p = set() for x in p: _p |= set(range(x - tolerance, x + tolerance + 1)) return _p
[ "def", "expand_alleles", "(", "p", ",", "tolerance", "=", "0", ")", ":", "_p", "=", "set", "(", ")", "for", "x", "in", "p", ":", "_p", "|=", "set", "(", "range", "(", "x", "-", "tolerance", ",", "x", "+", "tolerance", "+", "1", ")", ")", "ret...
Returns expanded allele set given the tolerance.
[ "Returns", "expanded", "allele", "set", "given", "the", "tolerance", "." ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/str.py#L127-L134
train
200,539
tanghaibao/jcvi
jcvi/projects/str.py
get_progenies
def get_progenies(p1, p2, x_linked=False, tolerance=0): """ Returns possible progenies in a trio. """ _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_progenies
python
def get_progenies(p1, p2, x_linked=False, tolerance=0): """ Returns possible progenies in a trio. """ _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_progenies
[ "def", "get_progenies", "(", "p1", ",", "p2", ",", "x_linked", "=", "False", ",", "tolerance", "=", "0", ")", ":", "_p1", "=", "expand_alleles", "(", "p1", ",", "tolerance", "=", "tolerance", ")", "_p2", "=", "expand_alleles", "(", "p2", ",", "toleranc...
Returns possible progenies in a trio.
[ "Returns", "possible", "progenies", "in", "a", "trio", "." ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/str.py#L137-L146
train
200,540
tanghaibao/jcvi
jcvi/projects/str.py
mendelian_errors2
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,11,0,1.4% """ 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)) root = fig.add_axes([0, 0, 1, 1]) ymin = -.2 df = pd.read_csv(csvfile) data = [] for i, d in df.iterrows(): tred = d['Name'] motif = d['Motif'] if tred in ignore: logging.debug("Ignore {}".format(d['TRED'])) continue if len(motif) > 6: if "/" in motif: # CTG/CAG motif = motif.split("/")[0] else: motif = motif[:6] + ".." xtred = "{} {}".format(tred, motif) accuracy = d[-1] data.append((xtred, accuracy)) key = lambda x: float(x.rstrip('%')) data.sort(key=lambda x: key(x[-1])) print(data) treds, accuracies = zip(*data) ntreds = len(treds) ticks = range(ntreds) accuracies = [key(x) for x in accuracies] for tick, accuracy in zip(ticks, accuracies): ax.plot([tick, tick], [ymin, accuracy], "-", lw=2, color='lightslategray') trios, = ax.plot(accuracies, "o", mfc='w', mec='b') ax.set_title("Mendelian errors based on STR calls in trios in HLI samples") ntrios = "Mendelian errors in 802 trios" ax.legend([trios], [ntrios], loc='best') ax.set_xticks(ticks) ax.set_xticklabels(treds, rotation=45, ha="right", size=8) ax.set_yticklabels([int(x) for x in ax.get_yticks()], family='Helvetica') ax.set_ylabel("Mendelian errors (\%)") ax.set_ylim(ymin, 100) normalize_axes(root) image_name = "mendelian_errors2." + iopts.format savefig(image_name, dpi=iopts.dpi, iopts=iopts)
python
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,11,0,1.4% """ 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)) root = fig.add_axes([0, 0, 1, 1]) ymin = -.2 df = pd.read_csv(csvfile) data = [] for i, d in df.iterrows(): tred = d['Name'] motif = d['Motif'] if tred in ignore: logging.debug("Ignore {}".format(d['TRED'])) continue if len(motif) > 6: if "/" in motif: # CTG/CAG motif = motif.split("/")[0] else: motif = motif[:6] + ".." xtred = "{} {}".format(tred, motif) accuracy = d[-1] data.append((xtred, accuracy)) key = lambda x: float(x.rstrip('%')) data.sort(key=lambda x: key(x[-1])) print(data) treds, accuracies = zip(*data) ntreds = len(treds) ticks = range(ntreds) accuracies = [key(x) for x in accuracies] for tick, accuracy in zip(ticks, accuracies): ax.plot([tick, tick], [ymin, accuracy], "-", lw=2, color='lightslategray') trios, = ax.plot(accuracies, "o", mfc='w', mec='b') ax.set_title("Mendelian errors based on STR calls in trios in HLI samples") ntrios = "Mendelian errors in 802 trios" ax.legend([trios], [ntrios], loc='best') ax.set_xticks(ticks) ax.set_xticklabels(treds, rotation=45, ha="right", size=8) ax.set_yticklabels([int(x) for x in ax.get_yticks()], family='Helvetica') ax.set_ylabel("Mendelian errors (\%)") ax.set_ylim(ymin, 100) normalize_axes(root) image_name = "mendelian_errors2." + iopts.format savefig(image_name, dpi=iopts.dpi, iopts=iopts)
[ "def", "mendelian_errors2", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "mendelian_errors2", ".", "__doc__", ")", "opts", ",", "args", ",", "iopts", "=", "p", ".", "set_image_options", "(", "args", ",", "figsize", "=", "\"7x7\"", ",", "format", ...
%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,11,0,1.4%
[ "%prog", "mendelian_errors2", "Trios", ".", "summary", ".", "csv" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/str.py#L196-L264
train
200,541
tanghaibao/jcvi
jcvi/projects/str.py
mendelian_check
def mendelian_check(tp1, tp2, tpp, is_xlinked=False): """ Compare TRED calls for Parent1, Parent2 and Proband. """ 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 tpp[2:]) tp1_call = call_to_ints(tp1_call) tp2_call = call_to_ints(tp2_call) tpp_call = call_to_ints(tpp_call) possible_progenies = set(tuple(sorted(x)) \ for x in product(tp1_call, tp2_call)) if is_xlinked and tpp_sex == "Male": possible_progenies = set(tuple((x,)) for x in tp1_call) if -1 in tp1_call or -1 in tp2_call or -1 in tpp_call: tag = "Missing" # elif tp1_evidence < 2 or tp2_evidence < 2 or tpp_evidence < 2: # tag = "Missing" else: tag = "Correct" if tpp_call in possible_progenies else "Error" return tag
python
def mendelian_check(tp1, tp2, tpp, is_xlinked=False): """ Compare TRED calls for Parent1, Parent2 and Proband. """ 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 tpp[2:]) tp1_call = call_to_ints(tp1_call) tp2_call = call_to_ints(tp2_call) tpp_call = call_to_ints(tpp_call) possible_progenies = set(tuple(sorted(x)) \ for x in product(tp1_call, tp2_call)) if is_xlinked and tpp_sex == "Male": possible_progenies = set(tuple((x,)) for x in tp1_call) if -1 in tp1_call or -1 in tp2_call or -1 in tpp_call: tag = "Missing" # elif tp1_evidence < 2 or tp2_evidence < 2 or tpp_evidence < 2: # tag = "Missing" else: tag = "Correct" if tpp_call in possible_progenies else "Error" return tag
[ "def", "mendelian_check", "(", "tp1", ",", "tp2", ",", "tpp", ",", "is_xlinked", "=", "False", ")", ":", "call_to_ints", "=", "lambda", "x", ":", "tuple", "(", "int", "(", "_", ")", "for", "_", "in", "x", ".", "split", "(", "\"|\"", ")", "if", "_...
Compare TRED calls for Parent1, Parent2 and Proband.
[ "Compare", "TRED", "calls", "for", "Parent1", "Parent2", "and", "Proband", "." ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/str.py#L398-L422
train
200,542
tanghaibao/jcvi
jcvi/projects/str.py
in_region
def in_region(rname, rstart, target_chr, target_start, target_end): """ Quick check if a point is within the target region. """ return (rname == target_chr) and \ (target_start <= rstart <= target_end)
python
def in_region(rname, rstart, target_chr, target_start, target_end): """ Quick check if a point is within the target region. """ return (rname == target_chr) and \ (target_start <= rstart <= target_end)
[ "def", "in_region", "(", "rname", ",", "rstart", ",", "target_chr", ",", "target_start", ",", "target_end", ")", ":", "return", "(", "rname", "==", "target_chr", ")", "and", "(", "target_start", "<=", "rstart", "<=", "target_end", ")" ]
Quick check if a point is within the target region.
[ "Quick", "check", "if", "a", "point", "is", "within", "the", "target", "region", "." ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/str.py#L425-L430
train
200,543
tanghaibao/jcvi
jcvi/projects/str.py
mendelian_errors
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 errors and trio errors. """ 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_axes([0, 0, 1, 1]) ymin = -.2 df = pd.read_csv(csvfile) data = [] for i, d in df.iterrows(): if d['TRED'].split()[0] in ignore: logging.debug("Ignore {}".format(d['TRED'])) continue data.append(d) treds, duos, trios = zip(*data) ntreds = len(treds) ticks = range(ntreds) treds = [x.split()[0] for x in treds] duos = [float(x.rstrip('%')) for x in duos] trios = [float(x.rstrip('%')) for x in trios] for tick, duo, trio in zip(ticks, duos, trios): m = max(duo, trio) ax.plot([tick, tick], [ymin, m], "-", lw=2, color='lightslategray') duos, = ax.plot(duos, "o", mfc='w', mec='g') trios, = ax.plot(trios, "o", mfc='w', mec='b') ax.set_title("Mendelian errors based on trios and duos in HLI samples") nduos = "Mendelian errors in 362 duos" ntrios = "Mendelian errors in 339 trios" ax.legend([trios, duos], [ntrios, nduos], loc='best') ax.set_xticks(ticks) ax.set_xticklabels(treds, rotation=45, ha="right", size=8) yticklabels = [int(x) for x in ax.get_yticks()] ax.set_yticklabels(yticklabels, family='Helvetica') ax.set_ylabel("Mendelian errors (\%)") ax.set_ylim(ymin, 20) normalize_axes(root) image_name = "mendelian_errors." + iopts.format savefig(image_name, dpi=iopts.dpi, iopts=iopts)
python
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 errors and trio errors. """ 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_axes([0, 0, 1, 1]) ymin = -.2 df = pd.read_csv(csvfile) data = [] for i, d in df.iterrows(): if d['TRED'].split()[0] in ignore: logging.debug("Ignore {}".format(d['TRED'])) continue data.append(d) treds, duos, trios = zip(*data) ntreds = len(treds) ticks = range(ntreds) treds = [x.split()[0] for x in treds] duos = [float(x.rstrip('%')) for x in duos] trios = [float(x.rstrip('%')) for x in trios] for tick, duo, trio in zip(ticks, duos, trios): m = max(duo, trio) ax.plot([tick, tick], [ymin, m], "-", lw=2, color='lightslategray') duos, = ax.plot(duos, "o", mfc='w', mec='g') trios, = ax.plot(trios, "o", mfc='w', mec='b') ax.set_title("Mendelian errors based on trios and duos in HLI samples") nduos = "Mendelian errors in 362 duos" ntrios = "Mendelian errors in 339 trios" ax.legend([trios, duos], [ntrios, nduos], loc='best') ax.set_xticks(ticks) ax.set_xticklabels(treds, rotation=45, ha="right", size=8) yticklabels = [int(x) for x in ax.get_yticks()] ax.set_yticklabels(yticklabels, family='Helvetica') ax.set_ylabel("Mendelian errors (\%)") ax.set_ylim(ymin, 20) normalize_axes(root) image_name = "mendelian_errors." + iopts.format savefig(image_name, dpi=iopts.dpi, iopts=iopts)
[ "def", "mendelian_errors", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "mendelian_errors", ".", "__doc__", ")", "opts", ",", "args", ",", "iopts", "=", "p", ".", "set_image_options", "(", "args", ",", "figsize", "=", "\"6x6\"", ")", "if", "len"...
%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 errors and trio errors.
[ "%prog", "mendelian_errors", "STR", "-", "Mendelian", "-", "errors", ".", "csv" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/str.py#L611-L672
train
200,544
tanghaibao/jcvi
jcvi/projects/str.py
read_tred_tsv
def read_tred_tsv(tsvfile): """ Read the TRED table into a dataframe. """ df = pd.read_csv(tsvfile, sep="\t", index_col=0, dtype={"SampleKey": str}) return df
python
def read_tred_tsv(tsvfile): """ Read the TRED table into a dataframe. """ df = pd.read_csv(tsvfile, sep="\t", index_col=0, dtype={"SampleKey": str}) return df
[ "def", "read_tred_tsv", "(", "tsvfile", ")", ":", "df", "=", "pd", ".", "read_csv", "(", "tsvfile", ",", "sep", "=", "\"\\t\"", ",", "index_col", "=", "0", ",", "dtype", "=", "{", "\"SampleKey\"", ":", "str", "}", ")", "return", "df" ]
Read the TRED table into a dataframe.
[ "Read", "the", "TRED", "table", "into", "a", "dataframe", "." ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/str.py#L703-L708
train
200,545
tanghaibao/jcvi
jcvi/projects/str.py
mendelian
def mendelian(args): """ %prog mendelian trios_candidate.json hli.20170424.tred.tsv Calculate Mendelian errors based on trios and duos. """ 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.verbose tolerance = opts.tolerance js = json.load(open(triosjson)) allterms = set() duos = set() trios = set() for v in js: allterms |= set(v.keys()) for trio_or_duo in extract_trios(v): assert len(trio_or_duo) in (2, 3) if len(trio_or_duo) == 2: duos.add(trio_or_duo) else: trios.add(trio_or_duo) # print "\n".join(allterms) print("A total of {} families imported".format(len(js))) # Read in all data df = read_tred_tsv(tredtsv) ids, treds = read_treds() table = {} for tred, inheritance in zip(treds["abbreviation"], treds["inheritance"]): x_linked = inheritance[0] == 'X' # X-linked name = tred if x_linked: name += " (X-linked)" print("[TRED] {}".format(name)) n_total = len(duos) n_error = 0 for duo in duos: n_error += duo.check_mendelian(df, tred, tolerance=tolerance, x_linked=x_linked, verbose=verbose) tag = "Duos - Mendelian errors" print("{}: {}".format(tag, percentage(n_error, n_total))) duo_error = percentage(n_error, n_total, mode=2) table[(name, tag)] = "{0:.1f}%".format(duo_error) n_total = len(trios) n_error = 0 for trio in trios: n_error += trio.check_mendelian(df, tred, tolerance=tolerance, x_linked=x_linked, verbose=verbose) tag = "Trios - Mendelian errors" print("{}: {}".format(tag, percentage(n_error, n_total))) trio_error = percentage(n_error, n_total, mode=2) table[(name, tag)] = "{0:.1f}%".format(trio_error) # Summarize print(tabulate(table))
python
def mendelian(args): """ %prog mendelian trios_candidate.json hli.20170424.tred.tsv Calculate Mendelian errors based on trios and duos. """ 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.verbose tolerance = opts.tolerance js = json.load(open(triosjson)) allterms = set() duos = set() trios = set() for v in js: allterms |= set(v.keys()) for trio_or_duo in extract_trios(v): assert len(trio_or_duo) in (2, 3) if len(trio_or_duo) == 2: duos.add(trio_or_duo) else: trios.add(trio_or_duo) # print "\n".join(allterms) print("A total of {} families imported".format(len(js))) # Read in all data df = read_tred_tsv(tredtsv) ids, treds = read_treds() table = {} for tred, inheritance in zip(treds["abbreviation"], treds["inheritance"]): x_linked = inheritance[0] == 'X' # X-linked name = tred if x_linked: name += " (X-linked)" print("[TRED] {}".format(name)) n_total = len(duos) n_error = 0 for duo in duos: n_error += duo.check_mendelian(df, tred, tolerance=tolerance, x_linked=x_linked, verbose=verbose) tag = "Duos - Mendelian errors" print("{}: {}".format(tag, percentage(n_error, n_total))) duo_error = percentage(n_error, n_total, mode=2) table[(name, tag)] = "{0:.1f}%".format(duo_error) n_total = len(trios) n_error = 0 for trio in trios: n_error += trio.check_mendelian(df, tred, tolerance=tolerance, x_linked=x_linked, verbose=verbose) tag = "Trios - Mendelian errors" print("{}: {}".format(tag, percentage(n_error, n_total))) trio_error = percentage(n_error, n_total, mode=2) table[(name, tag)] = "{0:.1f}%".format(trio_error) # Summarize print(tabulate(table))
[ "def", "mendelian", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "mendelian", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--tolerance\"", ",", "default", "=", "0", ",", "type", "=", "\"int\"", ",", "help", "=", "\"Tolernace for difference...
%prog mendelian trios_candidate.json hli.20170424.tred.tsv Calculate Mendelian errors based on trios and duos.
[ "%prog", "mendelian", "trios_candidate", ".", "json", "hli", ".", "20170424", ".", "tred", ".", "tsv" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/str.py#L711-L778
train
200,546
tanghaibao/jcvi
jcvi/projects/str.py
mini
def mini(args): """ %prog mini bamfile minibamfile Prepare mini-BAMs that contain only the STR loci. """ 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) if len(args) != 2: sys.exit(not p.print_help()) bamfile, minibam = args treds = opts.treds.split(",") if opts.treds else None pad = opts.pad bedfile = make_STR_bed(pad=pad, treds=treds) get_minibam_bed(bamfile, bedfile, minibam) logging.debug("Mini-BAM written to `{}`".format(minibam))
python
def mini(args): """ %prog mini bamfile minibamfile Prepare mini-BAMs that contain only the STR loci. """ 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) if len(args) != 2: sys.exit(not p.print_help()) bamfile, minibam = args treds = opts.treds.split(",") if opts.treds else None pad = opts.pad bedfile = make_STR_bed(pad=pad, treds=treds) get_minibam_bed(bamfile, bedfile, minibam) logging.debug("Mini-BAM written to `{}`".format(minibam))
[ "def", "mini", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "mini", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--pad\"", ",", "default", "=", "20000", ",", "type", "=", "\"int\"", ",", "help", "=", "\"Add padding to the STR reigons\"", ...
%prog mini bamfile minibamfile Prepare mini-BAMs that contain only the STR loci.
[ "%prog", "mini", "bamfile", "minibamfile" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/str.py#L820-L843
train
200,547
tanghaibao/jcvi
jcvi/projects/str.py
likelihood2
def likelihood2(args): """ %prog likelihood2 100_20.json Plot the likelihood surface and marginal distributions. """ 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(figsize=(iopts.w, iopts.h)) gs = gridspec.GridSpec(2, 2) ax1 = fig.add_subplot(gs[:, 0]) ax2 = fig.add_subplot(gs[0, 1]) ax3 = fig.add_subplot(gs[1, 1]) plt.tight_layout(pad=3) pf = plot_panel(jsonfile, ax1, ax2, ax3, opts.cmap) root = fig.add_axes([0, 0, 1, 1]) normalize_axes(root) image_name = "likelihood2.{}.".format(pf) + iopts.format savefig(image_name, dpi=iopts.dpi, iopts=iopts)
python
def likelihood2(args): """ %prog likelihood2 100_20.json Plot the likelihood surface and marginal distributions. """ 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(figsize=(iopts.w, iopts.h)) gs = gridspec.GridSpec(2, 2) ax1 = fig.add_subplot(gs[:, 0]) ax2 = fig.add_subplot(gs[0, 1]) ax3 = fig.add_subplot(gs[1, 1]) plt.tight_layout(pad=3) pf = plot_panel(jsonfile, ax1, ax2, ax3, opts.cmap) root = fig.add_axes([0, 0, 1, 1]) normalize_axes(root) image_name = "likelihood2.{}.".format(pf) + iopts.format savefig(image_name, dpi=iopts.dpi, iopts=iopts)
[ "def", "likelihood2", "(", "args", ")", ":", "from", "matplotlib", "import", "gridspec", "p", "=", "OptionParser", "(", "likelihood2", ".", "__doc__", ")", "opts", ",", "args", ",", "iopts", "=", "p", ".", "set_image_options", "(", "args", ",", "figsize", ...
%prog likelihood2 100_20.json Plot the likelihood surface and marginal distributions.
[ "%prog", "likelihood2", "100_20", ".", "json" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/str.py#L1011-L1039
train
200,548
tanghaibao/jcvi
jcvi/projects/str.py
likelihood3
def likelihood3(args): """ %prog likelihood3 140_20.json 140_70.json Plot the likelihood surface and marginal distributions for two settings. """ 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 = plt.figure(figsize=(iopts.w, iopts.h)) gs = gridspec.GridSpec(9, 2) ax1 = fig.add_subplot(gs[:4, 0]) ax2 = fig.add_subplot(gs[:2, 1]) ax3 = fig.add_subplot(gs[2:4, 1]) ax4 = fig.add_subplot(gs[5:, 0]) ax5 = fig.add_subplot(gs[5:7, 1]) ax6 = fig.add_subplot(gs[7:, 1]) plt.tight_layout(pad=2) plot_panel(jsonfile1, ax1, ax2, ax3, opts.cmap) plot_panel(jsonfile2, ax4, ax5, ax6, opts.cmap) root = fig.add_axes([0, 0, 1, 1]) pad = .02 panel_labels(root, ((pad, 1 - pad, "A"), (pad, 4. / 9, "B"))) normalize_axes(root) image_name = "likelihood3." + iopts.format savefig(image_name, dpi=iopts.dpi, iopts=iopts)
python
def likelihood3(args): """ %prog likelihood3 140_20.json 140_70.json Plot the likelihood surface and marginal distributions for two settings. """ 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 = plt.figure(figsize=(iopts.w, iopts.h)) gs = gridspec.GridSpec(9, 2) ax1 = fig.add_subplot(gs[:4, 0]) ax2 = fig.add_subplot(gs[:2, 1]) ax3 = fig.add_subplot(gs[2:4, 1]) ax4 = fig.add_subplot(gs[5:, 0]) ax5 = fig.add_subplot(gs[5:7, 1]) ax6 = fig.add_subplot(gs[7:, 1]) plt.tight_layout(pad=2) plot_panel(jsonfile1, ax1, ax2, ax3, opts.cmap) plot_panel(jsonfile2, ax4, ax5, ax6, opts.cmap) root = fig.add_axes([0, 0, 1, 1]) pad = .02 panel_labels(root, ((pad, 1 - pad, "A"), (pad, 4. / 9, "B"))) normalize_axes(root) image_name = "likelihood3." + iopts.format savefig(image_name, dpi=iopts.dpi, iopts=iopts)
[ "def", "likelihood3", "(", "args", ")", ":", "from", "matplotlib", "import", "gridspec", "p", "=", "OptionParser", "(", "likelihood3", ".", "__doc__", ")", "opts", ",", "args", ",", "iopts", "=", "p", ".", "set_image_options", "(", "args", ",", "figsize", ...
%prog likelihood3 140_20.json 140_70.json Plot the likelihood surface and marginal distributions for two settings.
[ "%prog", "likelihood3", "140_20", ".", "json", "140_70", ".", "json" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/str.py#L1042-L1076
train
200,549
tanghaibao/jcvi
jcvi/projects/str.py
allelefreqall
def allelefreqall(args): """ %prog allelefreqall HN_Platinum_Gold.20180525.tsv.report.txt Plot all 30 STR allele frequencies. """ 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 = [] for page in xrange(len(treds) / count + 1): start = page * count page_treds = treds[start: start + count] if not page_treds: break allelefreq([",".join(page_treds), "--usereport", reportfile, "--nopanels", "--figsize", "12x16"]) outpdf = "allelefreq.{}.pdf".format(page) sh("mv allelefreq.pdf {}".format(outpdf)) pdfs.append(outpdf) from jcvi.formats.pdf import cat pf = op.basename(reportfile).split(".")[0] finalpdf = pf + ".allelefreq.pdf" logging.debug("Merging pdfs into `{}`".format(finalpdf)) cat(pdfs + ["-o", finalpdf, "--cleanup"])
python
def allelefreqall(args): """ %prog allelefreqall HN_Platinum_Gold.20180525.tsv.report.txt Plot all 30 STR allele frequencies. """ 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 = [] for page in xrange(len(treds) / count + 1): start = page * count page_treds = treds[start: start + count] if not page_treds: break allelefreq([",".join(page_treds), "--usereport", reportfile, "--nopanels", "--figsize", "12x16"]) outpdf = "allelefreq.{}.pdf".format(page) sh("mv allelefreq.pdf {}".format(outpdf)) pdfs.append(outpdf) from jcvi.formats.pdf import cat pf = op.basename(reportfile).split(".")[0] finalpdf = pf + ".allelefreq.pdf" logging.debug("Merging pdfs into `{}`".format(finalpdf)) cat(pdfs + ["-o", finalpdf, "--cleanup"])
[ "def", "allelefreqall", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "allelefreqall", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", "1", ":", "sys", ".", "exit...
%prog allelefreqall HN_Platinum_Gold.20180525.tsv.report.txt Plot all 30 STR allele frequencies.
[ "%prog", "allelefreqall", "HN_Platinum_Gold", ".", "20180525", ".", "tsv", ".", "report", ".", "txt" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/str.py#L1239-L1273
train
200,550
tanghaibao/jcvi
jcvi/projects/str.py
allelefreq
def allelefreq(args): """ %prog allelefreq HD,DM1,SCA1,SCA17,FXTAS,FRAXE Plot the allele frequencies of some STRs. """ 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(args) != 1: sys.exit(not p.print_help()) loci, = args fig, ((ax1, ax2), (ax3, ax4), (ax5, ax6)) = plt.subplots(ncols=2, nrows=3, figsize=(iopts.w, iopts.h)) plt.tight_layout(pad=4) if opts.usereport: treds, df = read_treds(tredsfile=opts.usereport) else: treds, df = read_treds() df = df.set_index(["abbreviation"]) axes = (ax1, ax2, ax3, ax4, ax5, ax6) loci = loci.split(",") for ax, locus in zip(axes, loci): plot_allelefreq(ax, df, locus) # Delete unused axes for ax in axes[len(loci):]: ax.set_axis_off() root = fig.add_axes([0, 0, 1, 1]) pad = .03 if not opts.nopanels: panel_labels(root, ((pad / 2, 1 - pad, "A"), (.5 + pad, 1 - pad, "B"), (pad / 2, 2 / 3. - pad / 2, "C"), (.5 + pad, 2 / 3. - pad / 2, "D"), (pad / 2, 1 / 3. , "E"), (.5 + pad, 1 / 3. , "F"), )) normalize_axes(root) image_name = "allelefreq." + iopts.format savefig(image_name, dpi=iopts.dpi, iopts=iopts)
python
def allelefreq(args): """ %prog allelefreq HD,DM1,SCA1,SCA17,FXTAS,FRAXE Plot the allele frequencies of some STRs. """ 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(args) != 1: sys.exit(not p.print_help()) loci, = args fig, ((ax1, ax2), (ax3, ax4), (ax5, ax6)) = plt.subplots(ncols=2, nrows=3, figsize=(iopts.w, iopts.h)) plt.tight_layout(pad=4) if opts.usereport: treds, df = read_treds(tredsfile=opts.usereport) else: treds, df = read_treds() df = df.set_index(["abbreviation"]) axes = (ax1, ax2, ax3, ax4, ax5, ax6) loci = loci.split(",") for ax, locus in zip(axes, loci): plot_allelefreq(ax, df, locus) # Delete unused axes for ax in axes[len(loci):]: ax.set_axis_off() root = fig.add_axes([0, 0, 1, 1]) pad = .03 if not opts.nopanels: panel_labels(root, ((pad / 2, 1 - pad, "A"), (.5 + pad, 1 - pad, "B"), (pad / 2, 2 / 3. - pad / 2, "C"), (.5 + pad, 2 / 3. - pad / 2, "D"), (pad / 2, 1 / 3. , "E"), (.5 + pad, 1 / 3. , "F"), )) normalize_axes(root) image_name = "allelefreq." + iopts.format savefig(image_name, dpi=iopts.dpi, iopts=iopts)
[ "def", "allelefreq", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "allelefreq", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--nopanels\"", ",", "default", "=", "False", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"No panel l...
%prog allelefreq HD,DM1,SCA1,SCA17,FXTAS,FRAXE Plot the allele frequencies of some STRs.
[ "%prog", "allelefreq", "HD", "DM1", "SCA1", "SCA17", "FXTAS", "FRAXE" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/str.py#L1276-L1321
train
200,551
tanghaibao/jcvi
jcvi/projects/str.py
simulate
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`. """ 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", help="TRED locus") add_simulate_options(p) opts, args = p.parse_args(args) if len(args) != 3: sys.exit(not p.print_help()) rundir, startunits, endunits = args ref = opts.ref ref_fasta = "/mnt/ref/{}.upper.fa".format(ref) startunits, endunits = int(startunits), int(endunits) basecwd = os.getcwd() mkdir(rundir) os.chdir(rundir) cwd = os.getcwd() # TRED region (e.g. Huntington) pad_left, pad_right = 1000, 10000 repo = TREDsRepo(ref=ref) tred = repo[opts.tred] chr, start, end = tred.chr, tred.repeat_start, tred.repeat_end logging.debug("Simulating {}".format(tred)) fasta = Fasta(ref_fasta) seq_left = fasta[chr][start - pad_left:start - 1] seq_right = fasta[chr][end: end + pad_right] motif = tred.repeat simulate_method = wgsim if opts.method == "wgsim" else eagle # Write fake sequence for units in range(startunits, endunits + 1): pf = str(units) mkdir(pf) os.chdir(pf) seq = str(seq_left) + motif * units + str(seq_right) fastafile = pf + ".fasta" make_fasta(seq, fastafile, id=chr.upper()) # Simulate reads on it simulate_method([fastafile, "--depth={}".format(opts.depth), "--readlen={}".format(opts.readlen), "--distance={}".format(opts.distance), "--outfile={}".format(pf)]) read1 = pf + ".bwa.read1.fastq" read2 = pf + ".bwa.read2.fastq" samfile, _ = align([ref_fasta, read1, read2]) indexed_samfile = index([samfile]) sh("mv {} ../{}.bam".format(indexed_samfile, pf)) sh("mv {}.bai ../{}.bam.bai".format(indexed_samfile, pf)) os.chdir(cwd) shutil.rmtree(pf) os.chdir(basecwd)
python
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`. """ 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", help="TRED locus") add_simulate_options(p) opts, args = p.parse_args(args) if len(args) != 3: sys.exit(not p.print_help()) rundir, startunits, endunits = args ref = opts.ref ref_fasta = "/mnt/ref/{}.upper.fa".format(ref) startunits, endunits = int(startunits), int(endunits) basecwd = os.getcwd() mkdir(rundir) os.chdir(rundir) cwd = os.getcwd() # TRED region (e.g. Huntington) pad_left, pad_right = 1000, 10000 repo = TREDsRepo(ref=ref) tred = repo[opts.tred] chr, start, end = tred.chr, tred.repeat_start, tred.repeat_end logging.debug("Simulating {}".format(tred)) fasta = Fasta(ref_fasta) seq_left = fasta[chr][start - pad_left:start - 1] seq_right = fasta[chr][end: end + pad_right] motif = tred.repeat simulate_method = wgsim if opts.method == "wgsim" else eagle # Write fake sequence for units in range(startunits, endunits + 1): pf = str(units) mkdir(pf) os.chdir(pf) seq = str(seq_left) + motif * units + str(seq_right) fastafile = pf + ".fasta" make_fasta(seq, fastafile, id=chr.upper()) # Simulate reads on it simulate_method([fastafile, "--depth={}".format(opts.depth), "--readlen={}".format(opts.readlen), "--distance={}".format(opts.distance), "--outfile={}".format(pf)]) read1 = pf + ".bwa.read1.fastq" read2 = pf + ".bwa.read2.fastq" samfile, _ = align([ref_fasta, read1, read2]) indexed_samfile = index([samfile]) sh("mv {} ../{}.bam".format(indexed_samfile, pf)) sh("mv {}.bai ../{}.bam.bai".format(indexed_samfile, pf)) os.chdir(cwd) shutil.rmtree(pf) os.chdir(basecwd)
[ "def", "simulate", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "simulate", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--method\"", ",", "choices", "=", "(", "\"wgsim\"", ",", "\"eagle\"", ")", ",", "default", "=", "\"eagle\"", ",", ...
%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`.
[ "%prog", "simulate", "run_dir", "1", "300" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/str.py#L1339-L1407
train
200,552
tanghaibao/jcvi
jcvi/projects/str.py
batchlobstr
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 """ 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 jcvi.variation.str lobstr TREDs" cmd += " --input_bam_path {}" cmd += " --haploid {}".format(opts.haploid) cmd += " --simulation" cmds = [cmd.format(x.strip()) for x in open(bamlist).readlines()] p = Parallel(cmds, cpus=opts.cpus) p.run()
python
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 """ 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 jcvi.variation.str lobstr TREDs" cmd += " --input_bam_path {}" cmd += " --haploid {}".format(opts.haploid) cmd += " --simulation" cmds = [cmd.format(x.strip()) for x in open(bamlist).readlines()] p = Parallel(cmds, cpus=opts.cpus) p.run()
[ "def", "batchlobstr", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "batchlobstr", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--haploid\"", ",", "default", "=", "\"chrY,chrM\"", ",", "help", "=", "\"Use haploid model for these chromosomes\"", "...
%prog batchlobstr bamlist Run lobSTR on a list of BAMs. The corresponding batch command for TREDPARSE: $ tred.py bamlist --haploid chr4 --workdir tredparse_results
[ "%prog", "batchlobstr", "bamlist" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/str.py#L1453-L1476
train
200,553
tanghaibao/jcvi
jcvi/projects/str.py
compilevcf
def compilevcf(args): """ %prog compilevcf dir Compile vcf outputs into lists. """ 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 = LobSTRvcf(columnidsfile=None) p.parse(vcf_file, filtered=False) res = p.items() if res: k, v = res[0] res = v.replace(',', '/') else: res = "-1/-1" num = op.basename(vcf_file).split(".")[0] print(num, res) except (TypeError, AttributeError) as e: p = TREDPARSEvcf(vcf_file) continue
python
def compilevcf(args): """ %prog compilevcf dir Compile vcf outputs into lists. """ 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 = LobSTRvcf(columnidsfile=None) p.parse(vcf_file, filtered=False) res = p.items() if res: k, v = res[0] res = v.replace(',', '/') else: res = "-1/-1" num = op.basename(vcf_file).split(".")[0] print(num, res) except (TypeError, AttributeError) as e: p = TREDPARSEvcf(vcf_file) continue
[ "def", "compilevcf", "(", "args", ")", ":", "from", "jcvi", ".", "variation", ".", "str", "import", "LobSTRvcf", "p", "=", "OptionParser", "(", "compilevcf", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if",...
%prog compilevcf dir Compile vcf outputs into lists.
[ "%prog", "compilevcf", "dir" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/str.py#L1479-L1509
train
200,554
tanghaibao/jcvi
jcvi/projects/str.py
draw_jointplot
def draw_jointplot(figname, x, y, data=None, kind="reg", color=None, xlim=None, ylim=None, format="pdf"): """ Wraps around sns.jointplot """ 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", "HD.2": "Repeat size of the longer allele"} g = sns.jointplot(x, y, data=data, kind=kind, color=color, xlim=xlim, ylim=ylim) g.ax_joint.set_xlabel(register.get(x, x)) g.ax_joint.set_ylabel(register.get(y, y)) savefig(figname + "." + format, cleanup=False)
python
def draw_jointplot(figname, x, y, data=None, kind="reg", color=None, xlim=None, ylim=None, format="pdf"): """ Wraps around sns.jointplot """ 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", "HD.2": "Repeat size of the longer allele"} g = sns.jointplot(x, y, data=data, kind=kind, color=color, xlim=xlim, ylim=ylim) g.ax_joint.set_xlabel(register.get(x, x)) g.ax_joint.set_ylabel(register.get(y, y)) savefig(figname + "." + format, cleanup=False)
[ "def", "draw_jointplot", "(", "figname", ",", "x", ",", "y", ",", "data", "=", "None", ",", "kind", "=", "\"reg\"", ",", "color", "=", "None", ",", "xlim", "=", "None", ",", "ylim", "=", "None", ",", "format", "=", "\"pdf\"", ")", ":", "import", ...
Wraps around sns.jointplot
[ "Wraps", "around", "sns", ".", "jointplot" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/str.py#L1574-L1593
train
200,555
tanghaibao/jcvi
jcvi/projects/str.py
get_lo_hi_from_CI
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) """ 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)
python
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) """ 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", ")", ":", "a", ",", "b", "=", "s", ".", "split", "(", "\"|\"", ")", "ai", ",", "aj", "=", "a", ".", "split", "(", "\"-\"", ")", "bi", ",", "bj", "=", "b", ".", "split", "(", ...
Parse the confidence interval from CI. >>> get_lo_hi_from_CI("20-20/40-60") (40, 60)
[ "Parse", "the", "confidence", "interval", "from", "CI", "." ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/str.py#L1611-L1628
train
200,556
tanghaibao/jcvi
jcvi/projects/str.py
compare
def compare(args): """ %prog compare Evaluation.csv Compare performances of various variant callers on simulated STR datasets. """ 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, figsize=(iopts.w, iopts.h)) plt.tight_layout(pad=3) bbox = {'facecolor': 'tomato', 'alpha': .2, 'ec': 'w'} pad = 2 # Read benchmark data df = pd.read_csv("Evaluation.csv") truth = df["Truth"] axes = (ax1, ax2, ax3, ax4) progs = ("Manta", "Isaac", "GATK", "lobSTR") markers = ("bx-", "yo-", "md-", "c+-") for ax, prog, marker in zip(axes, progs, markers): ax.plot(truth, df[prog], marker) ax.plot(truth, truth, 'k--') # to show diagonal ax.axhline(infected_thr, color='tomato') ax.text(max(truth) - pad, infected_thr + pad, 'Risk threshold', bbox=bbox, ha="right") ax.axhline(ref_thr, color='tomato') ax.text(max(truth) - pad, ref_thr - pad, 'Reference repeat count', bbox=bbox, ha="right", va="top") ax.set_title(SIMULATED_HAPLOID) ax.set_xlabel(r'Num of CAG repeats inserted ($\mathit{h}$)') ax.set_ylabel('Num of CAG repeats called') ax.legend([prog, 'Truth'], loc='best') root = fig.add_axes([0, 0, 1, 1]) pad = .03 panel_labels(root, ((pad / 2, 1 - pad, "A"), (1 / 2., 1 - pad, "B"), (pad / 2, 1 / 2., "C"), (1 / 2., 1 / 2. , "D"))) normalize_axes(root) image_name = pf + "." + iopts.format savefig(image_name, dpi=iopts.dpi, iopts=iopts)
python
def compare(args): """ %prog compare Evaluation.csv Compare performances of various variant callers on simulated STR datasets. """ 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, figsize=(iopts.w, iopts.h)) plt.tight_layout(pad=3) bbox = {'facecolor': 'tomato', 'alpha': .2, 'ec': 'w'} pad = 2 # Read benchmark data df = pd.read_csv("Evaluation.csv") truth = df["Truth"] axes = (ax1, ax2, ax3, ax4) progs = ("Manta", "Isaac", "GATK", "lobSTR") markers = ("bx-", "yo-", "md-", "c+-") for ax, prog, marker in zip(axes, progs, markers): ax.plot(truth, df[prog], marker) ax.plot(truth, truth, 'k--') # to show diagonal ax.axhline(infected_thr, color='tomato') ax.text(max(truth) - pad, infected_thr + pad, 'Risk threshold', bbox=bbox, ha="right") ax.axhline(ref_thr, color='tomato') ax.text(max(truth) - pad, ref_thr - pad, 'Reference repeat count', bbox=bbox, ha="right", va="top") ax.set_title(SIMULATED_HAPLOID) ax.set_xlabel(r'Num of CAG repeats inserted ($\mathit{h}$)') ax.set_ylabel('Num of CAG repeats called') ax.legend([prog, 'Truth'], loc='best') root = fig.add_axes([0, 0, 1, 1]) pad = .03 panel_labels(root, ((pad / 2, 1 - pad, "A"), (1 / 2., 1 - pad, "B"), (pad / 2, 1 / 2., "C"), (1 / 2., 1 / 2. , "D"))) normalize_axes(root) image_name = pf + "." + iopts.format savefig(image_name, dpi=iopts.dpi, iopts=iopts)
[ "def", "compare", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "compare", ".", "__doc__", ")", "opts", ",", "args", ",", "iopts", "=", "p", ".", "set_image_options", "(", "args", ",", "figsize", "=", "\"10x10\"", ")", "if", "len", "(", "args...
%prog compare Evaluation.csv Compare performances of various variant callers on simulated STR datasets.
[ "%prog", "compare", "Evaluation", ".", "csv" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/str.py#L1660-L1709
train
200,557
tanghaibao/jcvi
jcvi/graphics/histogram.py
stem_leaf_plot
def stem_leaf_plot(data, vmin, vmax, bins, digit=1, title=None): ''' 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(data, bins=bins) # By default, len(bin_edges) = len(hist) + 1 bin_edges = bin_edges[:len(hist)] asciiplot(bin_edges, hist, digit=digit, title=title) print("Last bin ends in {0}, inclusive.".format(vmax), file=sys.stderr) return bin_edges, hist
python
def stem_leaf_plot(data, vmin, vmax, bins, digit=1, title=None): ''' 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(data, bins=bins) # By default, len(bin_edges) = len(hist) + 1 bin_edges = bin_edges[:len(hist)] asciiplot(bin_edges, hist, digit=digit, title=title) print("Last bin ends in {0}, inclusive.".format(vmax), file=sys.stderr) return bin_edges, hist
[ "def", "stem_leaf_plot", "(", "data", ",", "vmin", ",", "vmax", ",", "bins", ",", "digit", "=", "1", ",", "title", "=", "None", ")", ":", "assert", "bins", ">", "0", "range", "=", "vmax", "-", "vmin", "step", "=", "range", "*", "1.", "/", "bins",...
Generate stem and leaf plot given a collection of numbers
[ "Generate", "stem", "and", "leaf", "plot", "given", "a", "collection", "of", "numbers" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/graphics/histogram.py#L129-L148
train
200,558
tanghaibao/jcvi
jcvi/variation/tassel.py
prepare
def prepare(args): """ %prog prepare barcode_key.csv reference.fasta Prepare TASSEL pipeline. """ valid_enzymes = "ApeKI|ApoI|BamHI|EcoT22I|HinP1I|HpaII|MseI|MspI|" \ "NdeI|PasI|PstI|Sau3AI|SbfI|AsiSI-MspI|BssHII-MspI|" \ "FseI-MspI|PaeR7I-HhaI|PstI-ApeKI|PstI-EcoT22I|PstI-MspI" \ "PstI-TaqI|SalI-MspI|SbfI-MspI".split("|") p = OptionParser(prepare.__doc__) p.add_option("--enzyme", default="ApeKI", choices=valid_enzymes, help="Restriction enzyme used [default: %default]") p.set_home("tassel") p.set_aligner(aligner="bwa") p.set_cpus() opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) barcode, reference = args thome = opts.tassel_home reference = get_abs_path(reference) folders = ("fastq", "tagCounts", "mergedTagCounts", "topm", "tbt", "mergedTBT", "hapmap", "hapmap/raw", "hapmap/mergedSNPs", "hapmap/filt", "hapmap/bpec") for f in folders: mkdir(f) # Build the pipeline runsh = [] o = "-i fastq -k {0} -e {1} -o tagCounts".format(barcode, opts.enzyme) cmd = run_pipeline(thome, "FastqToTagCountPlugin", o) runsh.append(cmd) o = "-i tagCounts -o mergedTagCounts/myMasterTags.cnt" o += " -c 5 -t mergedTagCounts/myMasterTags.cnt.fq" cmd = run_pipeline(thome, "MergeMultipleTagCountPlugin", o) runsh.append(cmd) runsh.append("cd mergedTagCounts") cmd = "python -m jcvi.apps.{0} align --cpus {1}".\ format(opts.aligner, opts.cpus) cmd += " {0} myMasterTags.cnt.fq".format(reference) runsh.append(cmd) runsh.append("cd ..") o = "-i mergedTagCounts/*.sam -o topm/myMasterTags.topm" cmd = run_pipeline(thome, "SAMConverterPlugin", o) runsh.append(cmd) o = "-i mergedTBT/myStudy.tbt.byte -y -m topm/myMasterTags.topm" o += " -mUpd topm/myMasterTagsWithVariants.topm" o += " -o hapmap/raw/myGBSGenos_chr+.hmp.txt" o += " -mnF 0.8 -p myPedigreeFile.ped -mnMAF 0.02 -mnMAC 100000" o += " -ref {0} -sC 1 -eC 10".format(reference) cmd = run_pipeline(thome, "TagsToSNPByAlignmentPlugin", o) runsh.append(cmd) o = "-hmp hapmap/raw/myGBSGenos_chr+.hmp.txt" o += " -o hapmap/mergedSNPs/myGBSGenos_mergedSNPs_chr+.hmp.txt" o += " -misMat 0.1 -p myPedigreeFile.ped -callHets -sC 1 -eC 10" cmd = run_pipeline(thome, "MergeDuplicateSNPsPlugin", o) runsh.append(cmd) o = "-hmp hapmap/mergedSNPs/myGBSGenos_mergedSNPs_chr+.hmp.txt" o += " -o hapmap/filt/myGBSGenos_mergedSNPsFilt_chr+.hmp.txt" o += " -mnTCov 0.01 -mnSCov 0.2 -mnMAF 0.01 -sC 1 -eC 10" #o += "-hLD -mnR2 0.2 -mnBonP 0.005" cmd = run_pipeline(thome, "GBSHapMapFiltersPlugin", o) runsh.append(cmd) runfile = "run.sh" write_file(runfile, "\n".join(runsh))
python
def prepare(args): """ %prog prepare barcode_key.csv reference.fasta Prepare TASSEL pipeline. """ valid_enzymes = "ApeKI|ApoI|BamHI|EcoT22I|HinP1I|HpaII|MseI|MspI|" \ "NdeI|PasI|PstI|Sau3AI|SbfI|AsiSI-MspI|BssHII-MspI|" \ "FseI-MspI|PaeR7I-HhaI|PstI-ApeKI|PstI-EcoT22I|PstI-MspI" \ "PstI-TaqI|SalI-MspI|SbfI-MspI".split("|") p = OptionParser(prepare.__doc__) p.add_option("--enzyme", default="ApeKI", choices=valid_enzymes, help="Restriction enzyme used [default: %default]") p.set_home("tassel") p.set_aligner(aligner="bwa") p.set_cpus() opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) barcode, reference = args thome = opts.tassel_home reference = get_abs_path(reference) folders = ("fastq", "tagCounts", "mergedTagCounts", "topm", "tbt", "mergedTBT", "hapmap", "hapmap/raw", "hapmap/mergedSNPs", "hapmap/filt", "hapmap/bpec") for f in folders: mkdir(f) # Build the pipeline runsh = [] o = "-i fastq -k {0} -e {1} -o tagCounts".format(barcode, opts.enzyme) cmd = run_pipeline(thome, "FastqToTagCountPlugin", o) runsh.append(cmd) o = "-i tagCounts -o mergedTagCounts/myMasterTags.cnt" o += " -c 5 -t mergedTagCounts/myMasterTags.cnt.fq" cmd = run_pipeline(thome, "MergeMultipleTagCountPlugin", o) runsh.append(cmd) runsh.append("cd mergedTagCounts") cmd = "python -m jcvi.apps.{0} align --cpus {1}".\ format(opts.aligner, opts.cpus) cmd += " {0} myMasterTags.cnt.fq".format(reference) runsh.append(cmd) runsh.append("cd ..") o = "-i mergedTagCounts/*.sam -o topm/myMasterTags.topm" cmd = run_pipeline(thome, "SAMConverterPlugin", o) runsh.append(cmd) o = "-i mergedTBT/myStudy.tbt.byte -y -m topm/myMasterTags.topm" o += " -mUpd topm/myMasterTagsWithVariants.topm" o += " -o hapmap/raw/myGBSGenos_chr+.hmp.txt" o += " -mnF 0.8 -p myPedigreeFile.ped -mnMAF 0.02 -mnMAC 100000" o += " -ref {0} -sC 1 -eC 10".format(reference) cmd = run_pipeline(thome, "TagsToSNPByAlignmentPlugin", o) runsh.append(cmd) o = "-hmp hapmap/raw/myGBSGenos_chr+.hmp.txt" o += " -o hapmap/mergedSNPs/myGBSGenos_mergedSNPs_chr+.hmp.txt" o += " -misMat 0.1 -p myPedigreeFile.ped -callHets -sC 1 -eC 10" cmd = run_pipeline(thome, "MergeDuplicateSNPsPlugin", o) runsh.append(cmd) o = "-hmp hapmap/mergedSNPs/myGBSGenos_mergedSNPs_chr+.hmp.txt" o += " -o hapmap/filt/myGBSGenos_mergedSNPsFilt_chr+.hmp.txt" o += " -mnTCov 0.01 -mnSCov 0.2 -mnMAF 0.01 -sC 1 -eC 10" #o += "-hLD -mnR2 0.2 -mnBonP 0.005" cmd = run_pipeline(thome, "GBSHapMapFiltersPlugin", o) runsh.append(cmd) runfile = "run.sh" write_file(runfile, "\n".join(runsh))
[ "def", "prepare", "(", "args", ")", ":", "valid_enzymes", "=", "\"ApeKI|ApoI|BamHI|EcoT22I|HinP1I|HpaII|MseI|MspI|\"", "\"NdeI|PasI|PstI|Sau3AI|SbfI|AsiSI-MspI|BssHII-MspI|\"", "\"FseI-MspI|PaeR7I-HhaI|PstI-ApeKI|PstI-EcoT22I|PstI-MspI\"", "\"PstI-TaqI|SalI-MspI|SbfI-MspI\"", ".", "split",...
%prog prepare barcode_key.csv reference.fasta Prepare TASSEL pipeline.
[ "%prog", "prepare", "barcode_key", ".", "csv", "reference", ".", "fasta" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/tassel.py#L33-L107
train
200,559
tanghaibao/jcvi
jcvi/apps/bwa.py
batch
def batch(args): """ %proj batch database.fasta project_dir output_dir Run bwa in batch mode. """ 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://"): s3dir = outdir outdir = op.basename(outdir) mkdir(outdir) mm = MakeManager() for p, pf in iter_project(proj_dir): targs = [ref_fasta] + p cmd1, bamfile = mem(targs, opts) if cmd1: cmd1 = output_bam(cmd1, bamfile) nbamfile = op.join(outdir, bamfile) cmd2 = "mv {} {}".format(bamfile, nbamfile) cmds = [cmd1, cmd2] if s3dir: cmd = "aws s3 cp {} {} --sse".format(nbamfile, op.join(s3dir, bamfile)) cmds.append(cmd) mm.add(p, nbamfile, cmds) mm.write()
python
def batch(args): """ %proj batch database.fasta project_dir output_dir Run bwa in batch mode. """ 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://"): s3dir = outdir outdir = op.basename(outdir) mkdir(outdir) mm = MakeManager() for p, pf in iter_project(proj_dir): targs = [ref_fasta] + p cmd1, bamfile = mem(targs, opts) if cmd1: cmd1 = output_bam(cmd1, bamfile) nbamfile = op.join(outdir, bamfile) cmd2 = "mv {} {}".format(bamfile, nbamfile) cmds = [cmd1, cmd2] if s3dir: cmd = "aws s3 cp {} {} --sse".format(nbamfile, op.join(s3dir, bamfile)) cmds.append(cmd) mm.add(p, nbamfile, cmds) mm.write()
[ "def", "batch", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "batch", ".", "__doc__", ")", "set_align_options", "(", "p", ")", "p", ".", "set_sam_options", "(", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", ...
%proj batch database.fasta project_dir output_dir Run bwa in batch mode.
[ "%proj", "batch", "database", ".", "fasta", "project_dir", "output_dir" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/bwa.py#L33-L72
train
200,560
tanghaibao/jcvi
jcvi/apps/bwa.py
index
def index(args): """ %prog index database.fasta Wrapper for `bwa index`. Same interface. """ 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)
python
def index(args): """ %prog index database.fasta Wrapper for `bwa index`. Same interface. """ 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", ")", ":", "p", "=", "OptionParser", "(", "index", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", "1", ":", "sys", ".", "exit", "(", "not...
%prog index database.fasta Wrapper for `bwa index`. Same interface.
[ "%prog", "index", "database", ".", "fasta" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/bwa.py#L104-L117
train
200,561
tanghaibao/jcvi
jcvi/apps/bwa.py
samse
def samse(args, opts): """ %prog samse database.fasta short_read.fastq Wrapper for `bwa samse`. Output will be short_read.sam. """ 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): logging.error("`{0}` exists. `bwa samse` already run.".format(samfile)) return "", samfile cmd = "bwa samse {0} {1} {2}".format(dbfile, saifile, readfile) cmd += " " + opts.extra if opts.uniq: cmd += " -n 1" return cmd, samfile
python
def samse(args, opts): """ %prog samse database.fasta short_read.fastq Wrapper for `bwa samse`. Output will be short_read.sam. """ 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): logging.error("`{0}` exists. `bwa samse` already run.".format(samfile)) return "", samfile cmd = "bwa samse {0} {1} {2}".format(dbfile, saifile, readfile) cmd += " " + opts.extra if opts.uniq: cmd += " -n 1" return cmd, samfile
[ "def", "samse", "(", "args", ",", "opts", ")", ":", "dbfile", ",", "readfile", "=", "args", "dbfile", "=", "check_index", "(", "dbfile", ")", "saifile", "=", "check_aln", "(", "dbfile", ",", "readfile", ",", "cpus", "=", "opts", ".", "cpus", ")", "sa...
%prog samse database.fasta short_read.fastq Wrapper for `bwa samse`. Output will be short_read.sam.
[ "%prog", "samse", "database", ".", "fasta", "short_read", ".", "fastq" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/bwa.py#L184-L205
train
200,562
tanghaibao/jcvi
jcvi/apps/bwa.py
sampe
def sampe(args, opts): """ %prog sampe database.fasta read1.fq read2.fq Wrapper for `bwa sampe`. Output will be read1.sam. """ 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=opts.unmapped) if not need_update((dbfile, sai1file, sai2file), samfile): logging.error("`{0}` exists. `bwa samse` already run.".format(samfile)) return "", samfile cmd = "bwa sampe " + " ".join((dbfile, sai1file, sai2file, read1file, read2file)) cmd += " " + opts.extra if opts.cutoff: cmd += " -a {0}".format(opts.cutoff) if opts.uniq: cmd += " -n 1" return cmd, samfile
python
def sampe(args, opts): """ %prog sampe database.fasta read1.fq read2.fq Wrapper for `bwa sampe`. Output will be read1.sam. """ 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=opts.unmapped) if not need_update((dbfile, sai1file, sai2file), samfile): logging.error("`{0}` exists. `bwa samse` already run.".format(samfile)) return "", samfile cmd = "bwa sampe " + " ".join((dbfile, sai1file, sai2file, read1file, read2file)) cmd += " " + opts.extra if opts.cutoff: cmd += " -a {0}".format(opts.cutoff) if opts.uniq: cmd += " -n 1" return cmd, samfile
[ "def", "sampe", "(", "args", ",", "opts", ")", ":", "dbfile", ",", "read1file", ",", "read2file", "=", "args", "dbfile", "=", "check_index", "(", "dbfile", ")", "sai1file", "=", "check_aln", "(", "dbfile", ",", "read1file", ",", "cpus", "=", "opts", "....
%prog sampe database.fasta read1.fq read2.fq Wrapper for `bwa sampe`. Output will be read1.sam.
[ "%prog", "sampe", "database", ".", "fasta", "read1", ".", "fq", "read2", ".", "fq" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/bwa.py#L208-L233
train
200,563
tanghaibao/jcvi
jcvi/apps/bwa.py
bwasw
def bwasw(args, opts): """ %prog bwasw database.fasta long_read.fastq Wrapper for `bwa bwasw`. Output will be long_read.sam. """ 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)) return "", samfile cmd = "bwa bwasw " + " ".join(args) cmd += " -t {0}".format(opts.cpus) cmd += " " + opts.extra return cmd, samfile
python
def bwasw(args, opts): """ %prog bwasw database.fasta long_read.fastq Wrapper for `bwa bwasw`. Output will be long_read.sam. """ 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)) return "", samfile cmd = "bwa bwasw " + " ".join(args) cmd += " -t {0}".format(opts.cpus) cmd += " " + opts.extra return cmd, samfile
[ "def", "bwasw", "(", "args", ",", "opts", ")", ":", "dbfile", ",", "readfile", "=", "args", "dbfile", "=", "check_index", "(", "dbfile", ")", "samfile", ",", "_", ",", "unmapped", "=", "get_samfile", "(", "readfile", ",", "dbfile", ",", "bam", "=", "...
%prog bwasw database.fasta long_read.fastq Wrapper for `bwa bwasw`. Output will be long_read.sam.
[ "%prog", "bwasw", "database", ".", "fasta", "long_read", ".", "fastq" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/bwa.py#L270-L288
train
200,564
tanghaibao/jcvi
jcvi/apps/softlink.py
link
def link(args): """ %prog link metafile Link source to target based on a tabular file. """ 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: mkdir(d) fp = open(meta) cwd = op.dirname(get_abs_path(meta)) for row in fp: source, target = row.split() source = op.join(cwd, source) if d: target = op.join(d, target) lnsf(source, target, log=True)
python
def link(args): """ %prog link metafile Link source to target based on a tabular file. """ 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: mkdir(d) fp = open(meta) cwd = op.dirname(get_abs_path(meta)) for row in fp: source, target = row.split() source = op.join(cwd, source) if d: target = op.join(d, target) lnsf(source, target, log=True)
[ "def", "link", "(", "args", ")", ":", "from", "jcvi", ".", "apps", ".", "base", "import", "mkdir", "p", "=", "OptionParser", "(", "link", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--dir\"", ",", "help", "=", "\"Place links in a subdirectory [def...
%prog link metafile Link source to target based on a tabular file.
[ "%prog", "link", "metafile" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/softlink.py#L39-L67
train
200,565
tanghaibao/jcvi
jcvi/apps/softlink.py
touch
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. """ 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) lnsf(source, link_name)
python
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. """ 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) lnsf(source, link_name)
[ "def", "touch", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "touch", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "fp", "=", "sys", ".", "stdin", "for", "link_name", "in", "fp", ":", "link_name"...
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.
[ "find", ".", "-", "type", "l", "|", "%prog", "touch" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/softlink.py#L70-L89
train
200,566
tanghaibao/jcvi
jcvi/apps/softlink.py
cp
def cp(args): """ find folder -type l | %prog cp Copy all the softlinks to the current folder, using absolute paths """ 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.symlink(source, link_name) logging.debug(" => ".join((source, link_name)))
python
def cp(args): """ find folder -type l | %prog cp Copy all the softlinks to the current folder, using absolute paths """ 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.symlink(source, link_name) logging.debug(" => ".join((source, link_name)))
[ "def", "cp", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "cp", ".", "__doc__", ")", "fp", "=", "sys", ".", "stdin", "for", "link_name", "in", "fp", ":", "link_name", "=", "link_name", ".", "strip", "(", ")", "if", "not", "op", ".", "exi...
find folder -type l | %prog cp Copy all the softlinks to the current folder, using absolute paths
[ "find", "folder", "-", "type", "l", "|", "%prog", "cp" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/softlink.py#L108-L126
train
200,567
tanghaibao/jcvi
jcvi/apps/softlink.py
size
def size(args): """ find folder -type l | %prog size Get the size for all the paths that are pointed by the links """ 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(link_name) filesize = op.getsize(source) results.append((filesize, link_name)) # sort by descending file size for filesize, link_name in sorted(results, reverse=True): filesize = human_size(filesize, a_kilobyte_is_1024_bytes=True) print("%10s\t%s" % (filesize, link_name), file=sys.stderr)
python
def size(args): """ find folder -type l | %prog size Get the size for all the paths that are pointed by the links """ 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(link_name) filesize = op.getsize(source) results.append((filesize, link_name)) # sort by descending file size for filesize, link_name in sorted(results, reverse=True): filesize = human_size(filesize, a_kilobyte_is_1024_bytes=True) print("%10s\t%s" % (filesize, link_name), file=sys.stderr)
[ "def", "size", "(", "args", ")", ":", "from", "jcvi", ".", "utils", ".", "cbook", "import", "human_size", "p", "=", "OptionParser", "(", "size", ".", "__doc__", ")", "fp", "=", "sys", ".", "stdin", "results", "=", "[", "]", "for", "link_name", "in", ...
find folder -type l | %prog size Get the size for all the paths that are pointed by the links
[ "find", "folder", "-", "type", "l", "|", "%prog", "size" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/softlink.py#L129-L155
train
200,568
tanghaibao/jcvi
jcvi/projects/alfalfa.py
nucmer
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. """ 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) * m1, idx * m1))) bed.print_to_file(bedfile) cmd = "intersectBed -a {0} -b {1} -nonamecheck -sorted | cut -f4".\ format(mapbed, bedfile) idsfile = "query.ids" sh(cmd, outfile=idsfile) sfasta = fastaFromBed(bedfile, mtrfasta) qfasta = "query.fasta" cmd = "faSomeRecords {0} {1} {2}".format(asmfasta, idsfile, qfasta) sh(cmd) cmd = "nucmer {0} {1}".format(sfasta, qfasta) sh(cmd) mummerplot_main(["out.delta", "--refcov=0"]) sh("mv out.pdf {0}.{1}.pdf".format(chr, idx))
python
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. """ 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) * m1, idx * m1))) bed.print_to_file(bedfile) cmd = "intersectBed -a {0} -b {1} -nonamecheck -sorted | cut -f4".\ format(mapbed, bedfile) idsfile = "query.ids" sh(cmd, outfile=idsfile) sfasta = fastaFromBed(bedfile, mtrfasta) qfasta = "query.fasta" cmd = "faSomeRecords {0} {1} {2}".format(asmfasta, idsfile, qfasta) sh(cmd) cmd = "nucmer {0} {1}".format(sfasta, qfasta) sh(cmd) mummerplot_main(["out.delta", "--refcov=0"]) sh("mv out.pdf {0}.{1}.pdf".format(chr, idx))
[ "def", "nucmer", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "nucmer", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", "5", ":", "sys", ".", "exit", "(", "n...
%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.
[ "%prog", "nucmer", "mappings", ".", "bed", "MTR", ".", "fasta", "assembly", ".", "fasta", "chr1", "3" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/alfalfa.py#L24-L59
train
200,569
tanghaibao/jcvi
jcvi/formats/obo.py
validate_term
def validate_term(term, so=None, method="verify"): """ Validate an SO term against so.obo """ 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(tparts).strip() term = validate_term(nterm, so=so, method=method) if term is None: return None else: logging.error("Term `{0}` does not exist".format(term)) sys.exit(1) if oterm != term: logging.debug("Resolved term `{0}` to `{1}`".format(oterm, term)) return term
python
def validate_term(term, so=None, method="verify"): """ Validate an SO term against so.obo """ 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(tparts).strip() term = validate_term(nterm, so=so, method=method) if term is None: return None else: logging.error("Term `{0}` does not exist".format(term)) sys.exit(1) if oterm != term: logging.debug("Resolved term `{0}` to `{1}`".format(oterm, term)) return term
[ "def", "validate_term", "(", "term", ",", "so", "=", "None", ",", "method", "=", "\"verify\"", ")", ":", "if", "so", "is", "None", ":", "so", "=", "load_GODag", "(", ")", "oterm", "=", "term", "if", "term", "not", "in", "so", ".", "valid_names", ":...
Validate an SO term against so.obo
[ "Validate", "an", "SO", "term", "against", "so", ".", "obo" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/obo.py#L288-L311
train
200,570
tanghaibao/jcvi
jcvi/projects/pistachio.py
agp
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 the .manifest file shipped in the same package:: pistachio_b_23May2017_MeyIy.table.txt Tab-delimited table describing positions of input assembly scaffolds in the Hirise scaffolds. The table has the following format: 1. HiRise scaffold name 2. Input sequence name 3. Starting base (zero-based) of the input sequence 4. Ending base of the input sequence 5. Strand (- or +) of the input sequence in the scaffold 6. Starting base (zero-based) in the HiRise scaffold 7. Ending base in the HiRise scaffold where '-' in the strand column indicates that the sequence is reverse complemented relative to the input assembly. CAUTION: This is NOT a proper AGP format since it does not have gaps in them. """ 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 scaf_end = int(atoms[3]) strand = atoms[4] hr_start = int(atoms[5]) + 1 hr_end = int(atoms[6]) print("\t".join(str(x) for x in \ (hr, hr_start, hr_end, 1, 'W', scaf, scaf_start, scaf_end, strand)))
python
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 the .manifest file shipped in the same package:: pistachio_b_23May2017_MeyIy.table.txt Tab-delimited table describing positions of input assembly scaffolds in the Hirise scaffolds. The table has the following format: 1. HiRise scaffold name 2. Input sequence name 3. Starting base (zero-based) of the input sequence 4. Ending base of the input sequence 5. Strand (- or +) of the input sequence in the scaffold 6. Starting base (zero-based) in the HiRise scaffold 7. Ending base in the HiRise scaffold where '-' in the strand column indicates that the sequence is reverse complemented relative to the input assembly. CAUTION: This is NOT a proper AGP format since it does not have gaps in them. """ 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 scaf_end = int(atoms[3]) strand = atoms[4] hr_start = int(atoms[5]) + 1 hr_end = int(atoms[6]) print("\t".join(str(x) for x in \ (hr, hr_start, hr_end, 1, 'W', scaf, scaf_start, scaf_end, strand)))
[ "def", "agp", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "agp", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", "1", ":", "sys", ".", "exit", "(", "not", ...
%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 the .manifest file shipped in the same package:: pistachio_b_23May2017_MeyIy.table.txt Tab-delimited table describing positions of input assembly scaffolds in the Hirise scaffolds. The table has the following format: 1. HiRise scaffold name 2. Input sequence name 3. Starting base (zero-based) of the input sequence 4. Ending base of the input sequence 5. Strand (- or +) of the input sequence in the scaffold 6. Starting base (zero-based) in the HiRise scaffold 7. Ending base in the HiRise scaffold where '-' in the strand column indicates that the sequence is reverse complemented relative to the input assembly. CAUTION: This is NOT a proper AGP format since it does not have gaps in them.
[ "%prog", "agp", "Siirt_Female_pistachio_23May2017_table", ".", "txt" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/pistachio.py#L24-L71
train
200,571
tanghaibao/jcvi
jcvi/projects/age.py
traits
def traits(args): """ %prog traits directory Make HTML page that reports eye and skin color. """ 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 = json.load(open(filename)) js["skin_rgb"] = make_rgb( js["traits"]["skin-color"]["L"], js["traits"]["skin-color"]["A"], js["traits"]["skin-color"]["B"]) js["eye_rgb"] = make_rgb( js["traits"]["eye-color"]["L"], js["traits"]["eye-color"]["A"], js["traits"]["eye-color"]["B"]) samples.append(js) template = Template(traits_template) fw = open("report.html", "w") print(template.render(samples=samples), file=fw) logging.debug("Report written to `{}`".format(fw.name)) fw.close()
python
def traits(args): """ %prog traits directory Make HTML page that reports eye and skin color. """ 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 = json.load(open(filename)) js["skin_rgb"] = make_rgb( js["traits"]["skin-color"]["L"], js["traits"]["skin-color"]["A"], js["traits"]["skin-color"]["B"]) js["eye_rgb"] = make_rgb( js["traits"]["eye-color"]["L"], js["traits"]["eye-color"]["A"], js["traits"]["eye-color"]["B"]) samples.append(js) template = Template(traits_template) fw = open("report.html", "w") print(template.render(samples=samples), file=fw) logging.debug("Report written to `{}`".format(fw.name)) fw.close()
[ "def", "traits", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "traits", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "<", "1", ":", "sys", ".", "exit", "(", "no...
%prog traits directory Make HTML page that reports eye and skin color.
[ "%prog", "traits", "directory" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/age.py#L126-L159
train
200,572
tanghaibao/jcvi
jcvi/projects/age.py
regression
def regression(args): """ %prog regression postgenomic-s.tsv Plot chronological vs. predicted age. """ 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.DataFrame({chrono: df["hli_calc_age_sample_taken"], pred: df["Predicted Age"]}) g = sns.jointplot(chrono, pred, resdf, joint_kws={"s": 6}, xlim=(0, 100), ylim=(0, 80)) g.fig.set_figwidth(iopts.w) g.fig.set_figheight(iopts.h) outfile = tsvfile.rsplit(".", 1)[0] + ".regression.pdf" savefig(outfile)
python
def regression(args): """ %prog regression postgenomic-s.tsv Plot chronological vs. predicted age. """ 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.DataFrame({chrono: df["hli_calc_age_sample_taken"], pred: df["Predicted Age"]}) g = sns.jointplot(chrono, pred, resdf, joint_kws={"s": 6}, xlim=(0, 100), ylim=(0, 80)) g.fig.set_figwidth(iopts.w) g.fig.set_figheight(iopts.h) outfile = tsvfile.rsplit(".", 1)[0] + ".regression.pdf" savefig(outfile)
[ "def", "regression", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "regression", ".", "__doc__", ")", "opts", ",", "args", ",", "iopts", "=", "p", ".", "set_image_options", "(", "args", ",", "figsize", "=", "\"8x8\"", ")", "if", "len", "(", "...
%prog regression postgenomic-s.tsv Plot chronological vs. predicted age.
[ "%prog", "regression", "postgenomic", "-", "s", ".", "tsv" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/age.py#L256-L278
train
200,573
tanghaibao/jcvi
jcvi/projects/age.py
composite_correlation
def composite_correlation(df, size=(12, 8)): """ Plot composite correlation figure """ 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(zip(chemistry, colors)) age_label = "Chronological age (yr)" ax1.scatter(df["hli_calc_age_sample_taken"], df["teloLength"], s=10, marker='.', color=df["Chemistry"].map(color_map)) ax1.set_ylim(0, 15) ax1.set_ylabel("Telomere length (Kb)") ax2.scatter(df["hli_calc_age_sample_taken"], df["ccn.chrX"], s=10, marker='.', color=df["Chemistry"].map(color_map)) ax2.set_ylim(1.8, 2.1) ax2.set_ylabel("ChrX copy number") ax4.scatter(df["hli_calc_age_sample_taken"], df["ccn.chrY"], s=10, marker='.', color=df["Chemistry"].map(color_map)) ax4.set_ylim(0.8, 1.1) ax4.set_ylabel("ChrY copy number") ax3.scatter(df["hli_calc_age_sample_taken"], df["TRA.PPM"], s=10, marker='.', color=df["Chemistry"].map(color_map)) ax3.set_ylim(0, 250) ax3.set_ylabel("$TCR-\\alpha$ deletions (count per million reads)") from matplotlib.lines import Line2D legend_elements = [Line2D([0], [0], marker='.', color='w', label=chem, markerfacecolor=color, markersize=16) \ for (chem, color) in zip(chemistry, colors)[:3]] for ax in (ax1, ax2, ax3, ax4): ax.set_xlabel(age_label) ax.legend(handles=legend_elements, loc="upper right") plt.tight_layout() root = fig.add_axes((0, 0, 1, 1)) labels = ((.02, .98, "A"), (.52, .98, "B"), (.02, .5, "C"), (.52, .5, "D")) panel_labels(root, labels) root.set_xlim(0, 1) root.set_ylim(0, 1) root.set_axis_off()
python
def composite_correlation(df, size=(12, 8)): """ Plot composite correlation figure """ 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(zip(chemistry, colors)) age_label = "Chronological age (yr)" ax1.scatter(df["hli_calc_age_sample_taken"], df["teloLength"], s=10, marker='.', color=df["Chemistry"].map(color_map)) ax1.set_ylim(0, 15) ax1.set_ylabel("Telomere length (Kb)") ax2.scatter(df["hli_calc_age_sample_taken"], df["ccn.chrX"], s=10, marker='.', color=df["Chemistry"].map(color_map)) ax2.set_ylim(1.8, 2.1) ax2.set_ylabel("ChrX copy number") ax4.scatter(df["hli_calc_age_sample_taken"], df["ccn.chrY"], s=10, marker='.', color=df["Chemistry"].map(color_map)) ax4.set_ylim(0.8, 1.1) ax4.set_ylabel("ChrY copy number") ax3.scatter(df["hli_calc_age_sample_taken"], df["TRA.PPM"], s=10, marker='.', color=df["Chemistry"].map(color_map)) ax3.set_ylim(0, 250) ax3.set_ylabel("$TCR-\\alpha$ deletions (count per million reads)") from matplotlib.lines import Line2D legend_elements = [Line2D([0], [0], marker='.', color='w', label=chem, markerfacecolor=color, markersize=16) \ for (chem, color) in zip(chemistry, colors)[:3]] for ax in (ax1, ax2, ax3, ax4): ax.set_xlabel(age_label) ax.legend(handles=legend_elements, loc="upper right") plt.tight_layout() root = fig.add_axes((0, 0, 1, 1)) labels = ((.02, .98, "A"), (.52, .98, "B"), (.02, .5, "C"), (.52, .5, "D")) panel_labels(root, labels) root.set_xlim(0, 1) root.set_ylim(0, 1) root.set_axis_off()
[ "def", "composite_correlation", "(", "df", ",", "size", "=", "(", "12", ",", "8", ")", ")", ":", "fig", "=", "plt", ".", "figure", "(", "1", ",", "size", ")", "ax1", "=", "plt", ".", "subplot2grid", "(", "(", "2", ",", "2", ")", ",", "(", "0"...
Plot composite correlation figure
[ "Plot", "composite", "correlation", "figure" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/age.py#L281-L335
train
200,574
tanghaibao/jcvi
jcvi/projects/age.py
correlation
def correlation(args): """ %prog correlation postgenomic-s.tsv Plot correlation of age vs. postgenomic features. """ 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(".", 1)[0] + ".correlation.pdf" savefig(outfile)
python
def correlation(args): """ %prog correlation postgenomic-s.tsv Plot correlation of age vs. postgenomic features. """ 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(".", 1)[0] + ".correlation.pdf" savefig(outfile)
[ "def", "correlation", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "correlation", ".", "__doc__", ")", "opts", ",", "args", ",", "iopts", "=", "p", ".", "set_image_options", "(", "args", ",", "figsize", "=", "\"12x8\"", ")", "if", "len", "(", ...
%prog correlation postgenomic-s.tsv Plot correlation of age vs. postgenomic features.
[ "%prog", "correlation", "postgenomic", "-", "s", ".", "tsv" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/age.py#L338-L354
train
200,575
tanghaibao/jcvi
jcvi/projects/age.py
extract_twin_values
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 trait values of the twins """ # 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): traitValuesAbsent += 1 continue if np.isnan(traits[a]) or np.isnan(traits[b]): nanValues += 1 continue twinValues.append((traits[a], traits[b])) print("A total of {} pairs extracted ({} absent; {} nan; {} genderSkipped)"\ .format(len(twinValues), traitValuesAbsent, nanValues, genderSkipped)) return twinValues
python
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 trait values of the twins """ # 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): traitValuesAbsent += 1 continue if np.isnan(traits[a]) or np.isnan(traits[b]): nanValues += 1 continue twinValues.append((traits[a], traits[b])) print("A total of {} pairs extracted ({} absent; {} nan; {} genderSkipped)"\ .format(len(twinValues), traitValuesAbsent, nanValues, genderSkipped)) return twinValues
[ "def", "extract_twin_values", "(", "triples", ",", "traits", ",", "gender", "=", "None", ")", ":", "# Construct the pairs of trait values", "traitValuesAbsent", "=", "0", "nanValues", "=", "0", "genderSkipped", "=", "0", "twinValues", "=", "[", "]", "for", "a", ...
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 trait values of the twins
[ "Calculate", "the", "heritability", "of", "certain", "traits", "in", "triplets", "." ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/age.py#L464-L496
train
200,576
tanghaibao/jcvi
jcvi/projects/age.py
heritability
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 """ 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: yield row.strip().split(",") MZ = list(get_pairs(mz)) DZ = list(get_pairs(dz)) print(len(MZ), "monozygotic twins") print(len(DZ), "dizygotic twins") df = pd.read_csv(combined, sep="\t", index_col=0) df["Sample name"] = np.array(df["Sample name"], dtype=np.str) gender = extract_trait(df, "Sample name", "hli_calc_gender") sameGenderMZ = list(filter_same_gender(MZ, gender)) sameGenderDZ = list(filter_same_gender(DZ, gender)) composite(df, sameGenderMZ, sameGenderDZ, size=(iopts.w, iopts.h)) logging.getLogger().setLevel(logging.CRITICAL) savefig("heritability.pdf")
python
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 """ 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: yield row.strip().split(",") MZ = list(get_pairs(mz)) DZ = list(get_pairs(dz)) print(len(MZ), "monozygotic twins") print(len(DZ), "dizygotic twins") df = pd.read_csv(combined, sep="\t", index_col=0) df["Sample name"] = np.array(df["Sample name"], dtype=np.str) gender = extract_trait(df, "Sample name", "hli_calc_gender") sameGenderMZ = list(filter_same_gender(MZ, gender)) sameGenderDZ = list(filter_same_gender(DZ, gender)) composite(df, sameGenderMZ, sameGenderDZ, size=(iopts.w, iopts.h)) logging.getLogger().setLevel(logging.CRITICAL) savefig("heritability.pdf")
[ "def", "heritability", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "heritability", ".", "__doc__", ")", "opts", ",", "args", ",", "iopts", "=", "p", ".", "set_image_options", "(", "args", ",", "figsize", "=", "\"12x18\"", ")", "if", "len", "(...
%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
[ "%prog", "pg", ".", "tsv", "MZ", "-", "twins", ".", "csv", "DZ", "-", "twins", ".", "csv" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/age.py#L590-L626
train
200,577
tanghaibao/jcvi
jcvi/projects/age.py
compile
def compile(args): """ %prog compile directory Extract telomere length and ccn. """ 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.startswith("telomeres")][0] subdir = op.join(folder, subdir) filename = op.join(subdir, "tel_lengths.txt") df = pd.read_csv(filename, sep="\t") d1 = df.ix[0].to_dict() # ccn subdir = [x for x in ofolder if x.startswith("ccn")][0] subdir = op.join(folder, subdir) filename = iglob(subdir, "*.ccn.json")[0] js = json.load(open(filename)) d1.update(js) df = pd.DataFrame(d1, index=[0]) dfs.append(df) df = pd.concat(dfs, ignore_index=True) df.to_csv(opts.outfile, sep="\t", index=False)
python
def compile(args): """ %prog compile directory Extract telomere length and ccn. """ 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.startswith("telomeres")][0] subdir = op.join(folder, subdir) filename = op.join(subdir, "tel_lengths.txt") df = pd.read_csv(filename, sep="\t") d1 = df.ix[0].to_dict() # ccn subdir = [x for x in ofolder if x.startswith("ccn")][0] subdir = op.join(folder, subdir) filename = iglob(subdir, "*.ccn.json")[0] js = json.load(open(filename)) d1.update(js) df = pd.DataFrame(d1, index=[0]) dfs.append(df) df = pd.concat(dfs, ignore_index=True) df.to_csv(opts.outfile, sep="\t", index=False)
[ "def", "compile", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "compile", ".", "__doc__", ")", "p", ".", "set_outfile", "(", "outfile", "=", "\"age.tsv\"", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len",...
%prog compile directory Extract telomere length and ccn.
[ "%prog", "compile", "directory" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/age.py#L629-L663
train
200,578
tanghaibao/jcvi
jcvi/formats/fasta.py
simulate_one
def simulate_one(fw, name, size): """ Simulate a random sequence with name and size """ 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")
python
def simulate_one(fw, name, size): """ Simulate a random sequence with name and size """ 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", ")", ":", "from", "random", "import", "choice", "seq", "=", "Seq", "(", "''", ".", "join", "(", "choice", "(", "'ACGT'", ")", "for", "_", "in", "xrange", "(", "size", ")", ")", ")", "s",...
Simulate a random sequence with name and size
[ "Simulate", "a", "random", "sequence", "with", "name", "and", "size" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/fasta.py#L387-L394
train
200,579
tanghaibao/jcvi
jcvi/formats/fasta.py
simulate
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. """ 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) simulate_one(fw, name, size) fp.close()
python
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. """ 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) simulate_one(fw, name, size) fp.close()
[ "def", "simulate", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "simulate", ".", "__doc__", ")", "p", ".", "set_outfile", "(", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", ...
%prog simulate idsfile Simulate random FASTA file based on idsfile, which is a two-column tab-separated file with sequence name and size.
[ "%prog", "simulate", "idsfile" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/fasta.py#L397-L418
train
200,580
tanghaibao/jcvi
jcvi/formats/fasta.py
gc
def gc(args): """ %prog gc fastafile Plot G+C content distribution. """ 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 parse_fasta(fastafile): for i in range(len(seq) / binsize): atcnt = gccnt = 0 for c in seq[i * binsize: (i + 1) * binsize].upper(): if c in "AT": atcnt += 1 elif c in "GC": gccnt += 1 totalcnt = atcnt + gccnt if totalcnt == 0: continue gcpct = gccnt * 100 / totalcnt allbins.append(gcpct) from jcvi.graphics.base import asciiplot from collections import Counter title = "Total number of bins={}".format(len(allbins)) c = Counter(allbins) x, y = zip(*sorted(c.items())) asciiplot(x, y, title=title)
python
def gc(args): """ %prog gc fastafile Plot G+C content distribution. """ 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 parse_fasta(fastafile): for i in range(len(seq) / binsize): atcnt = gccnt = 0 for c in seq[i * binsize: (i + 1) * binsize].upper(): if c in "AT": atcnt += 1 elif c in "GC": gccnt += 1 totalcnt = atcnt + gccnt if totalcnt == 0: continue gcpct = gccnt * 100 / totalcnt allbins.append(gcpct) from jcvi.graphics.base import asciiplot from collections import Counter title = "Total number of bins={}".format(len(allbins)) c = Counter(allbins) x, y = zip(*sorted(c.items())) asciiplot(x, y, title=title)
[ "def", "gc", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "gc", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--binsize\"", ",", "default", "=", "500", ",", "type", "=", "\"int\"", ",", "help", "=", "\"Bin size to use\"", ")", "opts", ...
%prog gc fastafile Plot G+C content distribution.
[ "%prog", "gc", "fastafile" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/fasta.py#L421-L458
train
200,581
tanghaibao/jcvi
jcvi/formats/fasta.py
trimsplit
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. """ 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, = args minlength = opts.minlength fw = must_open(fastafile.rsplit(".", 1)[0] + ".split.fasta", "w") ntotal = 0 removed = [] Ns = [] for name, seq in parse_fasta(fastafile): stretches = [] ntotal += len(seq) for lower, stretch in groupby(seq, key=lambda x: x.islower()): stretch = "".join(stretch) if lower or len(stretch) < minlength: removed.append(len(stretch)) continue for isN, s in groupby(stretch, key=lambda x: x in "Nn"): s = "".join(s) if isN or len(s) < minlength: Ns.append(len(s)) continue stretches.append(s) for i, seq in enumerate(stretches): id = "{0}_{1}".format(name.split("|")[0], i) s = SeqRecord(Seq(seq), id=id, description="") SeqIO.write([s], fw, "fasta") fw.close() # Reporting if removed: logging.debug("Total bases removed: {0}".\ format(percentage(sum(removed), ntotal))) print(SummaryStats(removed), file=sys.stderr) if Ns: logging.debug("Total Ns removed: {0}".\ format(percentage(sum(Ns), ntotal))) print(SummaryStats(Ns), file=sys.stderr)
python
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. """ 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, = args minlength = opts.minlength fw = must_open(fastafile.rsplit(".", 1)[0] + ".split.fasta", "w") ntotal = 0 removed = [] Ns = [] for name, seq in parse_fasta(fastafile): stretches = [] ntotal += len(seq) for lower, stretch in groupby(seq, key=lambda x: x.islower()): stretch = "".join(stretch) if lower or len(stretch) < minlength: removed.append(len(stretch)) continue for isN, s in groupby(stretch, key=lambda x: x in "Nn"): s = "".join(s) if isN or len(s) < minlength: Ns.append(len(s)) continue stretches.append(s) for i, seq in enumerate(stretches): id = "{0}_{1}".format(name.split("|")[0], i) s = SeqRecord(Seq(seq), id=id, description="") SeqIO.write([s], fw, "fasta") fw.close() # Reporting if removed: logging.debug("Total bases removed: {0}".\ format(percentage(sum(removed), ntotal))) print(SummaryStats(removed), file=sys.stderr) if Ns: logging.debug("Total Ns removed: {0}".\ format(percentage(sum(Ns), ntotal))) print(SummaryStats(Ns), file=sys.stderr)
[ "def", "trimsplit", "(", "args", ")", ":", "from", "jcvi", ".", "utils", ".", "cbook", "import", "SummaryStats", "p", "=", "OptionParser", "(", "trimsplit", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--minlength\"", ",", "default", "=", "1000", ...
%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.
[ "%prog", "trimsplit", "fastafile" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/fasta.py#L461-L513
train
200,582
tanghaibao/jcvi
jcvi/formats/fasta.py
qual
def qual(args): """ %prog qual fastafile Generate dummy .qual file based on FASTA file. """ 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()) fastafile, = args sizes = Sizes(fastafile) qvchar = str(opts.qv) fw = must_open(opts.outfile, "w") total = 0 for s, slen in sizes.iter_sizes(): print(">" + s, file=fw) print(" ".join([qvchar] * slen), file=fw) total += 1 fw.close() logging.debug("Written {0} records in `{1}`.".format(total, opts.outfile))
python
def qual(args): """ %prog qual fastafile Generate dummy .qual file based on FASTA file. """ 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()) fastafile, = args sizes = Sizes(fastafile) qvchar = str(opts.qv) fw = must_open(opts.outfile, "w") total = 0 for s, slen in sizes.iter_sizes(): print(">" + s, file=fw) print(" ".join([qvchar] * slen), file=fw) total += 1 fw.close() logging.debug("Written {0} records in `{1}`.".format(total, opts.outfile))
[ "def", "qual", "(", "args", ")", ":", "from", "jcvi", ".", "formats", ".", "sizes", "import", "Sizes", "p", "=", "OptionParser", "(", "qual", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--qv\"", ",", "default", "=", "31", ",", "type", "=", ...
%prog qual fastafile Generate dummy .qual file based on FASTA file.
[ "%prog", "qual", "fastafile" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/fasta.py#L516-L543
train
200,583
tanghaibao/jcvi
jcvi/formats/fasta.py
fromtab
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. """ 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) if len(args) != 2: sys.exit(not p.print_help()) tabfile, fastafile = args sep = opts.sep replace = opts.replace fp = must_open(tabfile) fw = must_open(fastafile, "w") nseq = 0 if opts.noheader: next(fp) for row in fp: row = row.strip() if not row or row[0] == '#': continue name, seq = row.rsplit(sep, 1) if replace: name = name.replace(" ", replace) print(">{0}\n{1}".format(name, seq), file=fw) nseq += 1 fw.close() logging.debug("A total of {0} sequences written to `{1}`.".\ format(nseq, fastafile))
python
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. """ 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) if len(args) != 2: sys.exit(not p.print_help()) tabfile, fastafile = args sep = opts.sep replace = opts.replace fp = must_open(tabfile) fw = must_open(fastafile, "w") nseq = 0 if opts.noheader: next(fp) for row in fp: row = row.strip() if not row or row[0] == '#': continue name, seq = row.rsplit(sep, 1) if replace: name = name.replace(" ", replace) print(">{0}\n{1}".format(name, seq), file=fw) nseq += 1 fw.close() logging.debug("A total of {0} sequences written to `{1}`.".\ format(nseq, fastafile))
[ "def", "fromtab", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "fromtab", ".", "__doc__", ")", "p", ".", "set_sep", "(", "sep", "=", "None", ")", "p", ".", "add_option", "(", "\"--noheader\"", ",", "default", "=", "False", ",", "action", "="...
%prog fromtab tabfile fastafile Convert 2-column sequence file to FASTA format. One usage for this is to generatea `adapters.fasta` for TRIMMOMATIC.
[ "%prog", "fromtab", "tabfile", "fastafile" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/fasta.py#L571-L610
train
200,584
tanghaibao/jcvi
jcvi/formats/fasta.py
longestorf
def longestorf(args): """ %prog longestorf fastafile Find longest ORF for each sequence in fastafile. """ 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)[0] orffile = pf + ".orf.fasta" idsfile = None if opts.ids: idsfile = pf + ".orf.ids" fwids = open(idsfile, "w") f = Fasta(fastafile, lazy=True) fw = must_open(orffile, "w") before, after = 0, 0 for name, rec in f.iteritems_ordered(): cds = rec.seq before += len(cds) # Try all six frames orf = ORFFinder(cds) lorf = orf.get_longest_orf() newcds = Seq(lorf) after += len(newcds) newrec = SeqRecord(newcds, id=name, description=rec.description) SeqIO.write([newrec], fw, "fasta") if idsfile: print("\t".join((name, orf.info)), file=fwids) fw.close() if idsfile: fwids.close() logging.debug("Longest ORFs written to `{0}` ({1}).".\ format(orffile, percentage(after, before))) return orffile
python
def longestorf(args): """ %prog longestorf fastafile Find longest ORF for each sequence in fastafile. """ 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)[0] orffile = pf + ".orf.fasta" idsfile = None if opts.ids: idsfile = pf + ".orf.ids" fwids = open(idsfile, "w") f = Fasta(fastafile, lazy=True) fw = must_open(orffile, "w") before, after = 0, 0 for name, rec in f.iteritems_ordered(): cds = rec.seq before += len(cds) # Try all six frames orf = ORFFinder(cds) lorf = orf.get_longest_orf() newcds = Seq(lorf) after += len(newcds) newrec = SeqRecord(newcds, id=name, description=rec.description) SeqIO.write([newrec], fw, "fasta") if idsfile: print("\t".join((name, orf.info)), file=fwids) fw.close() if idsfile: fwids.close() logging.debug("Longest ORFs written to `{0}` ({1}).".\ format(orffile, percentage(after, before))) return orffile
[ "def", "longestorf", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "longestorf", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--ids\"", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Generate table with ORF info [default: %default]\"", ...
%prog longestorf fastafile Find longest ORF for each sequence in fastafile.
[ "%prog", "longestorf", "fastafile" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/fasta.py#L613-L658
train
200,585
tanghaibao/jcvi
jcvi/formats/fasta.py
ispcr
def ispcr(args): """ %prog ispcr fastafile Reformat paired primers into isPcr query format, which is three column format: name, forward, reverse """ 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()) fastafile, = args ispcrfile = fastafile + ".isPcr" fw = open(ispcrfile, "w") N = opts.rclip strip_name = lambda x: x[:-N] if N else str npairs = 0 fastaiter = SeqIO.parse(fastafile, "fasta") for a, b in grouper(fastaiter, 2): aid, bid = [strip_name(x) for x in (a.id, b.id)] assert aid == bid, "Name mismatch {0}".format((aid, bid)) print("\t".join((aid, str(a.seq), str(b.seq))), file=fw) npairs += 1 fw.close() logging.debug("A total of {0} pairs written to `{1}`.".\ format(npairs, ispcrfile))
python
def ispcr(args): """ %prog ispcr fastafile Reformat paired primers into isPcr query format, which is three column format: name, forward, reverse """ 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()) fastafile, = args ispcrfile = fastafile + ".isPcr" fw = open(ispcrfile, "w") N = opts.rclip strip_name = lambda x: x[:-N] if N else str npairs = 0 fastaiter = SeqIO.parse(fastafile, "fasta") for a, b in grouper(fastaiter, 2): aid, bid = [strip_name(x) for x in (a.id, b.id)] assert aid == bid, "Name mismatch {0}".format((aid, bid)) print("\t".join((aid, str(a.seq), str(b.seq))), file=fw) npairs += 1 fw.close() logging.debug("A total of {0} pairs written to `{1}`.".\ format(npairs, ispcrfile))
[ "def", "ispcr", "(", "args", ")", ":", "from", "jcvi", ".", "utils", ".", "iter", "import", "grouper", "p", "=", "OptionParser", "(", "ispcr", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"-r\"", ",", "dest", "=", "\"rclip\"", ",", "default", ...
%prog ispcr fastafile Reformat paired primers into isPcr query format, which is three column format: name, forward, reverse
[ "%prog", "ispcr", "fastafile" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/fasta.py#L661-L697
train
200,586
tanghaibao/jcvi
jcvi/formats/fasta.py
parse_fasta
def parse_fasta(infile, upper=False): ''' 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: header = next(header) if header[0] != '>': continue # drop '>' header = header.strip()[1:] # stitch the sequence lines together and make into upper case seq = "".join(s.strip() for s in next(fa_iter)) if upper: seq = seq.upper() yield header, seq
python
def parse_fasta(infile, upper=False): ''' 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: header = next(header) if header[0] != '>': continue # drop '>' header = header.strip()[1:] # stitch the sequence lines together and make into upper case seq = "".join(s.strip() for s in next(fa_iter)) if upper: seq = seq.upper() yield header, seq
[ "def", "parse_fasta", "(", "infile", ",", "upper", "=", "False", ")", ":", "try", ":", "fp", "=", "must_open", "(", "infile", ")", "except", ":", "fp", "=", "infile", "# keep header", "fa_iter", "=", "(", "x", "[", "1", "]", "for", "x", "in", "grou...
parse a fasta-formatted file and returns header can be a fasta file that contains multiple records.
[ "parse", "a", "fasta", "-", "formatted", "file", "and", "returns", "header", "can", "be", "a", "fasta", "file", "that", "contains", "multiple", "records", "." ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/fasta.py#L700-L721
train
200,587
tanghaibao/jcvi
jcvi/formats/fasta.py
clean
def clean(args): """ %prog clean fastafile Remove irregular chars in FASTA seqs. """ p = OptionParser(clean.__doc__) p.add_option("--fancy", default=False, action="store_true", help="Pretty print the sequence [default: %default]") p.add_option("--canonical", default=False, action="store_true", help="Use only acgtnACGTN [default: %default]") p.set_outfile() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) fastafile, = args fw = must_open(opts.outfile, "w") if opts.fancy: for header, seq in iter_clean_fasta(fastafile): print(">" + header, file=fw) fancyprint(fw, seq) return 0 iterator = iter_canonical_fasta if opts.canonical else iter_clean_fasta for header, seq in iterator(fastafile): seq = Seq(seq) s = SeqRecord(seq, id=header, description="") SeqIO.write([s], fw, "fasta")
python
def clean(args): """ %prog clean fastafile Remove irregular chars in FASTA seqs. """ p = OptionParser(clean.__doc__) p.add_option("--fancy", default=False, action="store_true", help="Pretty print the sequence [default: %default]") p.add_option("--canonical", default=False, action="store_true", help="Use only acgtnACGTN [default: %default]") p.set_outfile() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) fastafile, = args fw = must_open(opts.outfile, "w") if opts.fancy: for header, seq in iter_clean_fasta(fastafile): print(">" + header, file=fw) fancyprint(fw, seq) return 0 iterator = iter_canonical_fasta if opts.canonical else iter_clean_fasta for header, seq in iterator(fastafile): seq = Seq(seq) s = SeqRecord(seq, id=header, description="") SeqIO.write([s], fw, "fasta")
[ "def", "clean", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "clean", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--fancy\"", ",", "default", "=", "False", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Pretty print the sequen...
%prog clean fastafile Remove irregular chars in FASTA seqs.
[ "%prog", "clean", "fastafile" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/fasta.py#L758-L790
train
200,588
tanghaibao/jcvi
jcvi/formats/fasta.py
filter
def filter(args): """ %prog filter fastafile 100 Filter the FASTA file to contain records with size >= or <= certain cutoff. """ p = OptionParser(filter.__doc__) p.add_option("--less", default=False, action="store_true", help="filter the sizes < certain cutoff [default: >=]") p.set_outfile() opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) fastafile, cutoff = args try: cutoff = int(cutoff) except ValueError: sys.exit(not p.print_help()) f = Fasta(fastafile, lazy=True) fw = must_open(opts.outfile, "w") for name, rec in f.iteritems_ordered(): if opts.less and len(rec) >= cutoff: continue if (not opts.less) and len(rec) < cutoff: continue SeqIO.write([rec], fw, "fasta") fw.flush() return fw.name
python
def filter(args): """ %prog filter fastafile 100 Filter the FASTA file to contain records with size >= or <= certain cutoff. """ p = OptionParser(filter.__doc__) p.add_option("--less", default=False, action="store_true", help="filter the sizes < certain cutoff [default: >=]") p.set_outfile() opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) fastafile, cutoff = args try: cutoff = int(cutoff) except ValueError: sys.exit(not p.print_help()) f = Fasta(fastafile, lazy=True) fw = must_open(opts.outfile, "w") for name, rec in f.iteritems_ordered(): if opts.less and len(rec) >= cutoff: continue if (not opts.less) and len(rec) < cutoff: continue SeqIO.write([rec], fw, "fasta") fw.flush() return fw.name
[ "def", "filter", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "filter", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--less\"", ",", "default", "=", "False", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"filter the sizes < cer...
%prog filter fastafile 100 Filter the FASTA file to contain records with size >= or <= certain cutoff.
[ "%prog", "filter", "fastafile", "100" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/fasta.py#L902-L938
train
200,589
tanghaibao/jcvi
jcvi/formats/fasta.py
pool
def pool(args): """ %prog pool fastafiles > pool.fasta Pool a bunch of FASTA files, and add prefix to each record based on filenames. File names are simplified to longest unique prefix to avoid collisions after getting shortened. """ from jcvi.formats.base import longest_unique_prefix p = OptionParser(pool.__doc__) p.add_option("--sep", default=".", help="Separator between prefix and name") p.add_option("--sequential", default=False, action="store_true", help="Add sequential IDs") opts, args = p.parse_args(args) if len(args) < 1: sys.exit(not p.print_help()) for fastafile in args: pf = longest_unique_prefix(fastafile, args) print(fastafile, "=>", pf, file=sys.stderr) prefixopt = "--prefix={0}{1}".format(pf, opts.sep) format_args = [fastafile, "stdout", prefixopt] if opts.sequential: format_args += ["--sequential=replace"] format(format_args)
python
def pool(args): """ %prog pool fastafiles > pool.fasta Pool a bunch of FASTA files, and add prefix to each record based on filenames. File names are simplified to longest unique prefix to avoid collisions after getting shortened. """ from jcvi.formats.base import longest_unique_prefix p = OptionParser(pool.__doc__) p.add_option("--sep", default=".", help="Separator between prefix and name") p.add_option("--sequential", default=False, action="store_true", help="Add sequential IDs") opts, args = p.parse_args(args) if len(args) < 1: sys.exit(not p.print_help()) for fastafile in args: pf = longest_unique_prefix(fastafile, args) print(fastafile, "=>", pf, file=sys.stderr) prefixopt = "--prefix={0}{1}".format(pf, opts.sep) format_args = [fastafile, "stdout", prefixopt] if opts.sequential: format_args += ["--sequential=replace"] format(format_args)
[ "def", "pool", "(", "args", ")", ":", "from", "jcvi", ".", "formats", ".", "base", "import", "longest_unique_prefix", "p", "=", "OptionParser", "(", "pool", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--sep\"", ",", "default", "=", "\".\"", ",",...
%prog pool fastafiles > pool.fasta Pool a bunch of FASTA files, and add prefix to each record based on filenames. File names are simplified to longest unique prefix to avoid collisions after getting shortened.
[ "%prog", "pool", "fastafiles", ">", "pool", ".", "fasta" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/fasta.py#L941-L967
train
200,590
tanghaibao/jcvi
jcvi/formats/fasta.py
ids
def ids(args): """ %prog ids fastafiles Generate the FASTA headers without the '>'. """ p = OptionParser(ids.__doc__) p.add_option("--until", default=None, help="Truncate the name and description at words [default: %default]") p.add_option("--description", default=False, action="store_true", help="Generate a second column with description [default: %default]") p.set_outfile() opts, args = p.parse_args(args) if len(args) < 1: sys.exit(not p.print_help()) until = opts.until fw = must_open(opts.outfile, "w") for row in must_open(args): if row[0] == ">": row = row[1:].rstrip() if until: row = row.split(until)[0] atoms = row.split(None, 1) if opts.description: outrow = "\t".join(atoms) else: outrow = atoms[0] print(outrow, file=fw) fw.close()
python
def ids(args): """ %prog ids fastafiles Generate the FASTA headers without the '>'. """ p = OptionParser(ids.__doc__) p.add_option("--until", default=None, help="Truncate the name and description at words [default: %default]") p.add_option("--description", default=False, action="store_true", help="Generate a second column with description [default: %default]") p.set_outfile() opts, args = p.parse_args(args) if len(args) < 1: sys.exit(not p.print_help()) until = opts.until fw = must_open(opts.outfile, "w") for row in must_open(args): if row[0] == ">": row = row[1:].rstrip() if until: row = row.split(until)[0] atoms = row.split(None, 1) if opts.description: outrow = "\t".join(atoms) else: outrow = atoms[0] print(outrow, file=fw) fw.close()
[ "def", "ids", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "ids", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--until\"", ",", "default", "=", "None", ",", "help", "=", "\"Truncate the name and description at words [default: %default]\"", ")", ...
%prog ids fastafiles Generate the FASTA headers without the '>'.
[ "%prog", "ids", "fastafiles" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/fasta.py#L970-L1003
train
200,591
tanghaibao/jcvi
jcvi/formats/fasta.py
sort
def sort(args): """ %prog sort fastafile Sort a list of sequences and output with sorted IDs, etc. """ p = OptionParser(sort.__doc__) p.add_option("--sizes", default=False, action="store_true", help="Sort by decreasing size [default: %default]") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(p.print_help()) fastafile, = args sortedfastafile = fastafile.rsplit(".", 1)[0] + ".sorted.fasta" f = Fasta(fastafile, index=False) fw = must_open(sortedfastafile, "w") if opts.sizes: # Sort by decreasing size sortlist = sorted(f.itersizes(), key=lambda x: (-x[1], x[0])) logging.debug("Sort by size: max: {0}, min: {1}".\ format(sortlist[0], sortlist[-1])) sortlist = [x for x, s in sortlist] else: sortlist = sorted(f.iterkeys()) for key in sortlist: rec = f[key] SeqIO.write([rec], fw, "fasta") logging.debug("Sorted file written to `{0}`.".format(sortedfastafile)) fw.close() return sortedfastafile
python
def sort(args): """ %prog sort fastafile Sort a list of sequences and output with sorted IDs, etc. """ p = OptionParser(sort.__doc__) p.add_option("--sizes", default=False, action="store_true", help="Sort by decreasing size [default: %default]") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(p.print_help()) fastafile, = args sortedfastafile = fastafile.rsplit(".", 1)[0] + ".sorted.fasta" f = Fasta(fastafile, index=False) fw = must_open(sortedfastafile, "w") if opts.sizes: # Sort by decreasing size sortlist = sorted(f.itersizes(), key=lambda x: (-x[1], x[0])) logging.debug("Sort by size: max: {0}, min: {1}".\ format(sortlist[0], sortlist[-1])) sortlist = [x for x, s in sortlist] else: sortlist = sorted(f.iterkeys()) for key in sortlist: rec = f[key] SeqIO.write([rec], fw, "fasta") logging.debug("Sorted file written to `{0}`.".format(sortedfastafile)) fw.close() return sortedfastafile
[ "def", "sort", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "sort", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--sizes\"", ",", "default", "=", "False", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Sort by decreasing size [...
%prog sort fastafile Sort a list of sequences and output with sorted IDs, etc.
[ "%prog", "sort", "fastafile" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/fasta.py#L1006-L1042
train
200,592
tanghaibao/jcvi
jcvi/formats/fasta.py
print_first_difference
def print_first_difference(arec, brec, ignore_case=False, ignore_N=False, rc=False, report_match=True): """ Returns the first different nucleotide in two sequence comparisons runs both Plus and Minus strand """ plus_match = _print_first_difference(arec, brec, ignore_case=ignore_case, ignore_N=ignore_N, report_match=report_match) if rc and not plus_match: logging.debug("trying reverse complement of %s" % brec.id) brec.seq = brec.seq.reverse_complement() minus_match = _print_first_difference(arec, brec, ignore_case=ignore_case, ignore_N=ignore_N, report_match=report_match) return minus_match else: return plus_match
python
def print_first_difference(arec, brec, ignore_case=False, ignore_N=False, rc=False, report_match=True): """ Returns the first different nucleotide in two sequence comparisons runs both Plus and Minus strand """ plus_match = _print_first_difference(arec, brec, ignore_case=ignore_case, ignore_N=ignore_N, report_match=report_match) if rc and not plus_match: logging.debug("trying reverse complement of %s" % brec.id) brec.seq = brec.seq.reverse_complement() minus_match = _print_first_difference(arec, brec, ignore_case=ignore_case, ignore_N=ignore_N, report_match=report_match) return minus_match else: return plus_match
[ "def", "print_first_difference", "(", "arec", ",", "brec", ",", "ignore_case", "=", "False", ",", "ignore_N", "=", "False", ",", "rc", "=", "False", ",", "report_match", "=", "True", ")", ":", "plus_match", "=", "_print_first_difference", "(", "arec", ",", ...
Returns the first different nucleotide in two sequence comparisons runs both Plus and Minus strand
[ "Returns", "the", "first", "different", "nucleotide", "in", "two", "sequence", "comparisons", "runs", "both", "Plus", "and", "Minus", "strand" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/fasta.py#L1299-L1316
train
200,593
tanghaibao/jcvi
jcvi/formats/fasta.py
_print_first_difference
def _print_first_difference(arec, brec, ignore_case=False, ignore_N=False, report_match=True): """ Returns the first different nucleotide in two sequence comparisons """ aseq, bseq = arec.seq, brec.seq asize, bsize = len(aseq), len(bseq) matched = True for i, (a, b) in enumerate(zip_longest(aseq, bseq)): if ignore_case and None not in (a, b): a, b = a.upper(), b.upper() if ignore_N and ('N' in (a, b) or 'X' in (a, b)): continue if a != b: matched = False break if i + 1 == asize and matched: if report_match: print(green("Two sequences match")) match = True else: print(red("Two sequences do not match")) snippet_size = 20 # show the context of the difference print(red("Sequence start to differ at position %d:" % (i + 1))) begin = max(i - snippet_size, 0) aend = min(i + snippet_size, asize) bend = min(i + snippet_size, bsize) print(red(aseq[begin:i] + "|" + aseq[i:aend])) print(red(bseq[begin:i] + "|" + bseq[i:bend])) match = False return match
python
def _print_first_difference(arec, brec, ignore_case=False, ignore_N=False, report_match=True): """ Returns the first different nucleotide in two sequence comparisons """ aseq, bseq = arec.seq, brec.seq asize, bsize = len(aseq), len(bseq) matched = True for i, (a, b) in enumerate(zip_longest(aseq, bseq)): if ignore_case and None not in (a, b): a, b = a.upper(), b.upper() if ignore_N and ('N' in (a, b) or 'X' in (a, b)): continue if a != b: matched = False break if i + 1 == asize and matched: if report_match: print(green("Two sequences match")) match = True else: print(red("Two sequences do not match")) snippet_size = 20 # show the context of the difference print(red("Sequence start to differ at position %d:" % (i + 1))) begin = max(i - snippet_size, 0) aend = min(i + snippet_size, asize) bend = min(i + snippet_size, bsize) print(red(aseq[begin:i] + "|" + aseq[i:aend])) print(red(bseq[begin:i] + "|" + bseq[i:bend])) match = False return match
[ "def", "_print_first_difference", "(", "arec", ",", "brec", ",", "ignore_case", "=", "False", ",", "ignore_N", "=", "False", ",", "report_match", "=", "True", ")", ":", "aseq", ",", "bseq", "=", "arec", ".", "seq", ",", "brec", ".", "seq", "asize", ","...
Returns the first different nucleotide in two sequence comparisons
[ "Returns", "the", "first", "different", "nucleotide", "in", "two", "sequence", "comparisons" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/fasta.py#L1319-L1358
train
200,594
tanghaibao/jcvi
jcvi/formats/fasta.py
hash_fasta
def hash_fasta(seq, ignore_case=False, ignore_N=False, ignore_stop=False, checksum="MD5"): """ Generates checksum of input sequence element """ if ignore_stop: seq = seq.rstrip("*") if ignore_case: seq = seq.upper() if ignore_N: if not all(c.upper() in 'ATGCN' for c in seq): seq = re.sub('X', '', seq) else: seq = re.sub('N', '', seq) if checksum == "MD5": hashed = md5(seq).hexdigest() elif checksum == "GCG": hashed = seguid(seq) return hashed
python
def hash_fasta(seq, ignore_case=False, ignore_N=False, ignore_stop=False, checksum="MD5"): """ Generates checksum of input sequence element """ if ignore_stop: seq = seq.rstrip("*") if ignore_case: seq = seq.upper() if ignore_N: if not all(c.upper() in 'ATGCN' for c in seq): seq = re.sub('X', '', seq) else: seq = re.sub('N', '', seq) if checksum == "MD5": hashed = md5(seq).hexdigest() elif checksum == "GCG": hashed = seguid(seq) return hashed
[ "def", "hash_fasta", "(", "seq", ",", "ignore_case", "=", "False", ",", "ignore_N", "=", "False", ",", "ignore_stop", "=", "False", ",", "checksum", "=", "\"MD5\"", ")", ":", "if", "ignore_stop", ":", "seq", "=", "seq", ".", "rstrip", "(", "\"*\"", ")"...
Generates checksum of input sequence element
[ "Generates", "checksum", "of", "input", "sequence", "element" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/fasta.py#L1431-L1450
train
200,595
tanghaibao/jcvi
jcvi/formats/fasta.py
get_qual
def get_qual(fastafile, suffix=QUALSUFFIX, check=True): """ Check if current folder contains a qual file associated with the fastafile """ qualfile1 = fastafile.rsplit(".", 1)[0] + suffix qualfile2 = fastafile + suffix if check: if op.exists(qualfile1): logging.debug("qual file `{0}` found".format(qualfile1)) return qualfile1 elif op.exists(qualfile2): logging.debug("qual file `{0}` found".format(qualfile2)) return qualfile2 else: logging.warning("qual file not found") return None return qualfile1
python
def get_qual(fastafile, suffix=QUALSUFFIX, check=True): """ Check if current folder contains a qual file associated with the fastafile """ qualfile1 = fastafile.rsplit(".", 1)[0] + suffix qualfile2 = fastafile + suffix if check: if op.exists(qualfile1): logging.debug("qual file `{0}` found".format(qualfile1)) return qualfile1 elif op.exists(qualfile2): logging.debug("qual file `{0}` found".format(qualfile2)) return qualfile2 else: logging.warning("qual file not found") return None return qualfile1
[ "def", "get_qual", "(", "fastafile", ",", "suffix", "=", "QUALSUFFIX", ",", "check", "=", "True", ")", ":", "qualfile1", "=", "fastafile", ".", "rsplit", "(", "\".\"", ",", "1", ")", "[", "0", "]", "+", "suffix", "qualfile2", "=", "fastafile", "+", "...
Check if current folder contains a qual file associated with the fastafile
[ "Check", "if", "current", "folder", "contains", "a", "qual", "file", "associated", "with", "the", "fastafile" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/fasta.py#L1551-L1569
train
200,596
tanghaibao/jcvi
jcvi/formats/fasta.py
some
def some(args): """ %prog some fastafile listfile outfastafile generate a subset of fastafile, based on a list """ p = OptionParser(some.__doc__) p.add_option("--exclude", default=False, action="store_true", help="Output sequences not in the list file [default: %default]") p.add_option("--uniprot", default=False, action="store_true", help="Header is from uniprot [default: %default]") opts, args = p.parse_args(args) if len(args) != 3: sys.exit(p.print_help()) fastafile, listfile, outfastafile = args outfastahandle = must_open(outfastafile, "w") qualfile = get_qual(fastafile) names = set(x.strip() for x in open(listfile)) if qualfile: outqualfile = outfastafile + ".qual" outqualhandle = open(outqualfile, "w") parser = iter_fasta_qual(fastafile, qualfile) else: parser = SeqIO.parse(fastafile, "fasta") num_records = 0 for rec in parser: name = rec.id if opts.uniprot: name = name.split("|")[-1] if opts.exclude: if name in names: continue else: if name not in names: continue SeqIO.write([rec], outfastahandle, "fasta") if qualfile: SeqIO.write([rec], outqualhandle, "qual") num_records += 1 logging.debug("A total of %d records written to `%s`" % \ (num_records, outfastafile))
python
def some(args): """ %prog some fastafile listfile outfastafile generate a subset of fastafile, based on a list """ p = OptionParser(some.__doc__) p.add_option("--exclude", default=False, action="store_true", help="Output sequences not in the list file [default: %default]") p.add_option("--uniprot", default=False, action="store_true", help="Header is from uniprot [default: %default]") opts, args = p.parse_args(args) if len(args) != 3: sys.exit(p.print_help()) fastafile, listfile, outfastafile = args outfastahandle = must_open(outfastafile, "w") qualfile = get_qual(fastafile) names = set(x.strip() for x in open(listfile)) if qualfile: outqualfile = outfastafile + ".qual" outqualhandle = open(outqualfile, "w") parser = iter_fasta_qual(fastafile, qualfile) else: parser = SeqIO.parse(fastafile, "fasta") num_records = 0 for rec in parser: name = rec.id if opts.uniprot: name = name.split("|")[-1] if opts.exclude: if name in names: continue else: if name not in names: continue SeqIO.write([rec], outfastahandle, "fasta") if qualfile: SeqIO.write([rec], outqualhandle, "qual") num_records += 1 logging.debug("A total of %d records written to `%s`" % \ (num_records, outfastafile))
[ "def", "some", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "some", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--exclude\"", ",", "default", "=", "False", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Output sequences not in...
%prog some fastafile listfile outfastafile generate a subset of fastafile, based on a list
[ "%prog", "some", "fastafile", "listfile", "outfastafile" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/fasta.py#L1572-L1621
train
200,597
tanghaibao/jcvi
jcvi/formats/fasta.py
fastq
def fastq(args): """ %prog fastq fastafile Generate fastqfile by combining fastafile and fastafile.qual. Also check --qv option to use a default qv score. """ from jcvi.formats.fastq import FastqLite p = OptionParser(fastq.__doc__) p.add_option("--qv", type="int", help="Use generic qv value [dafault: %default]") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) fastafile, = args fastqfile = fastafile.rsplit(".", 1)[0] + ".fastq" fastqhandle = open(fastqfile, "w") num_records = 0 if opts.qv is not None: qv = chr(ord('!') + opts.qv) logging.debug("QV char '{0}' ({1})".format(qv, opts.qv)) else: qv = None if qv: f = Fasta(fastafile, lazy=True) for name, rec in f.iteritems_ordered(): r = FastqLite("@" + name, str(rec.seq).upper(), qv * len(rec.seq)) print(r, file=fastqhandle) num_records += 1 else: qualfile = get_qual(fastafile) for rec in iter_fasta_qual(fastafile, qualfile): SeqIO.write([rec], fastqhandle, "fastq") num_records += 1 fastqhandle.close() logging.debug("A total of %d records written to `%s`" % \ (num_records, fastqfile))
python
def fastq(args): """ %prog fastq fastafile Generate fastqfile by combining fastafile and fastafile.qual. Also check --qv option to use a default qv score. """ from jcvi.formats.fastq import FastqLite p = OptionParser(fastq.__doc__) p.add_option("--qv", type="int", help="Use generic qv value [dafault: %default]") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) fastafile, = args fastqfile = fastafile.rsplit(".", 1)[0] + ".fastq" fastqhandle = open(fastqfile, "w") num_records = 0 if opts.qv is not None: qv = chr(ord('!') + opts.qv) logging.debug("QV char '{0}' ({1})".format(qv, opts.qv)) else: qv = None if qv: f = Fasta(fastafile, lazy=True) for name, rec in f.iteritems_ordered(): r = FastqLite("@" + name, str(rec.seq).upper(), qv * len(rec.seq)) print(r, file=fastqhandle) num_records += 1 else: qualfile = get_qual(fastafile) for rec in iter_fasta_qual(fastafile, qualfile): SeqIO.write([rec], fastqhandle, "fastq") num_records += 1 fastqhandle.close() logging.debug("A total of %d records written to `%s`" % \ (num_records, fastqfile))
[ "def", "fastq", "(", "args", ")", ":", "from", "jcvi", ".", "formats", ".", "fastq", "import", "FastqLite", "p", "=", "OptionParser", "(", "fastq", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--qv\"", ",", "type", "=", "\"int\"", ",", "help", ...
%prog fastq fastafile Generate fastqfile by combining fastafile and fastafile.qual. Also check --qv option to use a default qv score.
[ "%prog", "fastq", "fastafile" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/fasta.py#L1624-L1668
train
200,598
tanghaibao/jcvi
jcvi/formats/fasta.py
pair
def pair(args): """ %prog pair fastafile Generate .pairs.fasta and .fragments.fasta by matching records into the pairs and the rest go to fragments. """ p = OptionParser(pair.__doc__) p.set_sep(sep=None, help="Separator in name to reduce to clone id" +\ "e.g. GFNQ33242/1 use /, BOT01-2453H.b1 use .") p.add_option("-m", dest="matepairs", default=False, action="store_true", help="generate .matepairs file [often used for Celera Assembler]") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(p.print_help()) fastafile, = args qualfile = get_qual(fastafile) prefix = fastafile.rsplit(".", 1)[0] pairsfile = prefix + ".pairs.fasta" fragsfile = prefix + ".frags.fasta" pairsfw = open(pairsfile, "w") fragsfw = open(fragsfile, "w") #TODO: need a class to handle coupled fasta and qual iterating and indexing if opts.matepairs: matepairsfile = prefix + ".matepairs" matepairsfw = open(matepairsfile, "w") if qualfile: pairsqualfile = pairsfile + ".qual" pairsqualhandle = open(pairsqualfile, "w") fragsqualfile = fragsfile + ".qual" fragsqualhandle = open(fragsqualfile, "w") f = Fasta(fastafile) if qualfile: q = SeqIO.index(qualfile, "qual") all_keys = list(f.keys()) all_keys.sort() sep = opts.sep if sep: key_fun = lambda x: x.split(sep, 1)[0] else: key_fun = lambda x: x[:-1] for key, variants in groupby(all_keys, key=key_fun): variants = list(variants) paired = (len(variants) == 2) if paired and opts.matepairs: print("\t".join(("%s/1" % key, "%s/2" % key)), file=matepairsfw) fw = pairsfw if paired else fragsfw if qualfile: qualfw = pairsqualhandle if paired else fragsqualhandle for i, var in enumerate(variants): rec = f[var] if qualfile: recqual = q[var] newid = "%s/%d" % (key, i + 1) rec.id = newid rec.description = "" SeqIO.write([rec], fw, "fasta") if qualfile: recqual.id = newid recqual.description = "" SeqIO.write([recqual], qualfw, "qual") logging.debug("sequences written to `%s` and `%s`" % \ (pairsfile, fragsfile)) if opts.matepairs: logging.debug("mates written to `%s`" % matepairsfile)
python
def pair(args): """ %prog pair fastafile Generate .pairs.fasta and .fragments.fasta by matching records into the pairs and the rest go to fragments. """ p = OptionParser(pair.__doc__) p.set_sep(sep=None, help="Separator in name to reduce to clone id" +\ "e.g. GFNQ33242/1 use /, BOT01-2453H.b1 use .") p.add_option("-m", dest="matepairs", default=False, action="store_true", help="generate .matepairs file [often used for Celera Assembler]") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(p.print_help()) fastafile, = args qualfile = get_qual(fastafile) prefix = fastafile.rsplit(".", 1)[0] pairsfile = prefix + ".pairs.fasta" fragsfile = prefix + ".frags.fasta" pairsfw = open(pairsfile, "w") fragsfw = open(fragsfile, "w") #TODO: need a class to handle coupled fasta and qual iterating and indexing if opts.matepairs: matepairsfile = prefix + ".matepairs" matepairsfw = open(matepairsfile, "w") if qualfile: pairsqualfile = pairsfile + ".qual" pairsqualhandle = open(pairsqualfile, "w") fragsqualfile = fragsfile + ".qual" fragsqualhandle = open(fragsqualfile, "w") f = Fasta(fastafile) if qualfile: q = SeqIO.index(qualfile, "qual") all_keys = list(f.keys()) all_keys.sort() sep = opts.sep if sep: key_fun = lambda x: x.split(sep, 1)[0] else: key_fun = lambda x: x[:-1] for key, variants in groupby(all_keys, key=key_fun): variants = list(variants) paired = (len(variants) == 2) if paired and opts.matepairs: print("\t".join(("%s/1" % key, "%s/2" % key)), file=matepairsfw) fw = pairsfw if paired else fragsfw if qualfile: qualfw = pairsqualhandle if paired else fragsqualhandle for i, var in enumerate(variants): rec = f[var] if qualfile: recqual = q[var] newid = "%s/%d" % (key, i + 1) rec.id = newid rec.description = "" SeqIO.write([rec], fw, "fasta") if qualfile: recqual.id = newid recqual.description = "" SeqIO.write([recqual], qualfw, "qual") logging.debug("sequences written to `%s` and `%s`" % \ (pairsfile, fragsfile)) if opts.matepairs: logging.debug("mates written to `%s`" % matepairsfile)
[ "def", "pair", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "pair", ".", "__doc__", ")", "p", ".", "set_sep", "(", "sep", "=", "None", ",", "help", "=", "\"Separator in name to reduce to clone id\"", "+", "\"e.g. GFNQ33242/1 use /, BOT01-2453H.b1 use .\""...
%prog pair fastafile Generate .pairs.fasta and .fragments.fasta by matching records into the pairs and the rest go to fragments.
[ "%prog", "pair", "fastafile" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/fasta.py#L1671-L1749
train
200,599