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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
bcbio/bcbio-nextgen | bcbio/bam/coverage.py | plot_multiple_regions_coverage | def plot_multiple_regions_coverage(samples, out_file, data, region_bed=None, stem_bed=None):
"""
given a list of bcbio samples and a bed file or BedTool of regions,
makes a plot of the coverage in the regions for the set of samples
if given a bed file or BedTool of locations in stem_bed with a label,
plots lollipops at those locations
"""
mpl.use('Agg', force=True)
PAD = 100
if file_exists(out_file):
return out_file
in_bams = [dd.get_align_bam(x) for x in samples]
samplenames = [dd.get_sample_name(x) for x in samples]
if isinstance(region_bed, six.string_types):
region_bed = pybedtools.BedTool(region_bed)
if isinstance(stem_bed, six.string_types):
stem_bed = pybedtools.BedTool(stem_bed)
if stem_bed is not None: # tabix indexed bedtools eval to false
stem_bed = stem_bed.tabix()
plt.clf()
plt.cla()
with file_transaction(out_file) as tx_out_file:
with backend_pdf.PdfPages(tx_out_file) as pdf_out:
sns.despine()
for line in region_bed:
for chrom, start, end in _split_regions(line.chrom, max(line.start - PAD, 0),
line.end + PAD):
df = _combine_regional_coverage(in_bams, samplenames, chrom,
start, end, os.path.dirname(tx_out_file), data)
plot = sns.tsplot(df, time="position", unit="chrom",
value="coverage", condition="sample")
if stem_bed is not None: # tabix indexed bedtools eval to false
interval = pybedtools.Interval(chrom, start, end)
_add_stems_to_plot(interval, stem_bed, samples, plot)
plt.title("{chrom}:{start}-{end}".format(**locals()))
pdf_out.savefig(plot.get_figure())
plt.close()
return out_file | python | def plot_multiple_regions_coverage(samples, out_file, data, region_bed=None, stem_bed=None):
"""
given a list of bcbio samples and a bed file or BedTool of regions,
makes a plot of the coverage in the regions for the set of samples
if given a bed file or BedTool of locations in stem_bed with a label,
plots lollipops at those locations
"""
mpl.use('Agg', force=True)
PAD = 100
if file_exists(out_file):
return out_file
in_bams = [dd.get_align_bam(x) for x in samples]
samplenames = [dd.get_sample_name(x) for x in samples]
if isinstance(region_bed, six.string_types):
region_bed = pybedtools.BedTool(region_bed)
if isinstance(stem_bed, six.string_types):
stem_bed = pybedtools.BedTool(stem_bed)
if stem_bed is not None: # tabix indexed bedtools eval to false
stem_bed = stem_bed.tabix()
plt.clf()
plt.cla()
with file_transaction(out_file) as tx_out_file:
with backend_pdf.PdfPages(tx_out_file) as pdf_out:
sns.despine()
for line in region_bed:
for chrom, start, end in _split_regions(line.chrom, max(line.start - PAD, 0),
line.end + PAD):
df = _combine_regional_coverage(in_bams, samplenames, chrom,
start, end, os.path.dirname(tx_out_file), data)
plot = sns.tsplot(df, time="position", unit="chrom",
value="coverage", condition="sample")
if stem_bed is not None: # tabix indexed bedtools eval to false
interval = pybedtools.Interval(chrom, start, end)
_add_stems_to_plot(interval, stem_bed, samples, plot)
plt.title("{chrom}:{start}-{end}".format(**locals()))
pdf_out.savefig(plot.get_figure())
plt.close()
return out_file | [
"def",
"plot_multiple_regions_coverage",
"(",
"samples",
",",
"out_file",
",",
"data",
",",
"region_bed",
"=",
"None",
",",
"stem_bed",
"=",
"None",
")",
":",
"mpl",
".",
"use",
"(",
"'Agg'",
",",
"force",
"=",
"True",
")",
"PAD",
"=",
"100",
"if",
"fi... | given a list of bcbio samples and a bed file or BedTool of regions,
makes a plot of the coverage in the regions for the set of samples
if given a bed file or BedTool of locations in stem_bed with a label,
plots lollipops at those locations | [
"given",
"a",
"list",
"of",
"bcbio",
"samples",
"and",
"a",
"bed",
"file",
"or",
"BedTool",
"of",
"regions",
"makes",
"a",
"plot",
"of",
"the",
"coverage",
"in",
"the",
"regions",
"for",
"the",
"set",
"of",
"samples"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/coverage.py#L110-L148 | train | 218,900 |
bcbio/bcbio-nextgen | bcbio/variation/mutect.py | _config_params | def _config_params(base_config, assoc_files, region, out_file, items):
"""Add parameters based on configuration variables, associated files and genomic regions.
"""
params = []
dbsnp = assoc_files.get("dbsnp")
if dbsnp:
params += ["--dbsnp", dbsnp]
cosmic = assoc_files.get("cosmic")
if cosmic:
params += ["--cosmic", cosmic]
variant_regions = bedutils.population_variant_regions(items)
region = subset_variant_regions(variant_regions, region, out_file, items)
if region:
params += ["-L", bamprep.region_to_gatk(region), "--interval_set_rule",
"INTERSECTION"]
# set low frequency calling parameter if adjusted
# to set other MuTect parameters on contamination, pass options to resources for mutect
# --fraction_contamination --minimum_normal_allele_fraction
min_af = tz.get_in(["algorithm", "min_allele_fraction"], base_config)
if min_af:
params += ["--minimum_mutation_cell_fraction", "%.2f" % (min_af / 100.0)]
resources = config_utils.get_resources("mutect", base_config)
if resources.get("options") is not None:
params += [str(x) for x in resources.get("options", [])]
# Output quality scores
if "--enable_qscore_output" not in params:
params.append("--enable_qscore_output")
# drf not currently supported in MuTect to turn off duplicateread filter
# params += gatk.standard_cl_params(items)
return params | python | def _config_params(base_config, assoc_files, region, out_file, items):
"""Add parameters based on configuration variables, associated files and genomic regions.
"""
params = []
dbsnp = assoc_files.get("dbsnp")
if dbsnp:
params += ["--dbsnp", dbsnp]
cosmic = assoc_files.get("cosmic")
if cosmic:
params += ["--cosmic", cosmic]
variant_regions = bedutils.population_variant_regions(items)
region = subset_variant_regions(variant_regions, region, out_file, items)
if region:
params += ["-L", bamprep.region_to_gatk(region), "--interval_set_rule",
"INTERSECTION"]
# set low frequency calling parameter if adjusted
# to set other MuTect parameters on contamination, pass options to resources for mutect
# --fraction_contamination --minimum_normal_allele_fraction
min_af = tz.get_in(["algorithm", "min_allele_fraction"], base_config)
if min_af:
params += ["--minimum_mutation_cell_fraction", "%.2f" % (min_af / 100.0)]
resources = config_utils.get_resources("mutect", base_config)
if resources.get("options") is not None:
params += [str(x) for x in resources.get("options", [])]
# Output quality scores
if "--enable_qscore_output" not in params:
params.append("--enable_qscore_output")
# drf not currently supported in MuTect to turn off duplicateread filter
# params += gatk.standard_cl_params(items)
return params | [
"def",
"_config_params",
"(",
"base_config",
",",
"assoc_files",
",",
"region",
",",
"out_file",
",",
"items",
")",
":",
"params",
"=",
"[",
"]",
"dbsnp",
"=",
"assoc_files",
".",
"get",
"(",
"\"dbsnp\"",
")",
"if",
"dbsnp",
":",
"params",
"+=",
"[",
"... | Add parameters based on configuration variables, associated files and genomic regions. | [
"Add",
"parameters",
"based",
"on",
"configuration",
"variables",
"associated",
"files",
"and",
"genomic",
"regions",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/mutect.py#L46-L75 | train | 218,901 |
bcbio/bcbio-nextgen | bcbio/variation/mutect.py | _mutect_call_prep | def _mutect_call_prep(align_bams, items, ref_file, assoc_files,
region=None, out_file=None):
"""Preparation work for MuTect.
"""
base_config = items[0]["config"]
broad_runner = broad.runner_from_path("picard", base_config)
broad_runner.run_fn("picard_index_ref", ref_file)
broad_runner = broad.runner_from_config(base_config, "mutect")
_check_mutect_version(broad_runner)
for x in align_bams:
bam.index(x, base_config)
paired = vcfutils.get_paired_bams(align_bams, items)
if not paired:
raise ValueError("Specified MuTect calling but 'tumor' phenotype not present in batch\n"
"https://bcbio-nextgen.readthedocs.org/en/latest/contents/"
"pipelines.html#cancer-variant-calling\n"
"for samples: %s" % ", " .join([dd.get_sample_name(x) for x in items]))
params = ["-R", ref_file, "-T", "MuTect", "-U", "ALLOW_N_CIGAR_READS"]
params += ["--read_filter", "NotPrimaryAlignment"]
params += ["-I:tumor", paired.tumor_bam]
params += ["--tumor_sample_name", paired.tumor_name]
if paired.normal_bam is not None:
params += ["-I:normal", paired.normal_bam]
params += ["--normal_sample_name", paired.normal_name]
if paired.normal_panel is not None:
params += ["--normal_panel", paired.normal_panel]
params += _config_params(base_config, assoc_files, region, out_file, items)
return broad_runner, params | python | def _mutect_call_prep(align_bams, items, ref_file, assoc_files,
region=None, out_file=None):
"""Preparation work for MuTect.
"""
base_config = items[0]["config"]
broad_runner = broad.runner_from_path("picard", base_config)
broad_runner.run_fn("picard_index_ref", ref_file)
broad_runner = broad.runner_from_config(base_config, "mutect")
_check_mutect_version(broad_runner)
for x in align_bams:
bam.index(x, base_config)
paired = vcfutils.get_paired_bams(align_bams, items)
if not paired:
raise ValueError("Specified MuTect calling but 'tumor' phenotype not present in batch\n"
"https://bcbio-nextgen.readthedocs.org/en/latest/contents/"
"pipelines.html#cancer-variant-calling\n"
"for samples: %s" % ", " .join([dd.get_sample_name(x) for x in items]))
params = ["-R", ref_file, "-T", "MuTect", "-U", "ALLOW_N_CIGAR_READS"]
params += ["--read_filter", "NotPrimaryAlignment"]
params += ["-I:tumor", paired.tumor_bam]
params += ["--tumor_sample_name", paired.tumor_name]
if paired.normal_bam is not None:
params += ["-I:normal", paired.normal_bam]
params += ["--normal_sample_name", paired.normal_name]
if paired.normal_panel is not None:
params += ["--normal_panel", paired.normal_panel]
params += _config_params(base_config, assoc_files, region, out_file, items)
return broad_runner, params | [
"def",
"_mutect_call_prep",
"(",
"align_bams",
",",
"items",
",",
"ref_file",
",",
"assoc_files",
",",
"region",
"=",
"None",
",",
"out_file",
"=",
"None",
")",
":",
"base_config",
"=",
"items",
"[",
"0",
"]",
"[",
"\"config\"",
"]",
"broad_runner",
"=",
... | Preparation work for MuTect. | [
"Preparation",
"work",
"for",
"MuTect",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/mutect.py#L77-L106 | train | 218,902 |
bcbio/bcbio-nextgen | bcbio/variation/mutect.py | _SID_call_prep | def _SID_call_prep(align_bams, items, ref_file, assoc_files, region=None, out_file=None):
"""Preparation work for SomaticIndelDetector.
"""
base_config = items[0]["config"]
for x in align_bams:
bam.index(x, base_config)
params = ["-R", ref_file, "-T", "SomaticIndelDetector", "-U", "ALLOW_N_CIGAR_READS"]
# Limit per base read start count to between 200-10000, i.e. from any base
# can no more 10000 new reads begin.
# Further, limit maxNumberOfReads accordingly, otherwise SID discards
# windows for high coverage panels.
paired = vcfutils.get_paired_bams(align_bams, items)
params += ["--read_filter", "NotPrimaryAlignment"]
params += ["-I:tumor", paired.tumor_bam]
min_af = float(get_in(paired.tumor_config, ("algorithm", "min_allele_fraction"), 10)) / 100.0
if paired.normal_bam is not None:
params += ["-I:normal", paired.normal_bam]
# notice there must be at least 4 reads of coverage in normal
params += ["--filter_expressions", "T_COV<6||N_COV<4||T_INDEL_F<%s||T_INDEL_CF<0.7" % min_af]
else:
params += ["--unpaired"]
params += ["--filter_expressions", "COV<6||INDEL_F<%s||INDEL_CF<0.7" % min_af]
if region:
params += ["-L", bamprep.region_to_gatk(region), "--interval_set_rule",
"INTERSECTION"]
return params | python | def _SID_call_prep(align_bams, items, ref_file, assoc_files, region=None, out_file=None):
"""Preparation work for SomaticIndelDetector.
"""
base_config = items[0]["config"]
for x in align_bams:
bam.index(x, base_config)
params = ["-R", ref_file, "-T", "SomaticIndelDetector", "-U", "ALLOW_N_CIGAR_READS"]
# Limit per base read start count to between 200-10000, i.e. from any base
# can no more 10000 new reads begin.
# Further, limit maxNumberOfReads accordingly, otherwise SID discards
# windows for high coverage panels.
paired = vcfutils.get_paired_bams(align_bams, items)
params += ["--read_filter", "NotPrimaryAlignment"]
params += ["-I:tumor", paired.tumor_bam]
min_af = float(get_in(paired.tumor_config, ("algorithm", "min_allele_fraction"), 10)) / 100.0
if paired.normal_bam is not None:
params += ["-I:normal", paired.normal_bam]
# notice there must be at least 4 reads of coverage in normal
params += ["--filter_expressions", "T_COV<6||N_COV<4||T_INDEL_F<%s||T_INDEL_CF<0.7" % min_af]
else:
params += ["--unpaired"]
params += ["--filter_expressions", "COV<6||INDEL_F<%s||INDEL_CF<0.7" % min_af]
if region:
params += ["-L", bamprep.region_to_gatk(region), "--interval_set_rule",
"INTERSECTION"]
return params | [
"def",
"_SID_call_prep",
"(",
"align_bams",
",",
"items",
",",
"ref_file",
",",
"assoc_files",
",",
"region",
"=",
"None",
",",
"out_file",
"=",
"None",
")",
":",
"base_config",
"=",
"items",
"[",
"0",
"]",
"[",
"\"config\"",
"]",
"for",
"x",
"in",
"al... | Preparation work for SomaticIndelDetector. | [
"Preparation",
"work",
"for",
"SomaticIndelDetector",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/mutect.py#L191-L217 | train | 218,903 |
bcbio/bcbio-nextgen | bcbio/variation/mutect.py | _fix_mutect_output | def _fix_mutect_output(orig_file, config, out_file, is_paired):
"""Adjust MuTect output to match other callers.
- Rename allelic fraction field in mutect output from FA to FREQ to standarize with other tools
- Remove extra 'none' samples introduced when calling tumor-only samples
"""
out_file_noc = out_file.replace(".vcf.gz", ".vcf")
none_index = -1
with file_transaction(config, out_file_noc) as tx_out_file:
with open_gzipsafe(orig_file) as in_handle:
with open(tx_out_file, 'w') as out_handle:
for line in in_handle:
if not is_paired and line.startswith("#CHROM"):
parts = line.rstrip().split("\t")
none_index = parts.index("none")
del parts[none_index]
line = "\t".join(parts) + "\n"
elif line.startswith("##FORMAT=<ID=FA"):
line = line.replace("=FA", "=FREQ")
elif not line.startswith("#"):
if none_index > 0:
parts = line.rstrip().split("\t")
del parts[none_index]
line = "\t".join(parts) + "\n"
line = line.replace("FA", "FREQ")
out_handle.write(line)
return bgzip_and_index(out_file_noc, config) | python | def _fix_mutect_output(orig_file, config, out_file, is_paired):
"""Adjust MuTect output to match other callers.
- Rename allelic fraction field in mutect output from FA to FREQ to standarize with other tools
- Remove extra 'none' samples introduced when calling tumor-only samples
"""
out_file_noc = out_file.replace(".vcf.gz", ".vcf")
none_index = -1
with file_transaction(config, out_file_noc) as tx_out_file:
with open_gzipsafe(orig_file) as in_handle:
with open(tx_out_file, 'w') as out_handle:
for line in in_handle:
if not is_paired and line.startswith("#CHROM"):
parts = line.rstrip().split("\t")
none_index = parts.index("none")
del parts[none_index]
line = "\t".join(parts) + "\n"
elif line.startswith("##FORMAT=<ID=FA"):
line = line.replace("=FA", "=FREQ")
elif not line.startswith("#"):
if none_index > 0:
parts = line.rstrip().split("\t")
del parts[none_index]
line = "\t".join(parts) + "\n"
line = line.replace("FA", "FREQ")
out_handle.write(line)
return bgzip_and_index(out_file_noc, config) | [
"def",
"_fix_mutect_output",
"(",
"orig_file",
",",
"config",
",",
"out_file",
",",
"is_paired",
")",
":",
"out_file_noc",
"=",
"out_file",
".",
"replace",
"(",
"\".vcf.gz\"",
",",
"\".vcf\"",
")",
"none_index",
"=",
"-",
"1",
"with",
"file_transaction",
"(",
... | Adjust MuTect output to match other callers.
- Rename allelic fraction field in mutect output from FA to FREQ to standarize with other tools
- Remove extra 'none' samples introduced when calling tumor-only samples | [
"Adjust",
"MuTect",
"output",
"to",
"match",
"other",
"callers",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/mutect.py#L219-L245 | train | 218,904 |
bcbio/bcbio-nextgen | bcbio/variation/population.py | prep_gemini_db | def prep_gemini_db(fnames, call_info, samples, extras):
"""Prepare a gemini database from VCF inputs prepared with snpEff.
"""
data = samples[0]
name, caller, is_batch = call_info
build_type = _get_build_type(fnames, samples, caller)
out_dir = utils.safe_makedir(os.path.join(data["dirs"]["work"], "gemini"))
gemini_vcf = get_multisample_vcf(fnames, name, caller, data)
# If we're building a gemini database, normalize the inputs
if build_type:
passonly = all("gemini_allvariants" not in dd.get_tools_on(d) for d in samples)
gemini_vcf = normalize.normalize(gemini_vcf, data, passonly=passonly)
decomposed = True
else:
decomposed = False
ann_vcf = run_vcfanno(gemini_vcf, data, decomposed)
gemini_db = os.path.join(out_dir, "%s-%s.db" % (name, caller))
if ann_vcf and build_type and not utils.file_exists(gemini_db):
ped_file = create_ped_file(samples + extras, gemini_vcf)
# Original approach for hg19/GRCh37
if vcfanno.is_human(data, builds=["37"]) and "gemini_orig" in build_type:
gemini_db = create_gemini_db_orig(gemini_vcf, data, gemini_db, ped_file)
else:
gemini_db = create_gemini_db(ann_vcf, data, gemini_db, ped_file)
# only pass along gemini_vcf_downstream if uniquely created here
if os.path.islink(gemini_vcf):
gemini_vcf = None
return [[(name, caller), {"db": gemini_db if utils.file_exists(gemini_db) else None,
"vcf": ann_vcf or gemini_vcf,
"decomposed": decomposed}]] | python | def prep_gemini_db(fnames, call_info, samples, extras):
"""Prepare a gemini database from VCF inputs prepared with snpEff.
"""
data = samples[0]
name, caller, is_batch = call_info
build_type = _get_build_type(fnames, samples, caller)
out_dir = utils.safe_makedir(os.path.join(data["dirs"]["work"], "gemini"))
gemini_vcf = get_multisample_vcf(fnames, name, caller, data)
# If we're building a gemini database, normalize the inputs
if build_type:
passonly = all("gemini_allvariants" not in dd.get_tools_on(d) for d in samples)
gemini_vcf = normalize.normalize(gemini_vcf, data, passonly=passonly)
decomposed = True
else:
decomposed = False
ann_vcf = run_vcfanno(gemini_vcf, data, decomposed)
gemini_db = os.path.join(out_dir, "%s-%s.db" % (name, caller))
if ann_vcf and build_type and not utils.file_exists(gemini_db):
ped_file = create_ped_file(samples + extras, gemini_vcf)
# Original approach for hg19/GRCh37
if vcfanno.is_human(data, builds=["37"]) and "gemini_orig" in build_type:
gemini_db = create_gemini_db_orig(gemini_vcf, data, gemini_db, ped_file)
else:
gemini_db = create_gemini_db(ann_vcf, data, gemini_db, ped_file)
# only pass along gemini_vcf_downstream if uniquely created here
if os.path.islink(gemini_vcf):
gemini_vcf = None
return [[(name, caller), {"db": gemini_db if utils.file_exists(gemini_db) else None,
"vcf": ann_vcf or gemini_vcf,
"decomposed": decomposed}]] | [
"def",
"prep_gemini_db",
"(",
"fnames",
",",
"call_info",
",",
"samples",
",",
"extras",
")",
":",
"data",
"=",
"samples",
"[",
"0",
"]",
"name",
",",
"caller",
",",
"is_batch",
"=",
"call_info",
"build_type",
"=",
"_get_build_type",
"(",
"fnames",
",",
... | Prepare a gemini database from VCF inputs prepared with snpEff. | [
"Prepare",
"a",
"gemini",
"database",
"from",
"VCF",
"inputs",
"prepared",
"with",
"snpEff",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/population.py#L25-L54 | train | 218,905 |
bcbio/bcbio-nextgen | bcbio/variation/population.py | _back_compatible_gemini | def _back_compatible_gemini(conf_files, data):
"""Provide old install directory for configuration with GEMINI supplied tidy VCFs.
Handles new style (bcbio installed) and old style (GEMINI installed)
configuration and data locations.
"""
if vcfanno.is_human(data, builds=["37"]):
for f in conf_files:
if f and os.path.basename(f) == "gemini.conf" and os.path.exists(f):
with open(f) as in_handle:
for line in in_handle:
if line.startswith("file"):
fname = line.strip().split("=")[-1].replace('"', '').strip()
if fname.find(".tidy.") > 0:
return install.get_gemini_dir(data)
return None | python | def _back_compatible_gemini(conf_files, data):
"""Provide old install directory for configuration with GEMINI supplied tidy VCFs.
Handles new style (bcbio installed) and old style (GEMINI installed)
configuration and data locations.
"""
if vcfanno.is_human(data, builds=["37"]):
for f in conf_files:
if f and os.path.basename(f) == "gemini.conf" and os.path.exists(f):
with open(f) as in_handle:
for line in in_handle:
if line.startswith("file"):
fname = line.strip().split("=")[-1].replace('"', '').strip()
if fname.find(".tidy.") > 0:
return install.get_gemini_dir(data)
return None | [
"def",
"_back_compatible_gemini",
"(",
"conf_files",
",",
"data",
")",
":",
"if",
"vcfanno",
".",
"is_human",
"(",
"data",
",",
"builds",
"=",
"[",
"\"37\"",
"]",
")",
":",
"for",
"f",
"in",
"conf_files",
":",
"if",
"f",
"and",
"os",
".",
"path",
"."... | Provide old install directory for configuration with GEMINI supplied tidy VCFs.
Handles new style (bcbio installed) and old style (GEMINI installed)
configuration and data locations. | [
"Provide",
"old",
"install",
"directory",
"for",
"configuration",
"with",
"GEMINI",
"supplied",
"tidy",
"VCFs",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/population.py#L56-L71 | train | 218,906 |
bcbio/bcbio-nextgen | bcbio/variation/population.py | run_vcfanno | def run_vcfanno(vcf_file, data, decomposed=False):
"""Run vcfanno, providing annotations from external databases if needed.
Puts together lua and conf files from multiple inputs by file names.
"""
conf_files = dd.get_vcfanno(data)
if conf_files:
with_basepaths = collections.defaultdict(list)
gemini_basepath = _back_compatible_gemini(conf_files, data)
for f in conf_files:
name = os.path.splitext(os.path.basename(f))[0]
if f.endswith(".lua"):
conf_file = None
lua_file = f
else:
conf_file = f
lua_file = "%s.lua" % utils.splitext_plus(conf_file)[0]
if lua_file and not os.path.exists(lua_file):
lua_file = None
data_basepath = gemini_basepath if name == "gemini" else None
if conf_file and os.path.exists(conf_file):
with_basepaths[(data_basepath, name)].append(conf_file)
if lua_file and os.path.exists(lua_file):
with_basepaths[(data_basepath, name)].append(lua_file)
conf_files = with_basepaths.items()
out_file = None
if conf_files:
VcfannoIn = collections.namedtuple("VcfannoIn", ["conf", "lua"])
bp_files = collections.defaultdict(list)
for (data_basepath, name), anno_files in conf_files:
anno_files = list(set(anno_files))
if len(anno_files) == 1:
cur = VcfannoIn(anno_files[0], None)
elif len(anno_files) == 2:
lua_files = [x for x in anno_files if x.endswith(".lua")]
assert len(lua_files) == 1, anno_files
lua_file = lua_files[0]
anno_files.remove(lua_file)
cur = VcfannoIn(anno_files[0], lua_file)
else:
raise ValueError("Unexpected annotation group %s" % anno_files)
bp_files[data_basepath].append(cur)
for data_basepath, anno_files in bp_files.items():
ann_file = vcfanno.run(vcf_file, [x.conf for x in anno_files],
[x.lua for x in anno_files], data,
basepath=data_basepath,
decomposed=decomposed)
if ann_file:
out_file = ann_file
vcf_file = ann_file
return out_file | python | def run_vcfanno(vcf_file, data, decomposed=False):
"""Run vcfanno, providing annotations from external databases if needed.
Puts together lua and conf files from multiple inputs by file names.
"""
conf_files = dd.get_vcfanno(data)
if conf_files:
with_basepaths = collections.defaultdict(list)
gemini_basepath = _back_compatible_gemini(conf_files, data)
for f in conf_files:
name = os.path.splitext(os.path.basename(f))[0]
if f.endswith(".lua"):
conf_file = None
lua_file = f
else:
conf_file = f
lua_file = "%s.lua" % utils.splitext_plus(conf_file)[0]
if lua_file and not os.path.exists(lua_file):
lua_file = None
data_basepath = gemini_basepath if name == "gemini" else None
if conf_file and os.path.exists(conf_file):
with_basepaths[(data_basepath, name)].append(conf_file)
if lua_file and os.path.exists(lua_file):
with_basepaths[(data_basepath, name)].append(lua_file)
conf_files = with_basepaths.items()
out_file = None
if conf_files:
VcfannoIn = collections.namedtuple("VcfannoIn", ["conf", "lua"])
bp_files = collections.defaultdict(list)
for (data_basepath, name), anno_files in conf_files:
anno_files = list(set(anno_files))
if len(anno_files) == 1:
cur = VcfannoIn(anno_files[0], None)
elif len(anno_files) == 2:
lua_files = [x for x in anno_files if x.endswith(".lua")]
assert len(lua_files) == 1, anno_files
lua_file = lua_files[0]
anno_files.remove(lua_file)
cur = VcfannoIn(anno_files[0], lua_file)
else:
raise ValueError("Unexpected annotation group %s" % anno_files)
bp_files[data_basepath].append(cur)
for data_basepath, anno_files in bp_files.items():
ann_file = vcfanno.run(vcf_file, [x.conf for x in anno_files],
[x.lua for x in anno_files], data,
basepath=data_basepath,
decomposed=decomposed)
if ann_file:
out_file = ann_file
vcf_file = ann_file
return out_file | [
"def",
"run_vcfanno",
"(",
"vcf_file",
",",
"data",
",",
"decomposed",
"=",
"False",
")",
":",
"conf_files",
"=",
"dd",
".",
"get_vcfanno",
"(",
"data",
")",
"if",
"conf_files",
":",
"with_basepaths",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")... | Run vcfanno, providing annotations from external databases if needed.
Puts together lua and conf files from multiple inputs by file names. | [
"Run",
"vcfanno",
"providing",
"annotations",
"from",
"external",
"databases",
"if",
"needed",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/population.py#L73-L123 | train | 218,907 |
bcbio/bcbio-nextgen | bcbio/variation/population.py | get_ped_info | def get_ped_info(data, samples):
"""Retrieve all PED info from metadata
"""
family_id = tz.get_in(["metadata", "family_id"], data, None)
if not family_id:
family_id = _find_shared_batch(samples)
return {
"gender": {"male": 1, "female": 2, "unknown": 0}.get(get_gender(data)),
"individual_id": dd.get_sample_name(data),
"family_id": family_id,
"maternal_id": tz.get_in(["metadata", "maternal_id"], data, -9),
"paternal_id": tz.get_in(["metadata", "paternal_id"], data, -9),
"affected": get_affected_status(data),
"ethnicity": tz.get_in(["metadata", "ethnicity"], data, -9)
} | python | def get_ped_info(data, samples):
"""Retrieve all PED info from metadata
"""
family_id = tz.get_in(["metadata", "family_id"], data, None)
if not family_id:
family_id = _find_shared_batch(samples)
return {
"gender": {"male": 1, "female": 2, "unknown": 0}.get(get_gender(data)),
"individual_id": dd.get_sample_name(data),
"family_id": family_id,
"maternal_id": tz.get_in(["metadata", "maternal_id"], data, -9),
"paternal_id": tz.get_in(["metadata", "paternal_id"], data, -9),
"affected": get_affected_status(data),
"ethnicity": tz.get_in(["metadata", "ethnicity"], data, -9)
} | [
"def",
"get_ped_info",
"(",
"data",
",",
"samples",
")",
":",
"family_id",
"=",
"tz",
".",
"get_in",
"(",
"[",
"\"metadata\"",
",",
"\"family_id\"",
"]",
",",
"data",
",",
"None",
")",
"if",
"not",
"family_id",
":",
"family_id",
"=",
"_find_shared_batch",
... | Retrieve all PED info from metadata | [
"Retrieve",
"all",
"PED",
"info",
"from",
"metadata"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/population.py#L224-L238 | train | 218,908 |
bcbio/bcbio-nextgen | bcbio/variation/population.py | create_ped_file | def create_ped_file(samples, base_vcf, out_dir=None):
"""Create a GEMINI-compatible PED file, including gender, family and phenotype information.
Checks for a specified `ped` file in metadata, and will use sample information from this file
before reconstituting from metadata information.
"""
out_file = "%s.ped" % utils.splitext_plus(base_vcf)[0]
if out_dir:
out_file = os.path.join(out_dir, os.path.basename(out_file))
sample_ped_lines = {}
header = ["#Family_ID", "Individual_ID", "Paternal_ID", "Maternal_ID", "Sex", "Phenotype", "Ethnicity"]
for md_ped in list(set([x for x in [tz.get_in(["metadata", "ped"], data)
for data in samples] if x is not None])):
with open(md_ped) as in_handle:
reader = csv.reader(in_handle, dialect="excel-tab")
for parts in reader:
if parts[0].startswith("#") and len(parts) > len(header):
header = header + parts[len(header):]
else:
sample_ped_lines[parts[1]] = parts
if not utils.file_exists(out_file):
with file_transaction(samples[0], out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
want_samples = set(vcfutils.get_samples(base_vcf))
writer = csv.writer(out_handle, dialect="excel-tab")
writer.writerow(header)
for data in samples:
ped_info = get_ped_info(data, samples)
sname = ped_info["individual_id"]
if sname in want_samples:
want_samples.remove(sname)
if sname in sample_ped_lines:
writer.writerow(sample_ped_lines[sname])
else:
writer.writerow([ped_info["family_id"], ped_info["individual_id"],
ped_info["paternal_id"], ped_info["maternal_id"],
ped_info["gender"], ped_info["affected"],
ped_info["ethnicity"]])
return out_file | python | def create_ped_file(samples, base_vcf, out_dir=None):
"""Create a GEMINI-compatible PED file, including gender, family and phenotype information.
Checks for a specified `ped` file in metadata, and will use sample information from this file
before reconstituting from metadata information.
"""
out_file = "%s.ped" % utils.splitext_plus(base_vcf)[0]
if out_dir:
out_file = os.path.join(out_dir, os.path.basename(out_file))
sample_ped_lines = {}
header = ["#Family_ID", "Individual_ID", "Paternal_ID", "Maternal_ID", "Sex", "Phenotype", "Ethnicity"]
for md_ped in list(set([x for x in [tz.get_in(["metadata", "ped"], data)
for data in samples] if x is not None])):
with open(md_ped) as in_handle:
reader = csv.reader(in_handle, dialect="excel-tab")
for parts in reader:
if parts[0].startswith("#") and len(parts) > len(header):
header = header + parts[len(header):]
else:
sample_ped_lines[parts[1]] = parts
if not utils.file_exists(out_file):
with file_transaction(samples[0], out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
want_samples = set(vcfutils.get_samples(base_vcf))
writer = csv.writer(out_handle, dialect="excel-tab")
writer.writerow(header)
for data in samples:
ped_info = get_ped_info(data, samples)
sname = ped_info["individual_id"]
if sname in want_samples:
want_samples.remove(sname)
if sname in sample_ped_lines:
writer.writerow(sample_ped_lines[sname])
else:
writer.writerow([ped_info["family_id"], ped_info["individual_id"],
ped_info["paternal_id"], ped_info["maternal_id"],
ped_info["gender"], ped_info["affected"],
ped_info["ethnicity"]])
return out_file | [
"def",
"create_ped_file",
"(",
"samples",
",",
"base_vcf",
",",
"out_dir",
"=",
"None",
")",
":",
"out_file",
"=",
"\"%s.ped\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"base_vcf",
")",
"[",
"0",
"]",
"if",
"out_dir",
":",
"out_file",
"=",
"os",
".",
... | Create a GEMINI-compatible PED file, including gender, family and phenotype information.
Checks for a specified `ped` file in metadata, and will use sample information from this file
before reconstituting from metadata information. | [
"Create",
"a",
"GEMINI",
"-",
"compatible",
"PED",
"file",
"including",
"gender",
"family",
"and",
"phenotype",
"information",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/population.py#L240-L278 | train | 218,909 |
bcbio/bcbio-nextgen | bcbio/variation/population.py | _is_small_vcf | def _is_small_vcf(vcf_file):
"""Check for small VCFs which we want to analyze quicker.
"""
count = 0
small_thresh = 250
with utils.open_gzipsafe(vcf_file) as in_handle:
for line in in_handle:
if not line.startswith("#"):
count += 1
if count > small_thresh:
return False
return True | python | def _is_small_vcf(vcf_file):
"""Check for small VCFs which we want to analyze quicker.
"""
count = 0
small_thresh = 250
with utils.open_gzipsafe(vcf_file) as in_handle:
for line in in_handle:
if not line.startswith("#"):
count += 1
if count > small_thresh:
return False
return True | [
"def",
"_is_small_vcf",
"(",
"vcf_file",
")",
":",
"count",
"=",
"0",
"small_thresh",
"=",
"250",
"with",
"utils",
".",
"open_gzipsafe",
"(",
"vcf_file",
")",
"as",
"in_handle",
":",
"for",
"line",
"in",
"in_handle",
":",
"if",
"not",
"line",
".",
"start... | Check for small VCFs which we want to analyze quicker. | [
"Check",
"for",
"small",
"VCFs",
"which",
"we",
"want",
"to",
"analyze",
"quicker",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/population.py#L286-L297 | train | 218,910 |
bcbio/bcbio-nextgen | bcbio/variation/population.py | get_multisample_vcf | def get_multisample_vcf(fnames, name, caller, data):
"""Retrieve a multiple sample VCF file in a standard location.
Handles inputs with multiple repeated input files from batches.
"""
unique_fnames = []
for f in fnames:
if f not in unique_fnames:
unique_fnames.append(f)
out_dir = utils.safe_makedir(os.path.join(data["dirs"]["work"], "gemini"))
if len(unique_fnames) > 1:
gemini_vcf = os.path.join(out_dir, "%s-%s.vcf.gz" % (name, caller))
vrn_file_batch = None
for variant in data.get("variants", []):
if variant["variantcaller"] == caller and variant.get("vrn_file_batch"):
vrn_file_batch = variant["vrn_file_batch"]
if vrn_file_batch:
utils.symlink_plus(vrn_file_batch, gemini_vcf)
return gemini_vcf
else:
return vcfutils.merge_variant_files(unique_fnames, gemini_vcf, dd.get_ref_file(data),
data["config"])
else:
gemini_vcf = os.path.join(out_dir, "%s-%s%s" % (name, caller, utils.splitext_plus(unique_fnames[0])[1]))
utils.symlink_plus(unique_fnames[0], gemini_vcf)
return gemini_vcf | python | def get_multisample_vcf(fnames, name, caller, data):
"""Retrieve a multiple sample VCF file in a standard location.
Handles inputs with multiple repeated input files from batches.
"""
unique_fnames = []
for f in fnames:
if f not in unique_fnames:
unique_fnames.append(f)
out_dir = utils.safe_makedir(os.path.join(data["dirs"]["work"], "gemini"))
if len(unique_fnames) > 1:
gemini_vcf = os.path.join(out_dir, "%s-%s.vcf.gz" % (name, caller))
vrn_file_batch = None
for variant in data.get("variants", []):
if variant["variantcaller"] == caller and variant.get("vrn_file_batch"):
vrn_file_batch = variant["vrn_file_batch"]
if vrn_file_batch:
utils.symlink_plus(vrn_file_batch, gemini_vcf)
return gemini_vcf
else:
return vcfutils.merge_variant_files(unique_fnames, gemini_vcf, dd.get_ref_file(data),
data["config"])
else:
gemini_vcf = os.path.join(out_dir, "%s-%s%s" % (name, caller, utils.splitext_plus(unique_fnames[0])[1]))
utils.symlink_plus(unique_fnames[0], gemini_vcf)
return gemini_vcf | [
"def",
"get_multisample_vcf",
"(",
"fnames",
",",
"name",
",",
"caller",
",",
"data",
")",
":",
"unique_fnames",
"=",
"[",
"]",
"for",
"f",
"in",
"fnames",
":",
"if",
"f",
"not",
"in",
"unique_fnames",
":",
"unique_fnames",
".",
"append",
"(",
"f",
")"... | Retrieve a multiple sample VCF file in a standard location.
Handles inputs with multiple repeated input files from batches. | [
"Retrieve",
"a",
"multiple",
"sample",
"VCF",
"file",
"in",
"a",
"standard",
"location",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/population.py#L299-L324 | train | 218,911 |
bcbio/bcbio-nextgen | bcbio/variation/population.py | get_gemini_files | def get_gemini_files(data):
"""Enumerate available gemini data files in a standard installation.
"""
try:
from gemini import annotations, config
except ImportError:
return {}
return {"base": config.read_gemini_config()["annotation_dir"],
"files": annotations.get_anno_files().values()} | python | def get_gemini_files(data):
"""Enumerate available gemini data files in a standard installation.
"""
try:
from gemini import annotations, config
except ImportError:
return {}
return {"base": config.read_gemini_config()["annotation_dir"],
"files": annotations.get_anno_files().values()} | [
"def",
"get_gemini_files",
"(",
"data",
")",
":",
"try",
":",
"from",
"gemini",
"import",
"annotations",
",",
"config",
"except",
"ImportError",
":",
"return",
"{",
"}",
"return",
"{",
"\"base\"",
":",
"config",
".",
"read_gemini_config",
"(",
")",
"[",
"\... | Enumerate available gemini data files in a standard installation. | [
"Enumerate",
"available",
"gemini",
"data",
"files",
"in",
"a",
"standard",
"installation",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/population.py#L348-L356 | train | 218,912 |
bcbio/bcbio-nextgen | bcbio/variation/population.py | _group_by_batches | def _group_by_batches(samples, check_fn):
"""Group data items into batches, providing details to retrieve results.
"""
batch_groups = collections.defaultdict(list)
singles = []
out_retrieve = []
extras = []
for data in [x[0] for x in samples]:
if check_fn(data):
batch = tz.get_in(["metadata", "batch"], data)
name = str(dd.get_sample_name(data))
if batch:
out_retrieve.append((str(batch), data))
else:
out_retrieve.append((name, data))
for vrn in data["variants"]:
if vrn.get("population", True):
if batch:
batch_groups[(str(batch), vrn["variantcaller"])].append((vrn["vrn_file"], data))
else:
singles.append((name, vrn["variantcaller"], data, vrn["vrn_file"]))
else:
extras.append(data)
return batch_groups, singles, out_retrieve, extras | python | def _group_by_batches(samples, check_fn):
"""Group data items into batches, providing details to retrieve results.
"""
batch_groups = collections.defaultdict(list)
singles = []
out_retrieve = []
extras = []
for data in [x[0] for x in samples]:
if check_fn(data):
batch = tz.get_in(["metadata", "batch"], data)
name = str(dd.get_sample_name(data))
if batch:
out_retrieve.append((str(batch), data))
else:
out_retrieve.append((name, data))
for vrn in data["variants"]:
if vrn.get("population", True):
if batch:
batch_groups[(str(batch), vrn["variantcaller"])].append((vrn["vrn_file"], data))
else:
singles.append((name, vrn["variantcaller"], data, vrn["vrn_file"]))
else:
extras.append(data)
return batch_groups, singles, out_retrieve, extras | [
"def",
"_group_by_batches",
"(",
"samples",
",",
"check_fn",
")",
":",
"batch_groups",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"singles",
"=",
"[",
"]",
"out_retrieve",
"=",
"[",
"]",
"extras",
"=",
"[",
"]",
"for",
"data",
"in",
"[",
... | Group data items into batches, providing details to retrieve results. | [
"Group",
"data",
"items",
"into",
"batches",
"providing",
"details",
"to",
"retrieve",
"results",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/population.py#L358-L381 | train | 218,913 |
bcbio/bcbio-nextgen | bcbio/variation/population.py | prep_db_parallel | def prep_db_parallel(samples, parallel_fn):
"""Prepares gemini databases in parallel, handling jointly called populations.
"""
batch_groups, singles, out_retrieve, extras = _group_by_batches(samples, _has_variant_calls)
to_process = []
has_batches = False
for (name, caller), info in batch_groups.items():
fnames = [x[0] for x in info]
to_process.append([fnames, (str(name), caller, True), [x[1] for x in info], extras])
has_batches = True
for name, caller, data, fname in singles:
to_process.append([[fname], (str(name), caller, False), [data], extras])
output = parallel_fn("prep_gemini_db", to_process)
out_fetch = {}
for batch_id, out_file in output:
out_fetch[tuple(batch_id)] = out_file
out = []
for batch_name, data in out_retrieve:
out_variants = []
for vrn in data["variants"]:
use_population = vrn.pop("population", True)
if use_population:
vrn["population"] = out_fetch[(batch_name, vrn["variantcaller"])]
out_variants.append(vrn)
data["variants"] = out_variants
out.append([data])
for x in extras:
out.append([x])
return out | python | def prep_db_parallel(samples, parallel_fn):
"""Prepares gemini databases in parallel, handling jointly called populations.
"""
batch_groups, singles, out_retrieve, extras = _group_by_batches(samples, _has_variant_calls)
to_process = []
has_batches = False
for (name, caller), info in batch_groups.items():
fnames = [x[0] for x in info]
to_process.append([fnames, (str(name), caller, True), [x[1] for x in info], extras])
has_batches = True
for name, caller, data, fname in singles:
to_process.append([[fname], (str(name), caller, False), [data], extras])
output = parallel_fn("prep_gemini_db", to_process)
out_fetch = {}
for batch_id, out_file in output:
out_fetch[tuple(batch_id)] = out_file
out = []
for batch_name, data in out_retrieve:
out_variants = []
for vrn in data["variants"]:
use_population = vrn.pop("population", True)
if use_population:
vrn["population"] = out_fetch[(batch_name, vrn["variantcaller"])]
out_variants.append(vrn)
data["variants"] = out_variants
out.append([data])
for x in extras:
out.append([x])
return out | [
"def",
"prep_db_parallel",
"(",
"samples",
",",
"parallel_fn",
")",
":",
"batch_groups",
",",
"singles",
",",
"out_retrieve",
",",
"extras",
"=",
"_group_by_batches",
"(",
"samples",
",",
"_has_variant_calls",
")",
"to_process",
"=",
"[",
"]",
"has_batches",
"="... | Prepares gemini databases in parallel, handling jointly called populations. | [
"Prepares",
"gemini",
"databases",
"in",
"parallel",
"handling",
"jointly",
"called",
"populations",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/population.py#L389-L417 | train | 218,914 |
bcbio/bcbio-nextgen | bcbio/workflow/stormseq.py | _get_s3_files | def _get_s3_files(local_dir, file_info, params):
"""Retrieve s3 files to local directory, handling STORMSeq inputs.
"""
assert len(file_info) == 1
files = file_info.values()[0]
fnames = []
for k in ["1", "2"]:
if files[k] not in fnames:
fnames.append(files[k])
out = []
for fname in fnames:
bucket, key = fname.replace("s3://", "").split("/", 1)
if params["access_key_id"] == "TEST":
out.append(os.path.join(local_dir, os.path.basename(key)))
else:
out.append(s3.get_file(local_dir, bucket, key, params))
return out | python | def _get_s3_files(local_dir, file_info, params):
"""Retrieve s3 files to local directory, handling STORMSeq inputs.
"""
assert len(file_info) == 1
files = file_info.values()[0]
fnames = []
for k in ["1", "2"]:
if files[k] not in fnames:
fnames.append(files[k])
out = []
for fname in fnames:
bucket, key = fname.replace("s3://", "").split("/", 1)
if params["access_key_id"] == "TEST":
out.append(os.path.join(local_dir, os.path.basename(key)))
else:
out.append(s3.get_file(local_dir, bucket, key, params))
return out | [
"def",
"_get_s3_files",
"(",
"local_dir",
",",
"file_info",
",",
"params",
")",
":",
"assert",
"len",
"(",
"file_info",
")",
"==",
"1",
"files",
"=",
"file_info",
".",
"values",
"(",
")",
"[",
"0",
"]",
"fnames",
"=",
"[",
"]",
"for",
"k",
"in",
"[... | Retrieve s3 files to local directory, handling STORMSeq inputs. | [
"Retrieve",
"s3",
"files",
"to",
"local",
"directory",
"handling",
"STORMSeq",
"inputs",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/stormseq.py#L22-L38 | train | 218,915 |
bcbio/bcbio-nextgen | bcbio/pipeline/fastq.py | _gzip_fastq | def _gzip_fastq(in_file, out_dir=None):
"""
gzip a fastq file if it is not already gzipped, handling conversion
from bzip to gzipped files
"""
if fastq.is_fastq(in_file) and not objectstore.is_remote(in_file):
if utils.is_bzipped(in_file):
return _bzip_gzip(in_file, out_dir)
elif not utils.is_gzipped(in_file):
if out_dir:
gzipped_file = os.path.join(out_dir, os.path.basename(in_file) + ".gz")
else:
gzipped_file = in_file + ".gz"
if file_exists(gzipped_file):
return gzipped_file
message = "gzipping {in_file} to {gzipped_file}.".format(
in_file=in_file, gzipped_file=gzipped_file)
with file_transaction(gzipped_file) as tx_gzipped_file:
do.run("gzip -c {in_file} > {tx_gzipped_file}".format(**locals()),
message)
return gzipped_file
return in_file | python | def _gzip_fastq(in_file, out_dir=None):
"""
gzip a fastq file if it is not already gzipped, handling conversion
from bzip to gzipped files
"""
if fastq.is_fastq(in_file) and not objectstore.is_remote(in_file):
if utils.is_bzipped(in_file):
return _bzip_gzip(in_file, out_dir)
elif not utils.is_gzipped(in_file):
if out_dir:
gzipped_file = os.path.join(out_dir, os.path.basename(in_file) + ".gz")
else:
gzipped_file = in_file + ".gz"
if file_exists(gzipped_file):
return gzipped_file
message = "gzipping {in_file} to {gzipped_file}.".format(
in_file=in_file, gzipped_file=gzipped_file)
with file_transaction(gzipped_file) as tx_gzipped_file:
do.run("gzip -c {in_file} > {tx_gzipped_file}".format(**locals()),
message)
return gzipped_file
return in_file | [
"def",
"_gzip_fastq",
"(",
"in_file",
",",
"out_dir",
"=",
"None",
")",
":",
"if",
"fastq",
".",
"is_fastq",
"(",
"in_file",
")",
"and",
"not",
"objectstore",
".",
"is_remote",
"(",
"in_file",
")",
":",
"if",
"utils",
".",
"is_bzipped",
"(",
"in_file",
... | gzip a fastq file if it is not already gzipped, handling conversion
from bzip to gzipped files | [
"gzip",
"a",
"fastq",
"file",
"if",
"it",
"is",
"not",
"already",
"gzipped",
"handling",
"conversion",
"from",
"bzip",
"to",
"gzipped",
"files"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/fastq.py#L51-L72 | train | 218,916 |
bcbio/bcbio-nextgen | bcbio/pipeline/fastq.py | _pipeline_needs_fastq | def _pipeline_needs_fastq(config, data):
"""Determine if the pipeline can proceed with a BAM file, or needs fastq conversion.
"""
aligner = config["algorithm"].get("aligner")
support_bam = aligner in alignment.metadata.get("support_bam", [])
return aligner and not support_bam | python | def _pipeline_needs_fastq(config, data):
"""Determine if the pipeline can proceed with a BAM file, or needs fastq conversion.
"""
aligner = config["algorithm"].get("aligner")
support_bam = aligner in alignment.metadata.get("support_bam", [])
return aligner and not support_bam | [
"def",
"_pipeline_needs_fastq",
"(",
"config",
",",
"data",
")",
":",
"aligner",
"=",
"config",
"[",
"\"algorithm\"",
"]",
".",
"get",
"(",
"\"aligner\"",
")",
"support_bam",
"=",
"aligner",
"in",
"alignment",
".",
"metadata",
".",
"get",
"(",
"\"support_bam... | Determine if the pipeline can proceed with a BAM file, or needs fastq conversion. | [
"Determine",
"if",
"the",
"pipeline",
"can",
"proceed",
"with",
"a",
"BAM",
"file",
"or",
"needs",
"fastq",
"conversion",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/fastq.py#L95-L100 | train | 218,917 |
bcbio/bcbio-nextgen | bcbio/pipeline/fastq.py | convert_bam_to_fastq | def convert_bam_to_fastq(in_file, work_dir, data, dirs, config):
"""Convert BAM input file into FASTQ files.
"""
return alignprep.prep_fastq_inputs([in_file], data) | python | def convert_bam_to_fastq(in_file, work_dir, data, dirs, config):
"""Convert BAM input file into FASTQ files.
"""
return alignprep.prep_fastq_inputs([in_file], data) | [
"def",
"convert_bam_to_fastq",
"(",
"in_file",
",",
"work_dir",
",",
"data",
",",
"dirs",
",",
"config",
")",
":",
"return",
"alignprep",
".",
"prep_fastq_inputs",
"(",
"[",
"in_file",
"]",
",",
"data",
")"
] | Convert BAM input file into FASTQ files. | [
"Convert",
"BAM",
"input",
"file",
"into",
"FASTQ",
"files",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/fastq.py#L103-L106 | train | 218,918 |
bcbio/bcbio-nextgen | bcbio/pipeline/fastq.py | merge | def merge(files, out_file, config):
"""merge smartly fastq files. It recognizes paired fastq files."""
pair1 = [fastq_file[0] for fastq_file in files]
if len(files[0]) > 1:
path = splitext_plus(out_file)
pair1_out_file = path[0] + "_R1" + path[1]
pair2 = [fastq_file[1] for fastq_file in files]
pair2_out_file = path[0] + "_R2" + path[1]
_merge_list_fastqs(pair1, pair1_out_file, config)
_merge_list_fastqs(pair2, pair2_out_file, config)
return [pair1_out_file, pair2_out_file]
else:
return _merge_list_fastqs(pair1, out_file, config) | python | def merge(files, out_file, config):
"""merge smartly fastq files. It recognizes paired fastq files."""
pair1 = [fastq_file[0] for fastq_file in files]
if len(files[0]) > 1:
path = splitext_plus(out_file)
pair1_out_file = path[0] + "_R1" + path[1]
pair2 = [fastq_file[1] for fastq_file in files]
pair2_out_file = path[0] + "_R2" + path[1]
_merge_list_fastqs(pair1, pair1_out_file, config)
_merge_list_fastqs(pair2, pair2_out_file, config)
return [pair1_out_file, pair2_out_file]
else:
return _merge_list_fastqs(pair1, out_file, config) | [
"def",
"merge",
"(",
"files",
",",
"out_file",
",",
"config",
")",
":",
"pair1",
"=",
"[",
"fastq_file",
"[",
"0",
"]",
"for",
"fastq_file",
"in",
"files",
"]",
"if",
"len",
"(",
"files",
"[",
"0",
"]",
")",
">",
"1",
":",
"path",
"=",
"splitext_... | merge smartly fastq files. It recognizes paired fastq files. | [
"merge",
"smartly",
"fastq",
"files",
".",
"It",
"recognizes",
"paired",
"fastq",
"files",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/fastq.py#L108-L120 | train | 218,919 |
bcbio/bcbio-nextgen | bcbio/pipeline/fastq.py | _merge_list_fastqs | def _merge_list_fastqs(files, out_file, config):
"""merge list of fastq files into one"""
if not all(map(fastq.is_fastq, files)):
raise ValueError("Not all of the files to merge are fastq files: %s " % (files))
assert all(map(utils.file_exists, files)), ("Not all of the files to merge "
"exist: %s" % (files))
if not file_exists(out_file):
files = [_gzip_fastq(fn) for fn in files]
if len(files) == 1:
if "remove_source" in config and config["remove_source"]:
shutil.move(files[0], out_file)
else:
os.symlink(files[0], out_file)
return out_file
with file_transaction(out_file) as file_txt_out:
files_str = " ".join(list(files))
cmd = "cat {files_str} > {file_txt_out}".format(**locals())
do.run(cmd, "merge fastq files %s" % files)
return out_file | python | def _merge_list_fastqs(files, out_file, config):
"""merge list of fastq files into one"""
if not all(map(fastq.is_fastq, files)):
raise ValueError("Not all of the files to merge are fastq files: %s " % (files))
assert all(map(utils.file_exists, files)), ("Not all of the files to merge "
"exist: %s" % (files))
if not file_exists(out_file):
files = [_gzip_fastq(fn) for fn in files]
if len(files) == 1:
if "remove_source" in config and config["remove_source"]:
shutil.move(files[0], out_file)
else:
os.symlink(files[0], out_file)
return out_file
with file_transaction(out_file) as file_txt_out:
files_str = " ".join(list(files))
cmd = "cat {files_str} > {file_txt_out}".format(**locals())
do.run(cmd, "merge fastq files %s" % files)
return out_file | [
"def",
"_merge_list_fastqs",
"(",
"files",
",",
"out_file",
",",
"config",
")",
":",
"if",
"not",
"all",
"(",
"map",
"(",
"fastq",
".",
"is_fastq",
",",
"files",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"Not all of the files to merge are fastq files: %s \"",... | merge list of fastq files into one | [
"merge",
"list",
"of",
"fastq",
"files",
"into",
"one"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/fastq.py#L122-L140 | train | 218,920 |
bcbio/bcbio-nextgen | bcbio/bed/__init__.py | decomment | def decomment(bed_file, out_file):
"""
clean a BED file
"""
if file_exists(out_file):
return out_file
with utils.open_gzipsafe(bed_file) as in_handle, open(out_file, "w") as out_handle:
for line in in_handle:
if line.startswith("#") or line.startswith("browser") or line.startswith("track"):
continue
else:
out_handle.write(line)
return out_file | python | def decomment(bed_file, out_file):
"""
clean a BED file
"""
if file_exists(out_file):
return out_file
with utils.open_gzipsafe(bed_file) as in_handle, open(out_file, "w") as out_handle:
for line in in_handle:
if line.startswith("#") or line.startswith("browser") or line.startswith("track"):
continue
else:
out_handle.write(line)
return out_file | [
"def",
"decomment",
"(",
"bed_file",
",",
"out_file",
")",
":",
"if",
"file_exists",
"(",
"out_file",
")",
":",
"return",
"out_file",
"with",
"utils",
".",
"open_gzipsafe",
"(",
"bed_file",
")",
"as",
"in_handle",
",",
"open",
"(",
"out_file",
",",
"\"w\""... | clean a BED file | [
"clean",
"a",
"BED",
"file"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bed/__init__.py#L5-L18 | train | 218,921 |
bcbio/bcbio-nextgen | bcbio/bed/__init__.py | concat | def concat(bed_files, catted=None):
"""
recursively concat a set of BED files, returning a
sorted bedtools object of the result
"""
bed_files = [x for x in bed_files if x]
if len(bed_files) == 0:
if catted:
# move to a .bed extension for downstream tools if not already
sorted_bed = catted.sort()
if not sorted_bed.fn.endswith(".bed"):
return sorted_bed.moveto(sorted_bed.fn + ".bed")
else:
return sorted_bed
else:
return catted
if not catted:
bed_files = list(bed_files)
catted = bt.BedTool(bed_files.pop())
else:
catted = catted.cat(bed_files.pop(), postmerge=False,
force_truncate=False)
return concat(bed_files, catted) | python | def concat(bed_files, catted=None):
"""
recursively concat a set of BED files, returning a
sorted bedtools object of the result
"""
bed_files = [x for x in bed_files if x]
if len(bed_files) == 0:
if catted:
# move to a .bed extension for downstream tools if not already
sorted_bed = catted.sort()
if not sorted_bed.fn.endswith(".bed"):
return sorted_bed.moveto(sorted_bed.fn + ".bed")
else:
return sorted_bed
else:
return catted
if not catted:
bed_files = list(bed_files)
catted = bt.BedTool(bed_files.pop())
else:
catted = catted.cat(bed_files.pop(), postmerge=False,
force_truncate=False)
return concat(bed_files, catted) | [
"def",
"concat",
"(",
"bed_files",
",",
"catted",
"=",
"None",
")",
":",
"bed_files",
"=",
"[",
"x",
"for",
"x",
"in",
"bed_files",
"if",
"x",
"]",
"if",
"len",
"(",
"bed_files",
")",
"==",
"0",
":",
"if",
"catted",
":",
"# move to a .bed extension for... | recursively concat a set of BED files, returning a
sorted bedtools object of the result | [
"recursively",
"concat",
"a",
"set",
"of",
"BED",
"files",
"returning",
"a",
"sorted",
"bedtools",
"object",
"of",
"the",
"result"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bed/__init__.py#L20-L44 | train | 218,922 |
bcbio/bcbio-nextgen | bcbio/bed/__init__.py | merge | def merge(bedfiles):
"""
given a BED file or list of BED files merge them an return a bedtools object
"""
if isinstance(bedfiles, list):
catted = concat(bedfiles)
else:
catted = concat([bedfiles])
if catted:
return concat(bedfiles).sort().merge()
else:
return catted | python | def merge(bedfiles):
"""
given a BED file or list of BED files merge them an return a bedtools object
"""
if isinstance(bedfiles, list):
catted = concat(bedfiles)
else:
catted = concat([bedfiles])
if catted:
return concat(bedfiles).sort().merge()
else:
return catted | [
"def",
"merge",
"(",
"bedfiles",
")",
":",
"if",
"isinstance",
"(",
"bedfiles",
",",
"list",
")",
":",
"catted",
"=",
"concat",
"(",
"bedfiles",
")",
"else",
":",
"catted",
"=",
"concat",
"(",
"[",
"bedfiles",
"]",
")",
"if",
"catted",
":",
"return",... | given a BED file or list of BED files merge them an return a bedtools object | [
"given",
"a",
"BED",
"file",
"or",
"list",
"of",
"BED",
"files",
"merge",
"them",
"an",
"return",
"a",
"bedtools",
"object"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bed/__init__.py#L46-L57 | train | 218,923 |
bcbio/bcbio-nextgen | bcbio/structural/hydra.py | select_unaligned_read_pairs | def select_unaligned_read_pairs(in_bam, extra, out_dir, config):
"""Retrieve unaligned read pairs from input alignment BAM, as two fastq files.
"""
runner = broad.runner_from_config(config)
base, ext = os.path.splitext(os.path.basename(in_bam))
nomap_bam = os.path.join(out_dir, "{}-{}{}".format(base, extra, ext))
if not utils.file_exists(nomap_bam):
with file_transaction(nomap_bam) as tx_out:
runner.run("FilterSamReads", [("INPUT", in_bam),
("OUTPUT", tx_out),
("EXCLUDE_ALIGNED", "true"),
("WRITE_READS_FILES", "false"),
("SORT_ORDER", "queryname")])
has_reads = False
with pysam.Samfile(nomap_bam, "rb") as in_pysam:
for read in in_pysam:
if read.is_paired:
has_reads = True
break
if has_reads:
out_fq1, out_fq2 = ["{}-{}.fq".format(os.path.splitext(nomap_bam)[0], i) for i in [1, 2]]
runner.run_fn("picard_bam_to_fastq", nomap_bam, out_fq1, out_fq2)
return out_fq1, out_fq2
else:
return None, None | python | def select_unaligned_read_pairs(in_bam, extra, out_dir, config):
"""Retrieve unaligned read pairs from input alignment BAM, as two fastq files.
"""
runner = broad.runner_from_config(config)
base, ext = os.path.splitext(os.path.basename(in_bam))
nomap_bam = os.path.join(out_dir, "{}-{}{}".format(base, extra, ext))
if not utils.file_exists(nomap_bam):
with file_transaction(nomap_bam) as tx_out:
runner.run("FilterSamReads", [("INPUT", in_bam),
("OUTPUT", tx_out),
("EXCLUDE_ALIGNED", "true"),
("WRITE_READS_FILES", "false"),
("SORT_ORDER", "queryname")])
has_reads = False
with pysam.Samfile(nomap_bam, "rb") as in_pysam:
for read in in_pysam:
if read.is_paired:
has_reads = True
break
if has_reads:
out_fq1, out_fq2 = ["{}-{}.fq".format(os.path.splitext(nomap_bam)[0], i) for i in [1, 2]]
runner.run_fn("picard_bam_to_fastq", nomap_bam, out_fq1, out_fq2)
return out_fq1, out_fq2
else:
return None, None | [
"def",
"select_unaligned_read_pairs",
"(",
"in_bam",
",",
"extra",
",",
"out_dir",
",",
"config",
")",
":",
"runner",
"=",
"broad",
".",
"runner_from_config",
"(",
"config",
")",
"base",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
"."... | Retrieve unaligned read pairs from input alignment BAM, as two fastq files. | [
"Retrieve",
"unaligned",
"read",
"pairs",
"from",
"input",
"alignment",
"BAM",
"as",
"two",
"fastq",
"files",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/hydra.py#L22-L46 | train | 218,924 |
bcbio/bcbio-nextgen | bcbio/structural/hydra.py | remove_nopairs | def remove_nopairs(in_bam, out_dir, config):
"""Remove any reads without both pairs present in the file.
"""
runner = broad.runner_from_config(config)
out_bam = os.path.join(out_dir, "{}-safepair{}".format(*os.path.splitext(os.path.basename(in_bam))))
if not utils.file_exists(out_bam):
read_counts = collections.defaultdict(int)
with pysam.Samfile(in_bam, "rb") as in_pysam:
for read in in_pysam:
if read.is_paired:
read_counts[read.qname] += 1
with pysam.Samfile(in_bam, "rb") as in_pysam:
with file_transaction(out_bam) as tx_out_bam:
with pysam.Samfile(tx_out_bam, "wb", template=in_pysam) as out_pysam:
for read in in_pysam:
if read_counts[read.qname] == 2:
out_pysam.write(read)
return runner.run_fn("picard_sort", out_bam, "queryname") | python | def remove_nopairs(in_bam, out_dir, config):
"""Remove any reads without both pairs present in the file.
"""
runner = broad.runner_from_config(config)
out_bam = os.path.join(out_dir, "{}-safepair{}".format(*os.path.splitext(os.path.basename(in_bam))))
if not utils.file_exists(out_bam):
read_counts = collections.defaultdict(int)
with pysam.Samfile(in_bam, "rb") as in_pysam:
for read in in_pysam:
if read.is_paired:
read_counts[read.qname] += 1
with pysam.Samfile(in_bam, "rb") as in_pysam:
with file_transaction(out_bam) as tx_out_bam:
with pysam.Samfile(tx_out_bam, "wb", template=in_pysam) as out_pysam:
for read in in_pysam:
if read_counts[read.qname] == 2:
out_pysam.write(read)
return runner.run_fn("picard_sort", out_bam, "queryname") | [
"def",
"remove_nopairs",
"(",
"in_bam",
",",
"out_dir",
",",
"config",
")",
":",
"runner",
"=",
"broad",
".",
"runner_from_config",
"(",
"config",
")",
"out_bam",
"=",
"os",
".",
"path",
".",
"join",
"(",
"out_dir",
",",
"\"{}-safepair{}\"",
".",
"format",... | Remove any reads without both pairs present in the file. | [
"Remove",
"any",
"reads",
"without",
"both",
"pairs",
"present",
"in",
"the",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/hydra.py#L48-L65 | train | 218,925 |
bcbio/bcbio-nextgen | bcbio/structural/hydra.py | tiered_alignment | def tiered_alignment(in_bam, tier_num, multi_mappers, extra_args,
genome_build, pair_stats,
work_dir, dirs, config):
"""Perform the alignment of non-mapped reads from previous tier.
"""
nomap_fq1, nomap_fq2 = select_unaligned_read_pairs(in_bam, "tier{}".format(tier_num),
work_dir, config)
if nomap_fq1 is not None:
base_name = "{}-tier{}out".format(os.path.splitext(os.path.basename(in_bam))[0],
tier_num)
config = copy.deepcopy(config)
dirs = copy.deepcopy(dirs)
config["algorithm"]["bam_sort"] = "queryname"
config["algorithm"]["multiple_mappers"] = multi_mappers
config["algorithm"]["extra_align_args"] = ["-i", int(pair_stats["mean"]),
int(pair_stats["std"])] + extra_args
out_bam, ref_file = align_to_sort_bam(nomap_fq1, nomap_fq2,
lane.rg_names(base_name, base_name, config),
genome_build, "novoalign",
dirs, config,
dir_ext=os.path.join("hydra", os.path.split(nomap_fq1)[0]))
return out_bam
else:
return None | python | def tiered_alignment(in_bam, tier_num, multi_mappers, extra_args,
genome_build, pair_stats,
work_dir, dirs, config):
"""Perform the alignment of non-mapped reads from previous tier.
"""
nomap_fq1, nomap_fq2 = select_unaligned_read_pairs(in_bam, "tier{}".format(tier_num),
work_dir, config)
if nomap_fq1 is not None:
base_name = "{}-tier{}out".format(os.path.splitext(os.path.basename(in_bam))[0],
tier_num)
config = copy.deepcopy(config)
dirs = copy.deepcopy(dirs)
config["algorithm"]["bam_sort"] = "queryname"
config["algorithm"]["multiple_mappers"] = multi_mappers
config["algorithm"]["extra_align_args"] = ["-i", int(pair_stats["mean"]),
int(pair_stats["std"])] + extra_args
out_bam, ref_file = align_to_sort_bam(nomap_fq1, nomap_fq2,
lane.rg_names(base_name, base_name, config),
genome_build, "novoalign",
dirs, config,
dir_ext=os.path.join("hydra", os.path.split(nomap_fq1)[0]))
return out_bam
else:
return None | [
"def",
"tiered_alignment",
"(",
"in_bam",
",",
"tier_num",
",",
"multi_mappers",
",",
"extra_args",
",",
"genome_build",
",",
"pair_stats",
",",
"work_dir",
",",
"dirs",
",",
"config",
")",
":",
"nomap_fq1",
",",
"nomap_fq2",
"=",
"select_unaligned_read_pairs",
... | Perform the alignment of non-mapped reads from previous tier. | [
"Perform",
"the",
"alignment",
"of",
"non",
"-",
"mapped",
"reads",
"from",
"previous",
"tier",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/hydra.py#L68-L91 | train | 218,926 |
bcbio/bcbio-nextgen | bcbio/structural/hydra.py | convert_bam_to_bed | def convert_bam_to_bed(in_bam, out_file):
"""Convert BAM to bed file using BEDTools.
"""
with file_transaction(out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
subprocess.check_call(["bamToBed", "-i", in_bam, "-tag", "NM"],
stdout=out_handle)
return out_file | python | def convert_bam_to_bed(in_bam, out_file):
"""Convert BAM to bed file using BEDTools.
"""
with file_transaction(out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
subprocess.check_call(["bamToBed", "-i", in_bam, "-tag", "NM"],
stdout=out_handle)
return out_file | [
"def",
"convert_bam_to_bed",
"(",
"in_bam",
",",
"out_file",
")",
":",
"with",
"file_transaction",
"(",
"out_file",
")",
"as",
"tx_out_file",
":",
"with",
"open",
"(",
"tx_out_file",
",",
"\"w\"",
")",
"as",
"out_handle",
":",
"subprocess",
".",
"check_call",
... | Convert BAM to bed file using BEDTools. | [
"Convert",
"BAM",
"to",
"bed",
"file",
"using",
"BEDTools",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/hydra.py#L96-L103 | train | 218,927 |
bcbio/bcbio-nextgen | bcbio/structural/hydra.py | hydra_breakpoints | def hydra_breakpoints(in_bam, pair_stats):
"""Detect structural variation breakpoints with hydra.
"""
in_bed = convert_bam_to_bed(in_bam)
if os.path.getsize(in_bed) > 0:
pair_bed = pair_discordants(in_bed, pair_stats)
dedup_bed = dedup_discordants(pair_bed)
return run_hydra(dedup_bed, pair_stats)
else:
return None | python | def hydra_breakpoints(in_bam, pair_stats):
"""Detect structural variation breakpoints with hydra.
"""
in_bed = convert_bam_to_bed(in_bam)
if os.path.getsize(in_bed) > 0:
pair_bed = pair_discordants(in_bed, pair_stats)
dedup_bed = dedup_discordants(pair_bed)
return run_hydra(dedup_bed, pair_stats)
else:
return None | [
"def",
"hydra_breakpoints",
"(",
"in_bam",
",",
"pair_stats",
")",
":",
"in_bed",
"=",
"convert_bam_to_bed",
"(",
"in_bam",
")",
"if",
"os",
".",
"path",
".",
"getsize",
"(",
"in_bed",
")",
">",
"0",
":",
"pair_bed",
"=",
"pair_discordants",
"(",
"in_bed",... | Detect structural variation breakpoints with hydra. | [
"Detect",
"structural",
"variation",
"breakpoints",
"with",
"hydra",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/hydra.py#L135-L144 | train | 218,928 |
bcbio/bcbio-nextgen | bcbio/structural/hydra.py | detect_sv | def detect_sv(align_bam, genome_build, dirs, config):
"""Detect structural variation from discordant aligned pairs.
"""
work_dir = utils.safe_makedir(os.path.join(dirs["work"], "structural"))
pair_stats = shared.calc_paired_insert_stats(align_bam)
fix_bam = remove_nopairs(align_bam, work_dir, config)
tier2_align = tiered_alignment(fix_bam, "2", True, [],
genome_build, pair_stats,
work_dir, dirs, config)
if tier2_align:
tier3_align = tiered_alignment(tier2_align, "3", "Ex 1100", ["-t", "300"],
genome_build, pair_stats,
work_dir, dirs, config)
if tier3_align:
hydra_bps = hydra_breakpoints(tier3_align, pair_stats) | python | def detect_sv(align_bam, genome_build, dirs, config):
"""Detect structural variation from discordant aligned pairs.
"""
work_dir = utils.safe_makedir(os.path.join(dirs["work"], "structural"))
pair_stats = shared.calc_paired_insert_stats(align_bam)
fix_bam = remove_nopairs(align_bam, work_dir, config)
tier2_align = tiered_alignment(fix_bam, "2", True, [],
genome_build, pair_stats,
work_dir, dirs, config)
if tier2_align:
tier3_align = tiered_alignment(tier2_align, "3", "Ex 1100", ["-t", "300"],
genome_build, pair_stats,
work_dir, dirs, config)
if tier3_align:
hydra_bps = hydra_breakpoints(tier3_align, pair_stats) | [
"def",
"detect_sv",
"(",
"align_bam",
",",
"genome_build",
",",
"dirs",
",",
"config",
")",
":",
"work_dir",
"=",
"utils",
".",
"safe_makedir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dirs",
"[",
"\"work\"",
"]",
",",
"\"structural\"",
")",
")",
"pa... | Detect structural variation from discordant aligned pairs. | [
"Detect",
"structural",
"variation",
"from",
"discordant",
"aligned",
"pairs",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/hydra.py#L148-L162 | train | 218,929 |
bcbio/bcbio-nextgen | bcbio/log/logbook_zmqpush.py | inject | def inject(**params):
"""
A Logbook processor to inject arbitrary information into log records.
Simply pass in keyword arguments and use as a context manager:
>>> with inject(identifier=str(uuid.uuid4())).applicationbound():
... logger.debug('Something happened')
"""
def callback(log_record):
log_record.extra.update(params)
return logbook.Processor(callback) | python | def inject(**params):
"""
A Logbook processor to inject arbitrary information into log records.
Simply pass in keyword arguments and use as a context manager:
>>> with inject(identifier=str(uuid.uuid4())).applicationbound():
... logger.debug('Something happened')
"""
def callback(log_record):
log_record.extra.update(params)
return logbook.Processor(callback) | [
"def",
"inject",
"(",
"*",
"*",
"params",
")",
":",
"def",
"callback",
"(",
"log_record",
")",
":",
"log_record",
".",
"extra",
".",
"update",
"(",
"params",
")",
"return",
"logbook",
".",
"Processor",
"(",
"callback",
")"
] | A Logbook processor to inject arbitrary information into log records.
Simply pass in keyword arguments and use as a context manager:
>>> with inject(identifier=str(uuid.uuid4())).applicationbound():
... logger.debug('Something happened') | [
"A",
"Logbook",
"processor",
"to",
"inject",
"arbitrary",
"information",
"into",
"log",
"records",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/log/logbook_zmqpush.py#L121-L134 | train | 218,930 |
bcbio/bcbio-nextgen | bcbio/log/logbook_zmqpush.py | ZeroMQPullSubscriber.recv | def recv(self, timeout=None):
"""Overwrite standard recv for timeout calls to catch interrupt errors.
"""
if timeout:
try:
testsock = self._zmq.select([self.socket], [], [], timeout)[0]
except zmq.ZMQError as e:
if e.errno == errno.EINTR:
testsock = None
else:
raise
if not testsock:
return
rv = self.socket.recv(self._zmq.NOBLOCK)
return LogRecord.from_dict(json.loads(rv))
else:
return super(ZeroMQPullSubscriber, self).recv(timeout) | python | def recv(self, timeout=None):
"""Overwrite standard recv for timeout calls to catch interrupt errors.
"""
if timeout:
try:
testsock = self._zmq.select([self.socket], [], [], timeout)[0]
except zmq.ZMQError as e:
if e.errno == errno.EINTR:
testsock = None
else:
raise
if not testsock:
return
rv = self.socket.recv(self._zmq.NOBLOCK)
return LogRecord.from_dict(json.loads(rv))
else:
return super(ZeroMQPullSubscriber, self).recv(timeout) | [
"def",
"recv",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"timeout",
":",
"try",
":",
"testsock",
"=",
"self",
".",
"_zmq",
".",
"select",
"(",
"[",
"self",
".",
"socket",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"timeout",
")",
... | Overwrite standard recv for timeout calls to catch interrupt errors. | [
"Overwrite",
"standard",
"recv",
"for",
"timeout",
"calls",
"to",
"catch",
"interrupt",
"errors",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/log/logbook_zmqpush.py#L98-L114 | train | 218,931 |
bcbio/bcbio-nextgen | bcbio/variation/pisces.py | run | def run(align_bams, items, ref_file, assoc_files, region=None, out_file=None):
"""Run tumor only pisces calling
Handles bgzipping output file and fixing VCF sample naming to match BAM sample.
"""
paired = vcfutils.get_paired_bams(align_bams, items)
assert paired and not paired.normal_bam, ("Pisces supports tumor-only variant calling: %s" %
(",".join([dd.get_sample_name(d) for d in items])))
vrs = bedutils.population_variant_regions(items)
target = shared.subset_variant_regions(vrs, region,
out_file, items=items, do_merge=True)
min_af = float(dd.get_min_allele_fraction(paired.tumor_data)) / 100.0
if not utils.file_exists(out_file):
base_out_name = utils.splitext_plus(os.path.basename(paired.tumor_bam))[0]
raw_file = "%s.vcf" % utils.splitext_plus(out_file)[0]
with file_transaction(paired.tumor_data, raw_file) as tx_out_file:
ref_dir = _prep_genome(os.path.dirname(tx_out_file), paired.tumor_data)
out_dir = os.path.dirname(tx_out_file)
cores = dd.get_num_cores(paired.tumor_data)
emit_min_af = min_af / 10.0
cmd = ("pisces --bampaths {paired.tumor_bam} --genomepaths {ref_dir} --intervalpaths {target} "
"--maxthreads {cores} --minvf {emit_min_af} --vffilter {min_af} "
"--ploidy somatic --gvcf false -o {out_dir}")
# Recommended filtering for low frequency indels
# https://github.com/bcbio/bcbio-nextgen/commit/49d0cbb1f6dcbea629c63749e2f9813bd06dcee3#commitcomment-29765373
cmd += " -RMxNFilter 5,9,0.35"
# For low frequency UMI tagged variants, set higher variant thresholds
# https://github.com/Illumina/Pisces/issues/14#issuecomment-399756862
if min_af < (1.0 / 100.0):
cmd += " --minbasecallquality 30"
do.run(cmd.format(**locals()), "Pisces tumor-only somatic calling")
shutil.move(os.path.join(out_dir, "%s.vcf" % base_out_name),
tx_out_file)
vcfutils.bgzip_and_index(raw_file, paired.tumor_data["config"],
prep_cmd="sed 's#%s.bam#%s#' | %s" %
(base_out_name, dd.get_sample_name(paired.tumor_data),
vcfutils.add_contig_to_header_cl(dd.get_ref_file(paired.tumor_data), out_file)))
return vcfutils.bgzip_and_index(out_file, paired.tumor_data["config"]) | python | def run(align_bams, items, ref_file, assoc_files, region=None, out_file=None):
"""Run tumor only pisces calling
Handles bgzipping output file and fixing VCF sample naming to match BAM sample.
"""
paired = vcfutils.get_paired_bams(align_bams, items)
assert paired and not paired.normal_bam, ("Pisces supports tumor-only variant calling: %s" %
(",".join([dd.get_sample_name(d) for d in items])))
vrs = bedutils.population_variant_regions(items)
target = shared.subset_variant_regions(vrs, region,
out_file, items=items, do_merge=True)
min_af = float(dd.get_min_allele_fraction(paired.tumor_data)) / 100.0
if not utils.file_exists(out_file):
base_out_name = utils.splitext_plus(os.path.basename(paired.tumor_bam))[0]
raw_file = "%s.vcf" % utils.splitext_plus(out_file)[0]
with file_transaction(paired.tumor_data, raw_file) as tx_out_file:
ref_dir = _prep_genome(os.path.dirname(tx_out_file), paired.tumor_data)
out_dir = os.path.dirname(tx_out_file)
cores = dd.get_num_cores(paired.tumor_data)
emit_min_af = min_af / 10.0
cmd = ("pisces --bampaths {paired.tumor_bam} --genomepaths {ref_dir} --intervalpaths {target} "
"--maxthreads {cores} --minvf {emit_min_af} --vffilter {min_af} "
"--ploidy somatic --gvcf false -o {out_dir}")
# Recommended filtering for low frequency indels
# https://github.com/bcbio/bcbio-nextgen/commit/49d0cbb1f6dcbea629c63749e2f9813bd06dcee3#commitcomment-29765373
cmd += " -RMxNFilter 5,9,0.35"
# For low frequency UMI tagged variants, set higher variant thresholds
# https://github.com/Illumina/Pisces/issues/14#issuecomment-399756862
if min_af < (1.0 / 100.0):
cmd += " --minbasecallquality 30"
do.run(cmd.format(**locals()), "Pisces tumor-only somatic calling")
shutil.move(os.path.join(out_dir, "%s.vcf" % base_out_name),
tx_out_file)
vcfutils.bgzip_and_index(raw_file, paired.tumor_data["config"],
prep_cmd="sed 's#%s.bam#%s#' | %s" %
(base_out_name, dd.get_sample_name(paired.tumor_data),
vcfutils.add_contig_to_header_cl(dd.get_ref_file(paired.tumor_data), out_file)))
return vcfutils.bgzip_and_index(out_file, paired.tumor_data["config"]) | [
"def",
"run",
"(",
"align_bams",
",",
"items",
",",
"ref_file",
",",
"assoc_files",
",",
"region",
"=",
"None",
",",
"out_file",
"=",
"None",
")",
":",
"paired",
"=",
"vcfutils",
".",
"get_paired_bams",
"(",
"align_bams",
",",
"items",
")",
"assert",
"pa... | Run tumor only pisces calling
Handles bgzipping output file and fixing VCF sample naming to match BAM sample. | [
"Run",
"tumor",
"only",
"pisces",
"calling"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/pisces.py#L17-L54 | train | 218,932 |
bcbio/bcbio-nextgen | bcbio/variation/pisces.py | _prep_genome | def _prep_genome(out_dir, data):
"""Create prepped reference directory for pisces.
Requires a custom GenomeSize.xml file present.
"""
genome_name = utils.splitext_plus(os.path.basename(dd.get_ref_file(data)))[0]
out_dir = utils.safe_makedir(os.path.join(out_dir, genome_name))
ref_file = dd.get_ref_file(data)
utils.symlink_plus(ref_file, os.path.join(out_dir, os.path.basename(ref_file)))
with open(os.path.join(out_dir, "GenomeSize.xml"), "w") as out_handle:
out_handle.write('<sequenceSizes genomeName="%s">' % genome_name)
for c in pysam.AlignmentFile("%s.dict" % utils.splitext_plus(ref_file)[0]).header["SQ"]:
cur_ploidy = ploidy.get_ploidy([data], region=[c["SN"]])
out_handle.write('<chromosome fileName="%s" contigName="%s" totalBases="%s" knownBases="%s" '
'isCircular="false" ploidy="%s" md5="%s"/>' %
(os.path.basename(ref_file), c["SN"], c["LN"], c["LN"], cur_ploidy, c["M5"]))
out_handle.write('</sequenceSizes>')
return out_dir | python | def _prep_genome(out_dir, data):
"""Create prepped reference directory for pisces.
Requires a custom GenomeSize.xml file present.
"""
genome_name = utils.splitext_plus(os.path.basename(dd.get_ref_file(data)))[0]
out_dir = utils.safe_makedir(os.path.join(out_dir, genome_name))
ref_file = dd.get_ref_file(data)
utils.symlink_plus(ref_file, os.path.join(out_dir, os.path.basename(ref_file)))
with open(os.path.join(out_dir, "GenomeSize.xml"), "w") as out_handle:
out_handle.write('<sequenceSizes genomeName="%s">' % genome_name)
for c in pysam.AlignmentFile("%s.dict" % utils.splitext_plus(ref_file)[0]).header["SQ"]:
cur_ploidy = ploidy.get_ploidy([data], region=[c["SN"]])
out_handle.write('<chromosome fileName="%s" contigName="%s" totalBases="%s" knownBases="%s" '
'isCircular="false" ploidy="%s" md5="%s"/>' %
(os.path.basename(ref_file), c["SN"], c["LN"], c["LN"], cur_ploidy, c["M5"]))
out_handle.write('</sequenceSizes>')
return out_dir | [
"def",
"_prep_genome",
"(",
"out_dir",
",",
"data",
")",
":",
"genome_name",
"=",
"utils",
".",
"splitext_plus",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"dd",
".",
"get_ref_file",
"(",
"data",
")",
")",
")",
"[",
"0",
"]",
"out_dir",
"=",
"util... | Create prepped reference directory for pisces.
Requires a custom GenomeSize.xml file present. | [
"Create",
"prepped",
"reference",
"directory",
"for",
"pisces",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/pisces.py#L56-L73 | train | 218,933 |
bcbio/bcbio-nextgen | bcbio/variation/deepvariant.py | run | def run(align_bams, items, ref_file, assoc_files, region, out_file):
"""Return DeepVariant calling on germline samples.
region can be a single region or list of multiple regions for multicore calling.
"""
assert not vcfutils.is_paired_analysis(align_bams, items), \
("DeepVariant currently only supports germline calling: %s" %
(", ".join([dd.get_sample_name(d) for d in items])))
assert len(items) == 1, \
("DeepVariant currently only supports single sample calling: %s" %
(", ".join([dd.get_sample_name(d) for d in items])))
out_file = _run_germline(align_bams[0], items[0], ref_file,
region, out_file)
return vcfutils.bgzip_and_index(out_file, items[0]["config"]) | python | def run(align_bams, items, ref_file, assoc_files, region, out_file):
"""Return DeepVariant calling on germline samples.
region can be a single region or list of multiple regions for multicore calling.
"""
assert not vcfutils.is_paired_analysis(align_bams, items), \
("DeepVariant currently only supports germline calling: %s" %
(", ".join([dd.get_sample_name(d) for d in items])))
assert len(items) == 1, \
("DeepVariant currently only supports single sample calling: %s" %
(", ".join([dd.get_sample_name(d) for d in items])))
out_file = _run_germline(align_bams[0], items[0], ref_file,
region, out_file)
return vcfutils.bgzip_and_index(out_file, items[0]["config"]) | [
"def",
"run",
"(",
"align_bams",
",",
"items",
",",
"ref_file",
",",
"assoc_files",
",",
"region",
",",
"out_file",
")",
":",
"assert",
"not",
"vcfutils",
".",
"is_paired_analysis",
"(",
"align_bams",
",",
"items",
")",
",",
"(",
"\"DeepVariant currently only ... | Return DeepVariant calling on germline samples.
region can be a single region or list of multiple regions for multicore calling. | [
"Return",
"DeepVariant",
"calling",
"on",
"germline",
"samples",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/deepvariant.py#L12-L25 | train | 218,934 |
bcbio/bcbio-nextgen | bcbio/variation/deepvariant.py | _run_germline | def _run_germline(bam_file, data, ref_file, region, out_file):
"""Single sample germline variant calling.
"""
work_dir = utils.safe_makedir("%s-work" % utils.splitext_plus(out_file)[0])
region_bed = strelka2.get_region_bed(region, [data], out_file, want_gzip=False)
example_dir = _make_examples(bam_file, data, ref_file, region_bed, out_file, work_dir)
if _has_candidate_variants(example_dir):
tfrecord_file = _call_variants(example_dir, region_bed, data, out_file)
return _postprocess_variants(tfrecord_file, data, ref_file, out_file)
else:
return vcfutils.write_empty_vcf(out_file, data["config"], [dd.get_sample_name(data)]) | python | def _run_germline(bam_file, data, ref_file, region, out_file):
"""Single sample germline variant calling.
"""
work_dir = utils.safe_makedir("%s-work" % utils.splitext_plus(out_file)[0])
region_bed = strelka2.get_region_bed(region, [data], out_file, want_gzip=False)
example_dir = _make_examples(bam_file, data, ref_file, region_bed, out_file, work_dir)
if _has_candidate_variants(example_dir):
tfrecord_file = _call_variants(example_dir, region_bed, data, out_file)
return _postprocess_variants(tfrecord_file, data, ref_file, out_file)
else:
return vcfutils.write_empty_vcf(out_file, data["config"], [dd.get_sample_name(data)]) | [
"def",
"_run_germline",
"(",
"bam_file",
",",
"data",
",",
"ref_file",
",",
"region",
",",
"out_file",
")",
":",
"work_dir",
"=",
"utils",
".",
"safe_makedir",
"(",
"\"%s-work\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"out_file",
")",
"[",
"0",
"]",
"... | Single sample germline variant calling. | [
"Single",
"sample",
"germline",
"variant",
"calling",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/deepvariant.py#L27-L37 | train | 218,935 |
bcbio/bcbio-nextgen | bcbio/variation/deepvariant.py | _make_examples | def _make_examples(bam_file, data, ref_file, region_bed, out_file, work_dir):
"""Create example pileup images to feed into variant calling.
"""
log_dir = utils.safe_makedir(os.path.join(work_dir, "log"))
example_dir = utils.safe_makedir(os.path.join(work_dir, "examples"))
if len(glob.glob(os.path.join(example_dir, "%s.tfrecord*.gz" % dd.get_sample_name(data)))) == 0:
with tx_tmpdir(data) as tx_example_dir:
cmd = ["dv_make_examples.py", "--cores", dd.get_num_cores(data), "--ref", ref_file,
"--reads", bam_file, "--regions", region_bed, "--logdir", log_dir,
"--examples", tx_example_dir, "--sample", dd.get_sample_name(data)]
do.run(cmd, "DeepVariant make_examples %s" % dd.get_sample_name(data))
for fname in glob.glob(os.path.join(tx_example_dir, "%s.tfrecord*.gz" % dd.get_sample_name(data))):
utils.copy_plus(fname, os.path.join(example_dir, os.path.basename(fname)))
return example_dir | python | def _make_examples(bam_file, data, ref_file, region_bed, out_file, work_dir):
"""Create example pileup images to feed into variant calling.
"""
log_dir = utils.safe_makedir(os.path.join(work_dir, "log"))
example_dir = utils.safe_makedir(os.path.join(work_dir, "examples"))
if len(glob.glob(os.path.join(example_dir, "%s.tfrecord*.gz" % dd.get_sample_name(data)))) == 0:
with tx_tmpdir(data) as tx_example_dir:
cmd = ["dv_make_examples.py", "--cores", dd.get_num_cores(data), "--ref", ref_file,
"--reads", bam_file, "--regions", region_bed, "--logdir", log_dir,
"--examples", tx_example_dir, "--sample", dd.get_sample_name(data)]
do.run(cmd, "DeepVariant make_examples %s" % dd.get_sample_name(data))
for fname in glob.glob(os.path.join(tx_example_dir, "%s.tfrecord*.gz" % dd.get_sample_name(data))):
utils.copy_plus(fname, os.path.join(example_dir, os.path.basename(fname)))
return example_dir | [
"def",
"_make_examples",
"(",
"bam_file",
",",
"data",
",",
"ref_file",
",",
"region_bed",
",",
"out_file",
",",
"work_dir",
")",
":",
"log_dir",
"=",
"utils",
".",
"safe_makedir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"work_dir",
",",
"\"log\"",
")"... | Create example pileup images to feed into variant calling. | [
"Create",
"example",
"pileup",
"images",
"to",
"feed",
"into",
"variant",
"calling",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/deepvariant.py#L42-L55 | train | 218,936 |
bcbio/bcbio-nextgen | bcbio/variation/deepvariant.py | _call_variants | def _call_variants(example_dir, region_bed, data, out_file):
"""Call variants from prepared pileup examples, creating tensorflow record file.
"""
tf_out_file = "%s-tfrecord.gz" % utils.splitext_plus(out_file)[0]
if not utils.file_exists(tf_out_file):
with file_transaction(data, tf_out_file) as tx_out_file:
model = "wes" if strelka2.coverage_interval_from_bed(region_bed) == "targeted" else "wgs"
cmd = ["dv_call_variants.py", "--cores", dd.get_num_cores(data),
"--outfile", tx_out_file, "--examples", example_dir,
"--sample", dd.get_sample_name(data), "--model", model]
do.run(cmd, "DeepVariant call_variants %s" % dd.get_sample_name(data))
return tf_out_file | python | def _call_variants(example_dir, region_bed, data, out_file):
"""Call variants from prepared pileup examples, creating tensorflow record file.
"""
tf_out_file = "%s-tfrecord.gz" % utils.splitext_plus(out_file)[0]
if not utils.file_exists(tf_out_file):
with file_transaction(data, tf_out_file) as tx_out_file:
model = "wes" if strelka2.coverage_interval_from_bed(region_bed) == "targeted" else "wgs"
cmd = ["dv_call_variants.py", "--cores", dd.get_num_cores(data),
"--outfile", tx_out_file, "--examples", example_dir,
"--sample", dd.get_sample_name(data), "--model", model]
do.run(cmd, "DeepVariant call_variants %s" % dd.get_sample_name(data))
return tf_out_file | [
"def",
"_call_variants",
"(",
"example_dir",
",",
"region_bed",
",",
"data",
",",
"out_file",
")",
":",
"tf_out_file",
"=",
"\"%s-tfrecord.gz\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"out_file",
")",
"[",
"0",
"]",
"if",
"not",
"utils",
".",
"file_exists... | Call variants from prepared pileup examples, creating tensorflow record file. | [
"Call",
"variants",
"from",
"prepared",
"pileup",
"examples",
"creating",
"tensorflow",
"record",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/deepvariant.py#L57-L68 | train | 218,937 |
bcbio/bcbio-nextgen | bcbio/variation/deepvariant.py | _postprocess_variants | def _postprocess_variants(record_file, data, ref_file, out_file):
"""Post-process variants, converting into standard VCF file.
"""
if not utils.file_uptodate(out_file, record_file):
with file_transaction(data, out_file) as tx_out_file:
cmd = ["dv_postprocess_variants.py", "--ref", ref_file,
"--infile", record_file, "--outfile", tx_out_file]
do.run(cmd, "DeepVariant postprocess_variants %s" % dd.get_sample_name(data))
return out_file | python | def _postprocess_variants(record_file, data, ref_file, out_file):
"""Post-process variants, converting into standard VCF file.
"""
if not utils.file_uptodate(out_file, record_file):
with file_transaction(data, out_file) as tx_out_file:
cmd = ["dv_postprocess_variants.py", "--ref", ref_file,
"--infile", record_file, "--outfile", tx_out_file]
do.run(cmd, "DeepVariant postprocess_variants %s" % dd.get_sample_name(data))
return out_file | [
"def",
"_postprocess_variants",
"(",
"record_file",
",",
"data",
",",
"ref_file",
",",
"out_file",
")",
":",
"if",
"not",
"utils",
".",
"file_uptodate",
"(",
"out_file",
",",
"record_file",
")",
":",
"with",
"file_transaction",
"(",
"data",
",",
"out_file",
... | Post-process variants, converting into standard VCF file. | [
"Post",
"-",
"process",
"variants",
"converting",
"into",
"standard",
"VCF",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/deepvariant.py#L70-L78 | train | 218,938 |
bcbio/bcbio-nextgen | bcbio/qc/qsignature.py | run | def run(bam_file, data, out_dir):
""" Run SignatureGenerator to create normalize vcf that later will be input of qsignature_summary
:param bam_file: (str) path of the bam_file
:param data: (list) list containing the all the dictionary
for this sample
:param out_dir: (str) path of the output
:returns: (string) output normalized vcf file
"""
qsig = config_utils.get_program("qsignature", data["config"])
res_qsig = config_utils.get_resources("qsignature", data["config"])
jvm_opts = " ".join(res_qsig.get("jvm_opts", ["-Xms750m", "-Xmx8g"]))
if not qsig:
logger.info("There is no qsignature tool. Skipping...")
return None
position = dd.get_qsig_file(data)
mixup_check = dd.get_mixup_check(data)
if mixup_check and mixup_check.startswith("qsignature"):
utils.safe_makedir(out_dir)
if not position:
logger.info("There is no qsignature for this species: %s"
% tz.get_in(['genome_build'], data))
return None
if mixup_check == "qsignature_full":
down_bam = bam_file
else:
down_bam = _slice_bam_chr21(bam_file, data)
position = _slice_vcf_chr21(position, out_dir)
out_name = os.path.basename(down_bam).replace("bam", "qsig.vcf")
out_file = os.path.join(out_dir, out_name)
log_file = os.path.join(out_dir, "qsig.log")
cores = dd.get_cores(data)
base_cmd = ("{qsig} {jvm_opts} "
"org.qcmg.sig.SignatureGenerator "
"--noOfThreads {cores} "
"-log {log_file} -i {position} "
"-i {down_bam} ")
if not os.path.exists(out_file):
file_qsign_out = "{0}.qsig.vcf".format(down_bam)
do.run(base_cmd.format(**locals()), "qsignature vcf generation: %s" % dd.get_sample_name(data))
if os.path.exists(file_qsign_out):
with file_transaction(data, out_file) as file_txt_out:
shutil.move(file_qsign_out, file_txt_out)
else:
raise IOError("File doesn't exist %s" % file_qsign_out)
return out_file
return None | python | def run(bam_file, data, out_dir):
""" Run SignatureGenerator to create normalize vcf that later will be input of qsignature_summary
:param bam_file: (str) path of the bam_file
:param data: (list) list containing the all the dictionary
for this sample
:param out_dir: (str) path of the output
:returns: (string) output normalized vcf file
"""
qsig = config_utils.get_program("qsignature", data["config"])
res_qsig = config_utils.get_resources("qsignature", data["config"])
jvm_opts = " ".join(res_qsig.get("jvm_opts", ["-Xms750m", "-Xmx8g"]))
if not qsig:
logger.info("There is no qsignature tool. Skipping...")
return None
position = dd.get_qsig_file(data)
mixup_check = dd.get_mixup_check(data)
if mixup_check and mixup_check.startswith("qsignature"):
utils.safe_makedir(out_dir)
if not position:
logger.info("There is no qsignature for this species: %s"
% tz.get_in(['genome_build'], data))
return None
if mixup_check == "qsignature_full":
down_bam = bam_file
else:
down_bam = _slice_bam_chr21(bam_file, data)
position = _slice_vcf_chr21(position, out_dir)
out_name = os.path.basename(down_bam).replace("bam", "qsig.vcf")
out_file = os.path.join(out_dir, out_name)
log_file = os.path.join(out_dir, "qsig.log")
cores = dd.get_cores(data)
base_cmd = ("{qsig} {jvm_opts} "
"org.qcmg.sig.SignatureGenerator "
"--noOfThreads {cores} "
"-log {log_file} -i {position} "
"-i {down_bam} ")
if not os.path.exists(out_file):
file_qsign_out = "{0}.qsig.vcf".format(down_bam)
do.run(base_cmd.format(**locals()), "qsignature vcf generation: %s" % dd.get_sample_name(data))
if os.path.exists(file_qsign_out):
with file_transaction(data, out_file) as file_txt_out:
shutil.move(file_qsign_out, file_txt_out)
else:
raise IOError("File doesn't exist %s" % file_qsign_out)
return out_file
return None | [
"def",
"run",
"(",
"bam_file",
",",
"data",
",",
"out_dir",
")",
":",
"qsig",
"=",
"config_utils",
".",
"get_program",
"(",
"\"qsignature\"",
",",
"data",
"[",
"\"config\"",
"]",
")",
"res_qsig",
"=",
"config_utils",
".",
"get_resources",
"(",
"\"qsignature\... | Run SignatureGenerator to create normalize vcf that later will be input of qsignature_summary
:param bam_file: (str) path of the bam_file
:param data: (list) list containing the all the dictionary
for this sample
:param out_dir: (str) path of the output
:returns: (string) output normalized vcf file | [
"Run",
"SignatureGenerator",
"to",
"create",
"normalize",
"vcf",
"that",
"later",
"will",
"be",
"input",
"of",
"qsignature_summary"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/qc/qsignature.py#L20-L69 | train | 218,939 |
bcbio/bcbio-nextgen | bcbio/qc/qsignature.py | summary | def summary(*samples):
"""Run SignatureCompareRelatedSimple module from qsignature tool.
Creates a matrix of pairwise comparison among samples. The
function will not run if the output exists
:param samples: list with only one element containing all samples information
:returns: (dict) with the path of the output to be joined to summary
"""
warnings, similar = [], []
qsig = config_utils.get_program("qsignature", samples[0][0]["config"])
if not qsig:
return [[]]
res_qsig = config_utils.get_resources("qsignature", samples[0][0]["config"])
jvm_opts = " ".join(res_qsig.get("jvm_opts", ["-Xms750m", "-Xmx8g"]))
work_dir = samples[0][0]["dirs"]["work"]
count = 0
for data in samples:
data = data[0]
vcf = tz.get_in(["summary", "qc", "qsignature", "base"], data)
if vcf:
count += 1
vcf_name = dd.get_sample_name(data) + ".qsig.vcf"
out_dir = utils.safe_makedir(os.path.join(work_dir, "qsignature"))
if not os.path.lexists(os.path.join(out_dir, vcf_name)):
os.symlink(vcf, os.path.join(out_dir, vcf_name))
if count > 0:
qc_out_dir = utils.safe_makedir(os.path.join(work_dir, "qc", "qsignature"))
out_file = os.path.join(qc_out_dir, "qsignature.xml")
out_ma_file = os.path.join(qc_out_dir, "qsignature.ma")
out_warn_file = os.path.join(qc_out_dir, "qsignature.warnings")
log = os.path.join(work_dir, "qsignature", "qsig-summary.log")
if not os.path.exists(out_file):
with file_transaction(samples[0][0], out_file) as file_txt_out:
base_cmd = ("{qsig} {jvm_opts} "
"org.qcmg.sig.SignatureCompareRelatedSimple "
"-log {log} -dir {out_dir} "
"-o {file_txt_out} ")
do.run(base_cmd.format(**locals()), "qsignature score calculation")
error, warnings, similar = _parse_qsignature_output(out_file, out_ma_file,
out_warn_file, samples[0][0])
return [{'total samples': count,
'similar samples pairs': len(similar),
'warnings samples pairs': len(warnings),
'error samples': list(error),
'out_dir': qc_out_dir}]
else:
return [] | python | def summary(*samples):
"""Run SignatureCompareRelatedSimple module from qsignature tool.
Creates a matrix of pairwise comparison among samples. The
function will not run if the output exists
:param samples: list with only one element containing all samples information
:returns: (dict) with the path of the output to be joined to summary
"""
warnings, similar = [], []
qsig = config_utils.get_program("qsignature", samples[0][0]["config"])
if not qsig:
return [[]]
res_qsig = config_utils.get_resources("qsignature", samples[0][0]["config"])
jvm_opts = " ".join(res_qsig.get("jvm_opts", ["-Xms750m", "-Xmx8g"]))
work_dir = samples[0][0]["dirs"]["work"]
count = 0
for data in samples:
data = data[0]
vcf = tz.get_in(["summary", "qc", "qsignature", "base"], data)
if vcf:
count += 1
vcf_name = dd.get_sample_name(data) + ".qsig.vcf"
out_dir = utils.safe_makedir(os.path.join(work_dir, "qsignature"))
if not os.path.lexists(os.path.join(out_dir, vcf_name)):
os.symlink(vcf, os.path.join(out_dir, vcf_name))
if count > 0:
qc_out_dir = utils.safe_makedir(os.path.join(work_dir, "qc", "qsignature"))
out_file = os.path.join(qc_out_dir, "qsignature.xml")
out_ma_file = os.path.join(qc_out_dir, "qsignature.ma")
out_warn_file = os.path.join(qc_out_dir, "qsignature.warnings")
log = os.path.join(work_dir, "qsignature", "qsig-summary.log")
if not os.path.exists(out_file):
with file_transaction(samples[0][0], out_file) as file_txt_out:
base_cmd = ("{qsig} {jvm_opts} "
"org.qcmg.sig.SignatureCompareRelatedSimple "
"-log {log} -dir {out_dir} "
"-o {file_txt_out} ")
do.run(base_cmd.format(**locals()), "qsignature score calculation")
error, warnings, similar = _parse_qsignature_output(out_file, out_ma_file,
out_warn_file, samples[0][0])
return [{'total samples': count,
'similar samples pairs': len(similar),
'warnings samples pairs': len(warnings),
'error samples': list(error),
'out_dir': qc_out_dir}]
else:
return [] | [
"def",
"summary",
"(",
"*",
"samples",
")",
":",
"warnings",
",",
"similar",
"=",
"[",
"]",
",",
"[",
"]",
"qsig",
"=",
"config_utils",
".",
"get_program",
"(",
"\"qsignature\"",
",",
"samples",
"[",
"0",
"]",
"[",
"0",
"]",
"[",
"\"config\"",
"]",
... | Run SignatureCompareRelatedSimple module from qsignature tool.
Creates a matrix of pairwise comparison among samples. The
function will not run if the output exists
:param samples: list with only one element containing all samples information
:returns: (dict) with the path of the output to be joined to summary | [
"Run",
"SignatureCompareRelatedSimple",
"module",
"from",
"qsignature",
"tool",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/qc/qsignature.py#L71-L118 | train | 218,940 |
bcbio/bcbio-nextgen | bcbio/qc/qsignature.py | _parse_qsignature_output | def _parse_qsignature_output(in_file, out_file, warning_file, data):
""" Parse xml file produced by qsignature
:param in_file: (str) with the path to the xml file
:param out_file: (str) with the path to output file
:param warning_file: (str) with the path to warning file
:returns: (list) with samples that could be duplicated
"""
name = {}
error, warnings, similar = set(), set(), set()
same, replicate, related = 0, 0.1, 0.18
mixup_check = dd.get_mixup_check(data)
if mixup_check == "qsignature_full":
same, replicate, related = 0, 0.01, 0.061
with open(in_file, 'r') as in_handle:
with file_transaction(data, out_file) as out_tx_file:
with file_transaction(data, warning_file) as warn_tx_file:
with open(out_tx_file, 'w') as out_handle:
with open(warn_tx_file, 'w') as warn_handle:
et = ET.parse(in_handle)
for i in list(et.iter('file')):
name[i.attrib['id']] = os.path.basename(i.attrib['name']).replace(".qsig.vcf", "")
for i in list(et.iter('comparison')):
msg = None
pair = "-".join([name[i.attrib['file1']], name[i.attrib['file2']]])
out_handle.write("%s\t%s\t%s\n" %
(name[i.attrib['file1']], name[i.attrib['file2']], i.attrib['score']))
if float(i.attrib['score']) == same:
msg = 'qsignature ERROR: read same samples:%s\n'
error.add(pair)
elif float(i.attrib['score']) < replicate:
msg = 'qsignature WARNING: read similar/replicate samples:%s\n'
warnings.add(pair)
elif float(i.attrib['score']) < related:
msg = 'qsignature NOTE: read relative samples:%s\n'
similar.add(pair)
if msg:
logger.info(msg % pair)
warn_handle.write(msg % pair)
return error, warnings, similar | python | def _parse_qsignature_output(in_file, out_file, warning_file, data):
""" Parse xml file produced by qsignature
:param in_file: (str) with the path to the xml file
:param out_file: (str) with the path to output file
:param warning_file: (str) with the path to warning file
:returns: (list) with samples that could be duplicated
"""
name = {}
error, warnings, similar = set(), set(), set()
same, replicate, related = 0, 0.1, 0.18
mixup_check = dd.get_mixup_check(data)
if mixup_check == "qsignature_full":
same, replicate, related = 0, 0.01, 0.061
with open(in_file, 'r') as in_handle:
with file_transaction(data, out_file) as out_tx_file:
with file_transaction(data, warning_file) as warn_tx_file:
with open(out_tx_file, 'w') as out_handle:
with open(warn_tx_file, 'w') as warn_handle:
et = ET.parse(in_handle)
for i in list(et.iter('file')):
name[i.attrib['id']] = os.path.basename(i.attrib['name']).replace(".qsig.vcf", "")
for i in list(et.iter('comparison')):
msg = None
pair = "-".join([name[i.attrib['file1']], name[i.attrib['file2']]])
out_handle.write("%s\t%s\t%s\n" %
(name[i.attrib['file1']], name[i.attrib['file2']], i.attrib['score']))
if float(i.attrib['score']) == same:
msg = 'qsignature ERROR: read same samples:%s\n'
error.add(pair)
elif float(i.attrib['score']) < replicate:
msg = 'qsignature WARNING: read similar/replicate samples:%s\n'
warnings.add(pair)
elif float(i.attrib['score']) < related:
msg = 'qsignature NOTE: read relative samples:%s\n'
similar.add(pair)
if msg:
logger.info(msg % pair)
warn_handle.write(msg % pair)
return error, warnings, similar | [
"def",
"_parse_qsignature_output",
"(",
"in_file",
",",
"out_file",
",",
"warning_file",
",",
"data",
")",
":",
"name",
"=",
"{",
"}",
"error",
",",
"warnings",
",",
"similar",
"=",
"set",
"(",
")",
",",
"set",
"(",
")",
",",
"set",
"(",
")",
"same",... | Parse xml file produced by qsignature
:param in_file: (str) with the path to the xml file
:param out_file: (str) with the path to output file
:param warning_file: (str) with the path to warning file
:returns: (list) with samples that could be duplicated | [
"Parse",
"xml",
"file",
"produced",
"by",
"qsignature"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/qc/qsignature.py#L125-L166 | train | 218,941 |
bcbio/bcbio-nextgen | bcbio/qc/qsignature.py | _slice_bam_chr21 | def _slice_bam_chr21(in_bam, data):
"""
return only one BAM file with only chromosome 21
"""
sambamba = config_utils.get_program("sambamba", data["config"])
out_file = "%s-chr%s" % os.path.splitext(in_bam)
if not utils.file_exists(out_file):
bam.index(in_bam, data['config'])
with pysam.Samfile(in_bam, "rb") as bamfile:
bam_contigs = [c["SN"] for c in bamfile.header["SQ"]]
chromosome = "21"
if "chr21" in bam_contigs:
chromosome = "chr21"
with file_transaction(data, out_file) as tx_out_file:
cmd = ("{sambamba} slice -o {tx_out_file} {in_bam} {chromosome}").format(**locals())
out = subprocess.check_output(cmd, shell=True)
return out_file | python | def _slice_bam_chr21(in_bam, data):
"""
return only one BAM file with only chromosome 21
"""
sambamba = config_utils.get_program("sambamba", data["config"])
out_file = "%s-chr%s" % os.path.splitext(in_bam)
if not utils.file_exists(out_file):
bam.index(in_bam, data['config'])
with pysam.Samfile(in_bam, "rb") as bamfile:
bam_contigs = [c["SN"] for c in bamfile.header["SQ"]]
chromosome = "21"
if "chr21" in bam_contigs:
chromosome = "chr21"
with file_transaction(data, out_file) as tx_out_file:
cmd = ("{sambamba} slice -o {tx_out_file} {in_bam} {chromosome}").format(**locals())
out = subprocess.check_output(cmd, shell=True)
return out_file | [
"def",
"_slice_bam_chr21",
"(",
"in_bam",
",",
"data",
")",
":",
"sambamba",
"=",
"config_utils",
".",
"get_program",
"(",
"\"sambamba\"",
",",
"data",
"[",
"\"config\"",
"]",
")",
"out_file",
"=",
"\"%s-chr%s\"",
"%",
"os",
".",
"path",
".",
"splitext",
"... | return only one BAM file with only chromosome 21 | [
"return",
"only",
"one",
"BAM",
"file",
"with",
"only",
"chromosome",
"21"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/qc/qsignature.py#L168-L184 | train | 218,942 |
bcbio/bcbio-nextgen | bcbio/qc/qsignature.py | _slice_vcf_chr21 | def _slice_vcf_chr21(vcf_file, out_dir):
"""
Slice chr21 of qsignature SNPs to reduce computation time
"""
tmp_file = os.path.join(out_dir, "chr21_qsignature.vcf")
if not utils.file_exists(tmp_file):
cmd = ("grep chr21 {vcf_file} > {tmp_file}").format(**locals())
out = subprocess.check_output(cmd, shell=True)
return tmp_file | python | def _slice_vcf_chr21(vcf_file, out_dir):
"""
Slice chr21 of qsignature SNPs to reduce computation time
"""
tmp_file = os.path.join(out_dir, "chr21_qsignature.vcf")
if not utils.file_exists(tmp_file):
cmd = ("grep chr21 {vcf_file} > {tmp_file}").format(**locals())
out = subprocess.check_output(cmd, shell=True)
return tmp_file | [
"def",
"_slice_vcf_chr21",
"(",
"vcf_file",
",",
"out_dir",
")",
":",
"tmp_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"out_dir",
",",
"\"chr21_qsignature.vcf\"",
")",
"if",
"not",
"utils",
".",
"file_exists",
"(",
"tmp_file",
")",
":",
"cmd",
"=",
... | Slice chr21 of qsignature SNPs to reduce computation time | [
"Slice",
"chr21",
"of",
"qsignature",
"SNPs",
"to",
"reduce",
"computation",
"time"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/qc/qsignature.py#L186-L194 | train | 218,943 |
bcbio/bcbio-nextgen | bcbio/variation/vcfanno.py | _combine_files | def _combine_files(orig_files, base_out_file, data, fill_paths=True):
"""Combine multiple input files, fixing file paths if needed.
We fill in full paths from files in the data dictionary if we're
not using basepath (old style GEMINI).
"""
orig_files = [x for x in orig_files if x and utils.file_exists(x)]
if not orig_files:
return None
out_file = "%s-combine%s" % (utils.splitext_plus(base_out_file)[0],
utils.splitext_plus(orig_files[0])[-1])
with open(out_file, "w") as out_handle:
for orig_file in orig_files:
with open(orig_file) as in_handle:
for line in in_handle:
if fill_paths and line.startswith("file"):
line = _fill_file_path(line, data)
out_handle.write(line)
out_handle.write("\n\n")
return out_file | python | def _combine_files(orig_files, base_out_file, data, fill_paths=True):
"""Combine multiple input files, fixing file paths if needed.
We fill in full paths from files in the data dictionary if we're
not using basepath (old style GEMINI).
"""
orig_files = [x for x in orig_files if x and utils.file_exists(x)]
if not orig_files:
return None
out_file = "%s-combine%s" % (utils.splitext_plus(base_out_file)[0],
utils.splitext_plus(orig_files[0])[-1])
with open(out_file, "w") as out_handle:
for orig_file in orig_files:
with open(orig_file) as in_handle:
for line in in_handle:
if fill_paths and line.startswith("file"):
line = _fill_file_path(line, data)
out_handle.write(line)
out_handle.write("\n\n")
return out_file | [
"def",
"_combine_files",
"(",
"orig_files",
",",
"base_out_file",
",",
"data",
",",
"fill_paths",
"=",
"True",
")",
":",
"orig_files",
"=",
"[",
"x",
"for",
"x",
"in",
"orig_files",
"if",
"x",
"and",
"utils",
".",
"file_exists",
"(",
"x",
")",
"]",
"if... | Combine multiple input files, fixing file paths if needed.
We fill in full paths from files in the data dictionary if we're
not using basepath (old style GEMINI). | [
"Combine",
"multiple",
"input",
"files",
"fixing",
"file",
"paths",
"if",
"needed",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/vcfanno.py#L47-L66 | train | 218,944 |
bcbio/bcbio-nextgen | bcbio/variation/vcfanno.py | _fill_file_path | def _fill_file_path(line, data):
"""Fill in a full file path in the configuration file from data dictionary.
"""
def _find_file(xs, target):
if isinstance(xs, dict):
for v in xs.values():
f = _find_file(v, target)
if f:
return f
elif isinstance(xs, (list, tuple)):
for x in xs:
f = _find_file(x, target)
if f:
return f
elif isinstance(xs, six.string_types) and os.path.exists(xs) and xs.endswith("/%s" % target):
return xs
orig_file = line.split("=")[-1].replace('"', '').strip()
full_file = _find_file(data, os.path.basename(orig_file))
if not full_file and os.path.exists(os.path.abspath(orig_file)):
full_file = os.path.abspath(orig_file)
assert full_file, "Did not find vcfanno input file %s" % (orig_file)
return 'file="%s"\n' % full_file | python | def _fill_file_path(line, data):
"""Fill in a full file path in the configuration file from data dictionary.
"""
def _find_file(xs, target):
if isinstance(xs, dict):
for v in xs.values():
f = _find_file(v, target)
if f:
return f
elif isinstance(xs, (list, tuple)):
for x in xs:
f = _find_file(x, target)
if f:
return f
elif isinstance(xs, six.string_types) and os.path.exists(xs) and xs.endswith("/%s" % target):
return xs
orig_file = line.split("=")[-1].replace('"', '').strip()
full_file = _find_file(data, os.path.basename(orig_file))
if not full_file and os.path.exists(os.path.abspath(orig_file)):
full_file = os.path.abspath(orig_file)
assert full_file, "Did not find vcfanno input file %s" % (orig_file)
return 'file="%s"\n' % full_file | [
"def",
"_fill_file_path",
"(",
"line",
",",
"data",
")",
":",
"def",
"_find_file",
"(",
"xs",
",",
"target",
")",
":",
"if",
"isinstance",
"(",
"xs",
",",
"dict",
")",
":",
"for",
"v",
"in",
"xs",
".",
"values",
"(",
")",
":",
"f",
"=",
"_find_fi... | Fill in a full file path in the configuration file from data dictionary. | [
"Fill",
"in",
"a",
"full",
"file",
"path",
"in",
"the",
"configuration",
"file",
"from",
"data",
"dictionary",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/vcfanno.py#L68-L89 | train | 218,945 |
bcbio/bcbio-nextgen | bcbio/variation/vcfanno.py | find_annotations | def find_annotations(data, retriever=None):
"""Find annotation configuration files for vcfanno, using pre-installed inputs.
Creates absolute paths for user specified inputs and finds locally
installed defaults.
Default annotations:
- gemini for variant pipelines
- somatic for variant tumor pipelines
- rnaedit for RNA-seq variant calling
"""
conf_files = dd.get_vcfanno(data)
if not isinstance(conf_files, (list, tuple)):
conf_files = [conf_files]
for c in _default_conf_files(data, retriever):
if c not in conf_files:
conf_files.append(c)
conf_checkers = {"gemini": annotate_gemini, "somatic": _annotate_somatic}
out = []
annodir = os.path.normpath(os.path.join(os.path.dirname(dd.get_ref_file(data)), os.pardir, "config", "vcfanno"))
if not retriever:
annodir = os.path.abspath(annodir)
for conf_file in conf_files:
if objectstore.is_remote(conf_file) or (os.path.exists(conf_file) and os.path.isfile(conf_file)):
conffn = conf_file
elif not retriever:
conffn = os.path.join(annodir, conf_file + ".conf")
else:
conffn = conf_file + ".conf"
luafn = "%s.lua" % utils.splitext_plus(conffn)[0]
if retriever:
conffn, luafn = [(x if objectstore.is_remote(x) else None)
for x in retriever.add_remotes([conffn, luafn], data["config"])]
if not conffn:
pass
elif conf_file in conf_checkers and not conf_checkers[conf_file](data, retriever):
logger.warn("Skipping vcfanno configuration: %s. Not all input files found." % conf_file)
elif not objectstore.file_exists_or_remote(conffn):
build = dd.get_genome_build(data)
CONF_NOT_FOUND = (
"The vcfanno configuration {conffn} was not found for {build}, skipping.")
logger.warn(CONF_NOT_FOUND.format(**locals()))
else:
out.append(conffn)
if luafn and objectstore.file_exists_or_remote(luafn):
out.append(luafn)
return out | python | def find_annotations(data, retriever=None):
"""Find annotation configuration files for vcfanno, using pre-installed inputs.
Creates absolute paths for user specified inputs and finds locally
installed defaults.
Default annotations:
- gemini for variant pipelines
- somatic for variant tumor pipelines
- rnaedit for RNA-seq variant calling
"""
conf_files = dd.get_vcfanno(data)
if not isinstance(conf_files, (list, tuple)):
conf_files = [conf_files]
for c in _default_conf_files(data, retriever):
if c not in conf_files:
conf_files.append(c)
conf_checkers = {"gemini": annotate_gemini, "somatic": _annotate_somatic}
out = []
annodir = os.path.normpath(os.path.join(os.path.dirname(dd.get_ref_file(data)), os.pardir, "config", "vcfanno"))
if not retriever:
annodir = os.path.abspath(annodir)
for conf_file in conf_files:
if objectstore.is_remote(conf_file) or (os.path.exists(conf_file) and os.path.isfile(conf_file)):
conffn = conf_file
elif not retriever:
conffn = os.path.join(annodir, conf_file + ".conf")
else:
conffn = conf_file + ".conf"
luafn = "%s.lua" % utils.splitext_plus(conffn)[0]
if retriever:
conffn, luafn = [(x if objectstore.is_remote(x) else None)
for x in retriever.add_remotes([conffn, luafn], data["config"])]
if not conffn:
pass
elif conf_file in conf_checkers and not conf_checkers[conf_file](data, retriever):
logger.warn("Skipping vcfanno configuration: %s. Not all input files found." % conf_file)
elif not objectstore.file_exists_or_remote(conffn):
build = dd.get_genome_build(data)
CONF_NOT_FOUND = (
"The vcfanno configuration {conffn} was not found for {build}, skipping.")
logger.warn(CONF_NOT_FOUND.format(**locals()))
else:
out.append(conffn)
if luafn and objectstore.file_exists_or_remote(luafn):
out.append(luafn)
return out | [
"def",
"find_annotations",
"(",
"data",
",",
"retriever",
"=",
"None",
")",
":",
"conf_files",
"=",
"dd",
".",
"get_vcfanno",
"(",
"data",
")",
"if",
"not",
"isinstance",
"(",
"conf_files",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"conf_files",
"... | Find annotation configuration files for vcfanno, using pre-installed inputs.
Creates absolute paths for user specified inputs and finds locally
installed defaults.
Default annotations:
- gemini for variant pipelines
- somatic for variant tumor pipelines
- rnaedit for RNA-seq variant calling | [
"Find",
"annotation",
"configuration",
"files",
"for",
"vcfanno",
"using",
"pre",
"-",
"installed",
"inputs",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/vcfanno.py#L91-L137 | train | 218,946 |
bcbio/bcbio-nextgen | bcbio/variation/vcfanno.py | annotate_gemini | def annotate_gemini(data, retriever=None):
"""Annotate with population calls if have data installed.
"""
r = dd.get_variation_resources(data)
return all([r.get(k) and objectstore.file_exists_or_remote(r[k]) for k in ["exac", "gnomad_exome"]]) | python | def annotate_gemini(data, retriever=None):
"""Annotate with population calls if have data installed.
"""
r = dd.get_variation_resources(data)
return all([r.get(k) and objectstore.file_exists_or_remote(r[k]) for k in ["exac", "gnomad_exome"]]) | [
"def",
"annotate_gemini",
"(",
"data",
",",
"retriever",
"=",
"None",
")",
":",
"r",
"=",
"dd",
".",
"get_variation_resources",
"(",
"data",
")",
"return",
"all",
"(",
"[",
"r",
".",
"get",
"(",
"k",
")",
"and",
"objectstore",
".",
"file_exists_or_remote... | Annotate with population calls if have data installed. | [
"Annotate",
"with",
"population",
"calls",
"if",
"have",
"data",
"installed",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/vcfanno.py#L150-L154 | train | 218,947 |
bcbio/bcbio-nextgen | bcbio/variation/vcfanno.py | _annotate_somatic | def _annotate_somatic(data, retriever=None):
"""Annotate somatic calls if we have cosmic data installed.
"""
if is_human(data):
paired = vcfutils.get_paired([data])
if paired:
r = dd.get_variation_resources(data)
if r.get("cosmic") and objectstore.file_exists_or_remote(r["cosmic"]):
return True
return False | python | def _annotate_somatic(data, retriever=None):
"""Annotate somatic calls if we have cosmic data installed.
"""
if is_human(data):
paired = vcfutils.get_paired([data])
if paired:
r = dd.get_variation_resources(data)
if r.get("cosmic") and objectstore.file_exists_or_remote(r["cosmic"]):
return True
return False | [
"def",
"_annotate_somatic",
"(",
"data",
",",
"retriever",
"=",
"None",
")",
":",
"if",
"is_human",
"(",
"data",
")",
":",
"paired",
"=",
"vcfutils",
".",
"get_paired",
"(",
"[",
"data",
"]",
")",
"if",
"paired",
":",
"r",
"=",
"dd",
".",
"get_variat... | Annotate somatic calls if we have cosmic data installed. | [
"Annotate",
"somatic",
"calls",
"if",
"we",
"have",
"cosmic",
"data",
"installed",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/vcfanno.py#L156-L165 | train | 218,948 |
bcbio/bcbio-nextgen | bcbio/variation/vcfanno.py | is_human | def is_human(data, builds=None):
"""Check if human, optionally with build number, search by name or extra GL contigs.
"""
def has_build37_contigs(data):
for contig in ref.file_contigs(dd.get_ref_file(data)):
if contig.name.startswith("GL") or contig.name.find("_gl") >= 0:
if contig.name in naming.GMAP["hg19"] or contig.name in naming.GMAP["GRCh37"]:
return True
return False
if not builds and tz.get_in(["genome_resources", "aliases", "human"], data):
return True
if not builds or "37" in builds:
target_builds = ["hg19", "GRCh37"]
if any([dd.get_genome_build(data).startswith(b) for b in target_builds]):
return True
elif has_build37_contigs(data):
return True
if not builds or "38" in builds:
target_builds = ["hg38"]
if any([dd.get_genome_build(data).startswith(b) for b in target_builds]):
return True
return False | python | def is_human(data, builds=None):
"""Check if human, optionally with build number, search by name or extra GL contigs.
"""
def has_build37_contigs(data):
for contig in ref.file_contigs(dd.get_ref_file(data)):
if contig.name.startswith("GL") or contig.name.find("_gl") >= 0:
if contig.name in naming.GMAP["hg19"] or contig.name in naming.GMAP["GRCh37"]:
return True
return False
if not builds and tz.get_in(["genome_resources", "aliases", "human"], data):
return True
if not builds or "37" in builds:
target_builds = ["hg19", "GRCh37"]
if any([dd.get_genome_build(data).startswith(b) for b in target_builds]):
return True
elif has_build37_contigs(data):
return True
if not builds or "38" in builds:
target_builds = ["hg38"]
if any([dd.get_genome_build(data).startswith(b) for b in target_builds]):
return True
return False | [
"def",
"is_human",
"(",
"data",
",",
"builds",
"=",
"None",
")",
":",
"def",
"has_build37_contigs",
"(",
"data",
")",
":",
"for",
"contig",
"in",
"ref",
".",
"file_contigs",
"(",
"dd",
".",
"get_ref_file",
"(",
"data",
")",
")",
":",
"if",
"contig",
... | Check if human, optionally with build number, search by name or extra GL contigs. | [
"Check",
"if",
"human",
"optionally",
"with",
"build",
"number",
"search",
"by",
"name",
"or",
"extra",
"GL",
"contigs",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/vcfanno.py#L167-L188 | train | 218,949 |
bcbio/bcbio-nextgen | bcbio/distributed/resources.py | _get_resource_programs | def _get_resource_programs(progs, algs):
"""Retrieve programs used in analysis based on algorithm configurations.
Handles special cases like aligners and variant callers.
"""
checks = {"gatk-vqsr": config_utils.use_vqsr,
"snpeff": config_utils.use_snpeff,
"bcbio-variation-recall": config_utils.use_bcbio_variation_recall}
parent_child = {"vardict": _parent_prefix("vardict")}
out = set([])
for p in progs:
if p == "aligner":
for alg in algs:
aligner = alg.get("aligner")
if aligner and not isinstance(aligner, bool):
out.add(aligner)
elif p in ["variantcaller", "svcaller", "peakcaller"]:
if p == "variantcaller":
for key, fn in parent_child.items():
if fn(algs):
out.add(key)
for alg in algs:
callers = alg.get(p)
if callers and not isinstance(callers, bool):
if isinstance(callers, dict):
callers = reduce(operator.add, callers.values())
if isinstance(callers, (list, tuple)):
for x in callers:
out.add(x)
else:
out.add(callers)
elif p in checks:
if checks[p](algs):
out.add(p)
else:
out.add(p)
return sorted(list(out)) | python | def _get_resource_programs(progs, algs):
"""Retrieve programs used in analysis based on algorithm configurations.
Handles special cases like aligners and variant callers.
"""
checks = {"gatk-vqsr": config_utils.use_vqsr,
"snpeff": config_utils.use_snpeff,
"bcbio-variation-recall": config_utils.use_bcbio_variation_recall}
parent_child = {"vardict": _parent_prefix("vardict")}
out = set([])
for p in progs:
if p == "aligner":
for alg in algs:
aligner = alg.get("aligner")
if aligner and not isinstance(aligner, bool):
out.add(aligner)
elif p in ["variantcaller", "svcaller", "peakcaller"]:
if p == "variantcaller":
for key, fn in parent_child.items():
if fn(algs):
out.add(key)
for alg in algs:
callers = alg.get(p)
if callers and not isinstance(callers, bool):
if isinstance(callers, dict):
callers = reduce(operator.add, callers.values())
if isinstance(callers, (list, tuple)):
for x in callers:
out.add(x)
else:
out.add(callers)
elif p in checks:
if checks[p](algs):
out.add(p)
else:
out.add(p)
return sorted(list(out)) | [
"def",
"_get_resource_programs",
"(",
"progs",
",",
"algs",
")",
":",
"checks",
"=",
"{",
"\"gatk-vqsr\"",
":",
"config_utils",
".",
"use_vqsr",
",",
"\"snpeff\"",
":",
"config_utils",
".",
"use_snpeff",
",",
"\"bcbio-variation-recall\"",
":",
"config_utils",
".",... | Retrieve programs used in analysis based on algorithm configurations.
Handles special cases like aligners and variant callers. | [
"Retrieve",
"programs",
"used",
"in",
"analysis",
"based",
"on",
"algorithm",
"configurations",
".",
"Handles",
"special",
"cases",
"like",
"aligners",
"and",
"variant",
"callers",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/resources.py#L14-L49 | train | 218,950 |
bcbio/bcbio-nextgen | bcbio/distributed/resources.py | _parent_prefix | def _parent_prefix(prefix):
"""Identify a parent prefix we should add to resources if present in a caller name.
"""
def run(algs):
for alg in algs:
vcs = alg.get("variantcaller")
if vcs:
if isinstance(vcs, dict):
vcs = reduce(operator.add, vcs.values())
if not isinstance(vcs, (list, tuple)):
vcs = [vcs]
return any(vc.startswith(prefix) for vc in vcs if vc)
return run | python | def _parent_prefix(prefix):
"""Identify a parent prefix we should add to resources if present in a caller name.
"""
def run(algs):
for alg in algs:
vcs = alg.get("variantcaller")
if vcs:
if isinstance(vcs, dict):
vcs = reduce(operator.add, vcs.values())
if not isinstance(vcs, (list, tuple)):
vcs = [vcs]
return any(vc.startswith(prefix) for vc in vcs if vc)
return run | [
"def",
"_parent_prefix",
"(",
"prefix",
")",
":",
"def",
"run",
"(",
"algs",
")",
":",
"for",
"alg",
"in",
"algs",
":",
"vcs",
"=",
"alg",
".",
"get",
"(",
"\"variantcaller\"",
")",
"if",
"vcs",
":",
"if",
"isinstance",
"(",
"vcs",
",",
"dict",
")"... | Identify a parent prefix we should add to resources if present in a caller name. | [
"Identify",
"a",
"parent",
"prefix",
"we",
"should",
"add",
"to",
"resources",
"if",
"present",
"in",
"a",
"caller",
"name",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/resources.py#L51-L63 | train | 218,951 |
bcbio/bcbio-nextgen | bcbio/distributed/resources.py | _ensure_min_resources | def _ensure_min_resources(progs, cores, memory, min_memory):
"""Ensure setting match minimum resources required for used programs.
"""
for p in progs:
if p in min_memory:
if not memory or cores * memory < min_memory[p]:
memory = float(min_memory[p]) / cores
return cores, memory | python | def _ensure_min_resources(progs, cores, memory, min_memory):
"""Ensure setting match minimum resources required for used programs.
"""
for p in progs:
if p in min_memory:
if not memory or cores * memory < min_memory[p]:
memory = float(min_memory[p]) / cores
return cores, memory | [
"def",
"_ensure_min_resources",
"(",
"progs",
",",
"cores",
",",
"memory",
",",
"min_memory",
")",
":",
"for",
"p",
"in",
"progs",
":",
"if",
"p",
"in",
"min_memory",
":",
"if",
"not",
"memory",
"or",
"cores",
"*",
"memory",
"<",
"min_memory",
"[",
"p"... | Ensure setting match minimum resources required for used programs. | [
"Ensure",
"setting",
"match",
"minimum",
"resources",
"required",
"for",
"used",
"programs",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/resources.py#L65-L72 | train | 218,952 |
bcbio/bcbio-nextgen | bcbio/distributed/resources.py | _get_prog_memory | def _get_prog_memory(resources, cores_per_job):
"""Get expected memory usage, in Gb per core, for a program from resource specification.
"""
out = None
for jvm_opt in resources.get("jvm_opts", []):
if jvm_opt.startswith("-Xmx"):
out = _str_memory_to_gb(jvm_opt[4:])
memory = resources.get("memory")
if memory:
out = _str_memory_to_gb(memory)
prog_cores = resources.get("cores")
# if a single core with memory is requested for the job
# and we run multiple cores, scale down to avoid overscheduling
if out and prog_cores and int(prog_cores) == 1 and cores_per_job > int(prog_cores):
out = out / float(cores_per_job)
return out | python | def _get_prog_memory(resources, cores_per_job):
"""Get expected memory usage, in Gb per core, for a program from resource specification.
"""
out = None
for jvm_opt in resources.get("jvm_opts", []):
if jvm_opt.startswith("-Xmx"):
out = _str_memory_to_gb(jvm_opt[4:])
memory = resources.get("memory")
if memory:
out = _str_memory_to_gb(memory)
prog_cores = resources.get("cores")
# if a single core with memory is requested for the job
# and we run multiple cores, scale down to avoid overscheduling
if out and prog_cores and int(prog_cores) == 1 and cores_per_job > int(prog_cores):
out = out / float(cores_per_job)
return out | [
"def",
"_get_prog_memory",
"(",
"resources",
",",
"cores_per_job",
")",
":",
"out",
"=",
"None",
"for",
"jvm_opt",
"in",
"resources",
".",
"get",
"(",
"\"jvm_opts\"",
",",
"[",
"]",
")",
":",
"if",
"jvm_opt",
".",
"startswith",
"(",
"\"-Xmx\"",
")",
":",... | Get expected memory usage, in Gb per core, for a program from resource specification. | [
"Get",
"expected",
"memory",
"usage",
"in",
"Gb",
"per",
"core",
"for",
"a",
"program",
"from",
"resource",
"specification",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/resources.py#L83-L98 | train | 218,953 |
bcbio/bcbio-nextgen | bcbio/distributed/resources.py | _scale_cores_to_memory | def _scale_cores_to_memory(cores, mem_per_core, sysinfo, system_memory):
"""Scale multicore usage to avoid excessive memory usage based on system information.
"""
total_mem = "%.2f" % (cores * mem_per_core + system_memory)
if "cores" not in sysinfo:
return cores, total_mem, 1.0
total_mem = min(float(total_mem), float(sysinfo["memory"]) - system_memory)
cores = min(cores, int(sysinfo["cores"]))
mem_cores = int(math.floor(float(total_mem) / mem_per_core)) # cores based on available memory
if mem_cores < 1:
out_cores = 1
elif mem_cores < cores:
out_cores = mem_cores
else:
out_cores = cores
mem_pct = float(out_cores) / float(cores)
return out_cores, total_mem, mem_pct | python | def _scale_cores_to_memory(cores, mem_per_core, sysinfo, system_memory):
"""Scale multicore usage to avoid excessive memory usage based on system information.
"""
total_mem = "%.2f" % (cores * mem_per_core + system_memory)
if "cores" not in sysinfo:
return cores, total_mem, 1.0
total_mem = min(float(total_mem), float(sysinfo["memory"]) - system_memory)
cores = min(cores, int(sysinfo["cores"]))
mem_cores = int(math.floor(float(total_mem) / mem_per_core)) # cores based on available memory
if mem_cores < 1:
out_cores = 1
elif mem_cores < cores:
out_cores = mem_cores
else:
out_cores = cores
mem_pct = float(out_cores) / float(cores)
return out_cores, total_mem, mem_pct | [
"def",
"_scale_cores_to_memory",
"(",
"cores",
",",
"mem_per_core",
",",
"sysinfo",
",",
"system_memory",
")",
":",
"total_mem",
"=",
"\"%.2f\"",
"%",
"(",
"cores",
"*",
"mem_per_core",
"+",
"system_memory",
")",
"if",
"\"cores\"",
"not",
"in",
"sysinfo",
":",... | Scale multicore usage to avoid excessive memory usage based on system information. | [
"Scale",
"multicore",
"usage",
"to",
"avoid",
"excessive",
"memory",
"usage",
"based",
"on",
"system",
"information",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/resources.py#L100-L117 | train | 218,954 |
bcbio/bcbio-nextgen | bcbio/distributed/resources.py | _scale_jobs_to_memory | def _scale_jobs_to_memory(jobs, mem_per_core, sysinfo):
"""When scheduling jobs with single cores, avoid overscheduling due to memory.
"""
if "cores" not in sysinfo:
return jobs, 1.0
sys_mem_per_core = float(sysinfo["memory"]) / float(sysinfo["cores"])
if sys_mem_per_core < mem_per_core:
pct = sys_mem_per_core / float(mem_per_core)
target_jobs = int(math.floor(jobs * pct))
return max(target_jobs, 1), pct
else:
return jobs, 1.0 | python | def _scale_jobs_to_memory(jobs, mem_per_core, sysinfo):
"""When scheduling jobs with single cores, avoid overscheduling due to memory.
"""
if "cores" not in sysinfo:
return jobs, 1.0
sys_mem_per_core = float(sysinfo["memory"]) / float(sysinfo["cores"])
if sys_mem_per_core < mem_per_core:
pct = sys_mem_per_core / float(mem_per_core)
target_jobs = int(math.floor(jobs * pct))
return max(target_jobs, 1), pct
else:
return jobs, 1.0 | [
"def",
"_scale_jobs_to_memory",
"(",
"jobs",
",",
"mem_per_core",
",",
"sysinfo",
")",
":",
"if",
"\"cores\"",
"not",
"in",
"sysinfo",
":",
"return",
"jobs",
",",
"1.0",
"sys_mem_per_core",
"=",
"float",
"(",
"sysinfo",
"[",
"\"memory\"",
"]",
")",
"/",
"f... | When scheduling jobs with single cores, avoid overscheduling due to memory. | [
"When",
"scheduling",
"jobs",
"with",
"single",
"cores",
"avoid",
"overscheduling",
"due",
"to",
"memory",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/resources.py#L119-L130 | train | 218,955 |
bcbio/bcbio-nextgen | bcbio/distributed/resources.py | calculate | def calculate(parallel, items, sysinfo, config, multiplier=1,
max_multicore=None):
"""Determine cores and workers to use for this stage based on used programs.
multiplier specifies the number of regions items will be split into during
processing.
max_multicore specifies an optional limit on the maximum cores. Can use to
force single core processing during specific tasks.
sysinfo specifies cores and memory on processing nodes, allowing us to tailor
jobs for available resources.
"""
assert len(items) > 0, "Finding job resources but no items to process"
all_cores = []
all_memory = []
# Provide 100Mb of additional memory for the system
system_memory = 0.10
algs = [config_utils.get_algorithm_config(x) for x in items]
progs = _get_resource_programs(parallel.get("progs", []), algs)
# Calculate cores
for prog in progs:
resources = config_utils.get_resources(prog, config)
all_cores.append(resources.get("cores", 1))
if len(all_cores) == 0:
all_cores.append(1)
cores_per_job = max(all_cores)
if max_multicore:
cores_per_job = min(cores_per_job, max_multicore)
if "cores" in sysinfo:
cores_per_job = min(cores_per_job, int(sysinfo["cores"]))
total = parallel["cores"]
if total > cores_per_job:
num_jobs = total // cores_per_job
else:
num_jobs, cores_per_job = 1, total
# Calculate memory. Use 1Gb memory usage per core as min baseline if not specified
for prog in progs:
resources = config_utils.get_resources(prog, config)
memory = _get_prog_memory(resources, cores_per_job)
if memory:
all_memory.append(memory)
if len(all_memory) == 0:
all_memory.append(1)
memory_per_core = max(all_memory)
logger.debug("Resource requests: {progs}; memory: {memory}; cores: {cores}".format(
progs=", ".join(progs), memory=", ".join("%.2f" % x for x in all_memory),
cores=", ".join(str(x) for x in all_cores)))
cores_per_job, memory_per_core = _ensure_min_resources(progs, cores_per_job, memory_per_core,
min_memory=parallel.get("ensure_mem", {}))
if cores_per_job == 1:
memory_per_job = "%.2f" % memory_per_core
num_jobs, mem_pct = _scale_jobs_to_memory(num_jobs, memory_per_core, sysinfo)
# For single core jobs, avoid overscheduling maximum cores_per_job
num_jobs = min(num_jobs, total)
else:
cores_per_job, memory_per_job, mem_pct = _scale_cores_to_memory(cores_per_job,
memory_per_core, sysinfo,
system_memory)
# For local runs with multiple jobs and multiple cores, potentially scale jobs down
if num_jobs > 1 and parallel.get("type") == "local":
memory_per_core = float(memory_per_job) / cores_per_job
num_jobs, _ = _scale_jobs_to_memory(num_jobs, memory_per_core, sysinfo)
# do not overschedule if we don't have extra items to process
num_jobs = int(min(num_jobs, len(items) * multiplier))
logger.debug("Configuring %d jobs to run, using %d cores each with %sg of "
"memory reserved for each job" % (num_jobs, cores_per_job,
str(memory_per_job)))
parallel = copy.deepcopy(parallel)
parallel["cores_per_job"] = cores_per_job
parallel["num_jobs"] = num_jobs
parallel["mem"] = str(memory_per_job)
parallel["mem_pct"] = "%.2f" % mem_pct
parallel["system_cores"] = sysinfo.get("cores", 1)
return parallel | python | def calculate(parallel, items, sysinfo, config, multiplier=1,
max_multicore=None):
"""Determine cores and workers to use for this stage based on used programs.
multiplier specifies the number of regions items will be split into during
processing.
max_multicore specifies an optional limit on the maximum cores. Can use to
force single core processing during specific tasks.
sysinfo specifies cores and memory on processing nodes, allowing us to tailor
jobs for available resources.
"""
assert len(items) > 0, "Finding job resources but no items to process"
all_cores = []
all_memory = []
# Provide 100Mb of additional memory for the system
system_memory = 0.10
algs = [config_utils.get_algorithm_config(x) for x in items]
progs = _get_resource_programs(parallel.get("progs", []), algs)
# Calculate cores
for prog in progs:
resources = config_utils.get_resources(prog, config)
all_cores.append(resources.get("cores", 1))
if len(all_cores) == 0:
all_cores.append(1)
cores_per_job = max(all_cores)
if max_multicore:
cores_per_job = min(cores_per_job, max_multicore)
if "cores" in sysinfo:
cores_per_job = min(cores_per_job, int(sysinfo["cores"]))
total = parallel["cores"]
if total > cores_per_job:
num_jobs = total // cores_per_job
else:
num_jobs, cores_per_job = 1, total
# Calculate memory. Use 1Gb memory usage per core as min baseline if not specified
for prog in progs:
resources = config_utils.get_resources(prog, config)
memory = _get_prog_memory(resources, cores_per_job)
if memory:
all_memory.append(memory)
if len(all_memory) == 0:
all_memory.append(1)
memory_per_core = max(all_memory)
logger.debug("Resource requests: {progs}; memory: {memory}; cores: {cores}".format(
progs=", ".join(progs), memory=", ".join("%.2f" % x for x in all_memory),
cores=", ".join(str(x) for x in all_cores)))
cores_per_job, memory_per_core = _ensure_min_resources(progs, cores_per_job, memory_per_core,
min_memory=parallel.get("ensure_mem", {}))
if cores_per_job == 1:
memory_per_job = "%.2f" % memory_per_core
num_jobs, mem_pct = _scale_jobs_to_memory(num_jobs, memory_per_core, sysinfo)
# For single core jobs, avoid overscheduling maximum cores_per_job
num_jobs = min(num_jobs, total)
else:
cores_per_job, memory_per_job, mem_pct = _scale_cores_to_memory(cores_per_job,
memory_per_core, sysinfo,
system_memory)
# For local runs with multiple jobs and multiple cores, potentially scale jobs down
if num_jobs > 1 and parallel.get("type") == "local":
memory_per_core = float(memory_per_job) / cores_per_job
num_jobs, _ = _scale_jobs_to_memory(num_jobs, memory_per_core, sysinfo)
# do not overschedule if we don't have extra items to process
num_jobs = int(min(num_jobs, len(items) * multiplier))
logger.debug("Configuring %d jobs to run, using %d cores each with %sg of "
"memory reserved for each job" % (num_jobs, cores_per_job,
str(memory_per_job)))
parallel = copy.deepcopy(parallel)
parallel["cores_per_job"] = cores_per_job
parallel["num_jobs"] = num_jobs
parallel["mem"] = str(memory_per_job)
parallel["mem_pct"] = "%.2f" % mem_pct
parallel["system_cores"] = sysinfo.get("cores", 1)
return parallel | [
"def",
"calculate",
"(",
"parallel",
",",
"items",
",",
"sysinfo",
",",
"config",
",",
"multiplier",
"=",
"1",
",",
"max_multicore",
"=",
"None",
")",
":",
"assert",
"len",
"(",
"items",
")",
">",
"0",
",",
"\"Finding job resources but no items to process\"",
... | Determine cores and workers to use for this stage based on used programs.
multiplier specifies the number of regions items will be split into during
processing.
max_multicore specifies an optional limit on the maximum cores. Can use to
force single core processing during specific tasks.
sysinfo specifies cores and memory on processing nodes, allowing us to tailor
jobs for available resources. | [
"Determine",
"cores",
"and",
"workers",
"to",
"use",
"for",
"this",
"stage",
"based",
"on",
"used",
"programs",
".",
"multiplier",
"specifies",
"the",
"number",
"of",
"regions",
"items",
"will",
"be",
"split",
"into",
"during",
"processing",
".",
"max_multicor... | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/resources.py#L159-L234 | train | 218,956 |
bcbio/bcbio-nextgen | bcbio/ngsalign/hisat2.py | create_splicesites_file | def create_splicesites_file(gtf_file, align_dir, data):
"""
if not pre-created, make a splicesites file to use with hisat2
"""
out_file = os.path.join(align_dir, "ref-transcripts-splicesites.txt")
if file_exists(out_file):
return out_file
safe_makedir(align_dir)
hisat2_ss = config_utils.get_program("hisat2_extract_splice_sites.py", data)
cmd = "{hisat2_ss} {gtf_file} > {tx_out_file}"
message = "Creating hisat2 splicesites file from %s." % gtf_file
with file_transaction(out_file) as tx_out_file:
do.run(cmd.format(**locals()), message)
return out_file | python | def create_splicesites_file(gtf_file, align_dir, data):
"""
if not pre-created, make a splicesites file to use with hisat2
"""
out_file = os.path.join(align_dir, "ref-transcripts-splicesites.txt")
if file_exists(out_file):
return out_file
safe_makedir(align_dir)
hisat2_ss = config_utils.get_program("hisat2_extract_splice_sites.py", data)
cmd = "{hisat2_ss} {gtf_file} > {tx_out_file}"
message = "Creating hisat2 splicesites file from %s." % gtf_file
with file_transaction(out_file) as tx_out_file:
do.run(cmd.format(**locals()), message)
return out_file | [
"def",
"create_splicesites_file",
"(",
"gtf_file",
",",
"align_dir",
",",
"data",
")",
":",
"out_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"align_dir",
",",
"\"ref-transcripts-splicesites.txt\"",
")",
"if",
"file_exists",
"(",
"out_file",
")",
":",
"ret... | if not pre-created, make a splicesites file to use with hisat2 | [
"if",
"not",
"pre",
"-",
"created",
"make",
"a",
"splicesites",
"file",
"to",
"use",
"with",
"hisat2"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/hisat2.py#L63-L76 | train | 218,957 |
bcbio/bcbio-nextgen | bcbio/ngsalign/hisat2.py | get_splicejunction_file | def get_splicejunction_file(align_dir, data):
"""
locate the splice junction file from hisat2. hisat2 outputs a novel
splicesites file to go along with the provided file, if available.
this combines the two together and outputs a combined file of all
of the known and novel splice junctions
"""
samplename = dd.get_sample_name(data)
align_dir = os.path.dirname(dd.get_work_bam(data))
knownfile = get_known_splicesites_file(align_dir, data)
novelfile = os.path.join(align_dir, "%s-novelsplicesites.bed" % samplename)
bed_files = [x for x in [knownfile, novelfile] if file_exists(x)]
splicejunction = bed.concat(bed_files)
splicejunctionfile = os.path.join(align_dir,
"%s-splicejunctions.bed" % samplename)
if splicejunction:
splicejunction.saveas(splicejunctionfile)
return splicejunctionfile
else:
return None | python | def get_splicejunction_file(align_dir, data):
"""
locate the splice junction file from hisat2. hisat2 outputs a novel
splicesites file to go along with the provided file, if available.
this combines the two together and outputs a combined file of all
of the known and novel splice junctions
"""
samplename = dd.get_sample_name(data)
align_dir = os.path.dirname(dd.get_work_bam(data))
knownfile = get_known_splicesites_file(align_dir, data)
novelfile = os.path.join(align_dir, "%s-novelsplicesites.bed" % samplename)
bed_files = [x for x in [knownfile, novelfile] if file_exists(x)]
splicejunction = bed.concat(bed_files)
splicejunctionfile = os.path.join(align_dir,
"%s-splicejunctions.bed" % samplename)
if splicejunction:
splicejunction.saveas(splicejunctionfile)
return splicejunctionfile
else:
return None | [
"def",
"get_splicejunction_file",
"(",
"align_dir",
",",
"data",
")",
":",
"samplename",
"=",
"dd",
".",
"get_sample_name",
"(",
"data",
")",
"align_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"dd",
".",
"get_work_bam",
"(",
"data",
")",
")",
"kno... | locate the splice junction file from hisat2. hisat2 outputs a novel
splicesites file to go along with the provided file, if available.
this combines the two together and outputs a combined file of all
of the known and novel splice junctions | [
"locate",
"the",
"splice",
"junction",
"file",
"from",
"hisat2",
".",
"hisat2",
"outputs",
"a",
"novel",
"splicesites",
"file",
"to",
"go",
"along",
"with",
"the",
"provided",
"file",
"if",
"available",
".",
"this",
"combines",
"the",
"two",
"together",
"and... | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/hisat2.py#L127-L146 | train | 218,958 |
bcbio/bcbio-nextgen | bcbio/provenance/system.py | write_info | def write_info(dirs, parallel, config):
"""Write cluster or local filesystem resources, spinning up cluster if not present.
"""
if parallel["type"] in ["ipython"] and not parallel.get("run_local"):
out_file = _get_cache_file(dirs, parallel)
if not utils.file_exists(out_file):
sys_config = copy.deepcopy(config)
minfos = _get_machine_info(parallel, sys_config, dirs, config)
with open(out_file, "w") as out_handle:
yaml.safe_dump(minfos, out_handle, default_flow_style=False, allow_unicode=False) | python | def write_info(dirs, parallel, config):
"""Write cluster or local filesystem resources, spinning up cluster if not present.
"""
if parallel["type"] in ["ipython"] and not parallel.get("run_local"):
out_file = _get_cache_file(dirs, parallel)
if not utils.file_exists(out_file):
sys_config = copy.deepcopy(config)
minfos = _get_machine_info(parallel, sys_config, dirs, config)
with open(out_file, "w") as out_handle:
yaml.safe_dump(minfos, out_handle, default_flow_style=False, allow_unicode=False) | [
"def",
"write_info",
"(",
"dirs",
",",
"parallel",
",",
"config",
")",
":",
"if",
"parallel",
"[",
"\"type\"",
"]",
"in",
"[",
"\"ipython\"",
"]",
"and",
"not",
"parallel",
".",
"get",
"(",
"\"run_local\"",
")",
":",
"out_file",
"=",
"_get_cache_file",
"... | Write cluster or local filesystem resources, spinning up cluster if not present. | [
"Write",
"cluster",
"or",
"local",
"filesystem",
"resources",
"spinning",
"up",
"cluster",
"if",
"not",
"present",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/system.py#L25-L34 | train | 218,959 |
bcbio/bcbio-nextgen | bcbio/provenance/system.py | _get_machine_info | def _get_machine_info(parallel, sys_config, dirs, config):
"""Get machine resource information from the job scheduler via either the command line or the queue.
"""
if parallel.get("queue") and parallel.get("scheduler"):
# dictionary as switch statement; can add new scheduler implementation functions as (lowercase) keys
sched_info_dict = {
"slurm": _slurm_info,
"torque": _torque_info,
"sge": _sge_info
}
if parallel["scheduler"].lower() in sched_info_dict:
try:
return sched_info_dict[parallel["scheduler"].lower()](parallel.get("queue", ""))
except:
# If something goes wrong, just hit the queue
logger.exception("Couldn't get machine information from resource query function for queue "
"'{0}' on scheduler \"{1}\"; "
"submitting job to queue".format(parallel.get("queue", ""), parallel["scheduler"]))
else:
logger.info("Resource query function not implemented for scheduler \"{0}\"; "
"submitting job to queue".format(parallel["scheduler"]))
from bcbio.distributed import prun
with prun.start(parallel, [[sys_config]], config, dirs) as run_parallel:
return run_parallel("machine_info", [[sys_config]]) | python | def _get_machine_info(parallel, sys_config, dirs, config):
"""Get machine resource information from the job scheduler via either the command line or the queue.
"""
if parallel.get("queue") and parallel.get("scheduler"):
# dictionary as switch statement; can add new scheduler implementation functions as (lowercase) keys
sched_info_dict = {
"slurm": _slurm_info,
"torque": _torque_info,
"sge": _sge_info
}
if parallel["scheduler"].lower() in sched_info_dict:
try:
return sched_info_dict[parallel["scheduler"].lower()](parallel.get("queue", ""))
except:
# If something goes wrong, just hit the queue
logger.exception("Couldn't get machine information from resource query function for queue "
"'{0}' on scheduler \"{1}\"; "
"submitting job to queue".format(parallel.get("queue", ""), parallel["scheduler"]))
else:
logger.info("Resource query function not implemented for scheduler \"{0}\"; "
"submitting job to queue".format(parallel["scheduler"]))
from bcbio.distributed import prun
with prun.start(parallel, [[sys_config]], config, dirs) as run_parallel:
return run_parallel("machine_info", [[sys_config]]) | [
"def",
"_get_machine_info",
"(",
"parallel",
",",
"sys_config",
",",
"dirs",
",",
"config",
")",
":",
"if",
"parallel",
".",
"get",
"(",
"\"queue\"",
")",
"and",
"parallel",
".",
"get",
"(",
"\"scheduler\"",
")",
":",
"# dictionary as switch statement; can add n... | Get machine resource information from the job scheduler via either the command line or the queue. | [
"Get",
"machine",
"resource",
"information",
"from",
"the",
"job",
"scheduler",
"via",
"either",
"the",
"command",
"line",
"or",
"the",
"queue",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/system.py#L36-L59 | train | 218,960 |
bcbio/bcbio-nextgen | bcbio/provenance/system.py | _slurm_info | def _slurm_info(queue):
"""Returns machine information for a slurm job scheduler.
"""
cl = "sinfo -h -p {} --format '%c %m %D'".format(queue)
num_cpus, mem, num_nodes = subprocess.check_output(shlex.split(cl)).decode().split()
# if the queue contains multiple memory configurations, the minimum value is printed with a trailing '+'
mem = float(mem.replace('+', ''))
num_cpus = int(num_cpus.replace('+', ''))
# handle small clusters where we need to allocate memory for bcbio and the controller
# This will typically be on cloud AWS machines
bcbio_mem = 2000
controller_mem = 4000
if int(num_nodes) < 3 and mem > (bcbio_mem + controller_mem) * 2:
mem = mem - bcbio_mem - controller_mem
return [{"cores": int(num_cpus), "memory": mem / 1024.0, "name": "slurm_machine"}] | python | def _slurm_info(queue):
"""Returns machine information for a slurm job scheduler.
"""
cl = "sinfo -h -p {} --format '%c %m %D'".format(queue)
num_cpus, mem, num_nodes = subprocess.check_output(shlex.split(cl)).decode().split()
# if the queue contains multiple memory configurations, the minimum value is printed with a trailing '+'
mem = float(mem.replace('+', ''))
num_cpus = int(num_cpus.replace('+', ''))
# handle small clusters where we need to allocate memory for bcbio and the controller
# This will typically be on cloud AWS machines
bcbio_mem = 2000
controller_mem = 4000
if int(num_nodes) < 3 and mem > (bcbio_mem + controller_mem) * 2:
mem = mem - bcbio_mem - controller_mem
return [{"cores": int(num_cpus), "memory": mem / 1024.0, "name": "slurm_machine"}] | [
"def",
"_slurm_info",
"(",
"queue",
")",
":",
"cl",
"=",
"\"sinfo -h -p {} --format '%c %m %D'\"",
".",
"format",
"(",
"queue",
")",
"num_cpus",
",",
"mem",
",",
"num_nodes",
"=",
"subprocess",
".",
"check_output",
"(",
"shlex",
".",
"split",
"(",
"cl",
")",... | Returns machine information for a slurm job scheduler. | [
"Returns",
"machine",
"information",
"for",
"a",
"slurm",
"job",
"scheduler",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/system.py#L61-L75 | train | 218,961 |
bcbio/bcbio-nextgen | bcbio/provenance/system.py | _torque_info | def _torque_info(queue):
"""Return machine information for a torque job scheduler using pbsnodes.
To identify which host to use it tries to parse available hosts
from qstat -Qf `acl_hosts`. If found, it uses these and gets the
first node from pbsnodes matching to the list. If no attached
hosts are available, it uses the first host found from pbsnodes.
"""
nodes = _torque_queue_nodes(queue)
pbs_out = subprocess.check_output(["pbsnodes"]).decode()
info = {}
for i, line in enumerate(pbs_out.split("\n")):
if i == 0 and len(nodes) == 0:
info["name"] = line.strip()
elif line.startswith(nodes):
info["name"] = line.strip()
elif info.get("name"):
if line.strip().startswith("np = "):
info["cores"] = int(line.replace("np = ", "").strip())
elif line.strip().startswith("status = "):
mem = [x for x in pbs_out.split(",") if x.startswith("physmem=")][0]
info["memory"] = float(mem.split("=")[1].rstrip("kb")) / 1048576.0
return [info] | python | def _torque_info(queue):
"""Return machine information for a torque job scheduler using pbsnodes.
To identify which host to use it tries to parse available hosts
from qstat -Qf `acl_hosts`. If found, it uses these and gets the
first node from pbsnodes matching to the list. If no attached
hosts are available, it uses the first host found from pbsnodes.
"""
nodes = _torque_queue_nodes(queue)
pbs_out = subprocess.check_output(["pbsnodes"]).decode()
info = {}
for i, line in enumerate(pbs_out.split("\n")):
if i == 0 and len(nodes) == 0:
info["name"] = line.strip()
elif line.startswith(nodes):
info["name"] = line.strip()
elif info.get("name"):
if line.strip().startswith("np = "):
info["cores"] = int(line.replace("np = ", "").strip())
elif line.strip().startswith("status = "):
mem = [x for x in pbs_out.split(",") if x.startswith("physmem=")][0]
info["memory"] = float(mem.split("=")[1].rstrip("kb")) / 1048576.0
return [info] | [
"def",
"_torque_info",
"(",
"queue",
")",
":",
"nodes",
"=",
"_torque_queue_nodes",
"(",
"queue",
")",
"pbs_out",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"\"pbsnodes\"",
"]",
")",
".",
"decode",
"(",
")",
"info",
"=",
"{",
"}",
"for",
"i",
",... | Return machine information for a torque job scheduler using pbsnodes.
To identify which host to use it tries to parse available hosts
from qstat -Qf `acl_hosts`. If found, it uses these and gets the
first node from pbsnodes matching to the list. If no attached
hosts are available, it uses the first host found from pbsnodes. | [
"Return",
"machine",
"information",
"for",
"a",
"torque",
"job",
"scheduler",
"using",
"pbsnodes",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/system.py#L77-L99 | train | 218,962 |
bcbio/bcbio-nextgen | bcbio/provenance/system.py | _torque_queue_nodes | def _torque_queue_nodes(queue):
"""Retrieve the nodes available for a queue.
Parses out nodes from `acl_hosts` in qstat -Qf and extracts the
initial names of nodes used in pbsnodes.
"""
qstat_out = subprocess.check_output(["qstat", "-Qf", queue]).decode()
hosts = []
in_hosts = False
for line in qstat_out.split("\n"):
if line.strip().startswith("acl_hosts = "):
hosts.extend(line.replace("acl_hosts = ", "").strip().split(","))
in_hosts = True
elif in_hosts:
if line.find(" = ") > 0:
break
else:
hosts.extend(line.strip().split(","))
return tuple([h.split(".")[0].strip() for h in hosts if h.strip()]) | python | def _torque_queue_nodes(queue):
"""Retrieve the nodes available for a queue.
Parses out nodes from `acl_hosts` in qstat -Qf and extracts the
initial names of nodes used in pbsnodes.
"""
qstat_out = subprocess.check_output(["qstat", "-Qf", queue]).decode()
hosts = []
in_hosts = False
for line in qstat_out.split("\n"):
if line.strip().startswith("acl_hosts = "):
hosts.extend(line.replace("acl_hosts = ", "").strip().split(","))
in_hosts = True
elif in_hosts:
if line.find(" = ") > 0:
break
else:
hosts.extend(line.strip().split(","))
return tuple([h.split(".")[0].strip() for h in hosts if h.strip()]) | [
"def",
"_torque_queue_nodes",
"(",
"queue",
")",
":",
"qstat_out",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"\"qstat\"",
",",
"\"-Qf\"",
",",
"queue",
"]",
")",
".",
"decode",
"(",
")",
"hosts",
"=",
"[",
"]",
"in_hosts",
"=",
"False",
"for",
... | Retrieve the nodes available for a queue.
Parses out nodes from `acl_hosts` in qstat -Qf and extracts the
initial names of nodes used in pbsnodes. | [
"Retrieve",
"the",
"nodes",
"available",
"for",
"a",
"queue",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/system.py#L101-L119 | train | 218,963 |
bcbio/bcbio-nextgen | bcbio/provenance/system.py | _sge_info | def _sge_info(queue):
"""Returns machine information for an sge job scheduler.
"""
qhost_out = subprocess.check_output(["qhost", "-q", "-xml"]).decode()
qstat_queue = ["-q", queue] if queue and "," not in queue else []
qstat_out = subprocess.check_output(["qstat", "-f", "-xml"] + qstat_queue).decode()
slot_info = _sge_get_slots(qstat_out)
mem_info = _sge_get_mem(qhost_out, queue)
machine_keys = slot_info.keys()
#num_cpus_vec = [slot_info[x]["slots_total"] for x in machine_keys]
#mem_vec = [mem_info[x]["mem_total"] for x in machine_keys]
mem_per_slot = [mem_info[x]["mem_total"] / float(slot_info[x]["slots_total"]) for x in machine_keys]
min_ratio_index = mem_per_slot.index(median_left(mem_per_slot))
mem_info[machine_keys[min_ratio_index]]["mem_total"]
return [{"cores": slot_info[machine_keys[min_ratio_index]]["slots_total"],
"memory": mem_info[machine_keys[min_ratio_index]]["mem_total"],
"name": "sge_machine"}] | python | def _sge_info(queue):
"""Returns machine information for an sge job scheduler.
"""
qhost_out = subprocess.check_output(["qhost", "-q", "-xml"]).decode()
qstat_queue = ["-q", queue] if queue and "," not in queue else []
qstat_out = subprocess.check_output(["qstat", "-f", "-xml"] + qstat_queue).decode()
slot_info = _sge_get_slots(qstat_out)
mem_info = _sge_get_mem(qhost_out, queue)
machine_keys = slot_info.keys()
#num_cpus_vec = [slot_info[x]["slots_total"] for x in machine_keys]
#mem_vec = [mem_info[x]["mem_total"] for x in machine_keys]
mem_per_slot = [mem_info[x]["mem_total"] / float(slot_info[x]["slots_total"]) for x in machine_keys]
min_ratio_index = mem_per_slot.index(median_left(mem_per_slot))
mem_info[machine_keys[min_ratio_index]]["mem_total"]
return [{"cores": slot_info[machine_keys[min_ratio_index]]["slots_total"],
"memory": mem_info[machine_keys[min_ratio_index]]["mem_total"],
"name": "sge_machine"}] | [
"def",
"_sge_info",
"(",
"queue",
")",
":",
"qhost_out",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"\"qhost\"",
",",
"\"-q\"",
",",
"\"-xml\"",
"]",
")",
".",
"decode",
"(",
")",
"qstat_queue",
"=",
"[",
"\"-q\"",
",",
"queue",
"]",
"if",
"queu... | Returns machine information for an sge job scheduler. | [
"Returns",
"machine",
"information",
"for",
"an",
"sge",
"job",
"scheduler",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/system.py#L128-L144 | train | 218,964 |
bcbio/bcbio-nextgen | bcbio/provenance/system.py | _sge_get_slots | def _sge_get_slots(xmlstring):
""" Get slot information from qstat
"""
rootxml = ET.fromstring(xmlstring)
my_machine_dict = {}
for queue_list in rootxml.iter("Queue-List"):
# find all hosts supporting queues
my_hostname = queue_list.find("name").text.rsplit("@")[-1]
my_slots = queue_list.find("slots_total").text
my_machine_dict[my_hostname] = {}
my_machine_dict[my_hostname]["slots_total"] = int(my_slots)
return my_machine_dict | python | def _sge_get_slots(xmlstring):
""" Get slot information from qstat
"""
rootxml = ET.fromstring(xmlstring)
my_machine_dict = {}
for queue_list in rootxml.iter("Queue-List"):
# find all hosts supporting queues
my_hostname = queue_list.find("name").text.rsplit("@")[-1]
my_slots = queue_list.find("slots_total").text
my_machine_dict[my_hostname] = {}
my_machine_dict[my_hostname]["slots_total"] = int(my_slots)
return my_machine_dict | [
"def",
"_sge_get_slots",
"(",
"xmlstring",
")",
":",
"rootxml",
"=",
"ET",
".",
"fromstring",
"(",
"xmlstring",
")",
"my_machine_dict",
"=",
"{",
"}",
"for",
"queue_list",
"in",
"rootxml",
".",
"iter",
"(",
"\"Queue-List\"",
")",
":",
"# find all hosts support... | Get slot information from qstat | [
"Get",
"slot",
"information",
"from",
"qstat"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/system.py#L146-L157 | train | 218,965 |
bcbio/bcbio-nextgen | bcbio/provenance/system.py | _sge_get_mem | def _sge_get_mem(xmlstring, queue_name):
""" Get memory information from qhost
"""
rootxml = ET.fromstring(xmlstring)
my_machine_dict = {}
# on some machines rootxml.tag looks like "{...}qhost" where the "{...}" gets prepended to all attributes
rootTag = rootxml.tag.rstrip("qhost")
for host in rootxml.findall(rootTag + 'host'):
# find all hosts supporting queues
for queues in host.findall(rootTag + 'queue'):
# if the user specified queue matches that in the xml:
if not queue_name or any(q in queues.attrib['name'] for q in queue_name.split(",")):
my_machine_dict[host.attrib['name']] = {}
# values from xml for number of processors and mem_total on each machine
for hostvalues in host.findall(rootTag + 'hostvalue'):
if('mem_total' == hostvalues.attrib['name']):
if hostvalues.text.lower().endswith('g'):
multip = 1
elif hostvalues.text.lower().endswith('m'):
multip = 1 / float(1024)
elif hostvalues.text.lower().endswith('t'):
multip = 1024
else:
raise Exception("Unrecognized suffix in mem_tot from SGE")
my_machine_dict[host.attrib['name']]['mem_total'] = \
float(hostvalues.text[:-1]) * float(multip)
break
return my_machine_dict | python | def _sge_get_mem(xmlstring, queue_name):
""" Get memory information from qhost
"""
rootxml = ET.fromstring(xmlstring)
my_machine_dict = {}
# on some machines rootxml.tag looks like "{...}qhost" where the "{...}" gets prepended to all attributes
rootTag = rootxml.tag.rstrip("qhost")
for host in rootxml.findall(rootTag + 'host'):
# find all hosts supporting queues
for queues in host.findall(rootTag + 'queue'):
# if the user specified queue matches that in the xml:
if not queue_name or any(q in queues.attrib['name'] for q in queue_name.split(",")):
my_machine_dict[host.attrib['name']] = {}
# values from xml for number of processors and mem_total on each machine
for hostvalues in host.findall(rootTag + 'hostvalue'):
if('mem_total' == hostvalues.attrib['name']):
if hostvalues.text.lower().endswith('g'):
multip = 1
elif hostvalues.text.lower().endswith('m'):
multip = 1 / float(1024)
elif hostvalues.text.lower().endswith('t'):
multip = 1024
else:
raise Exception("Unrecognized suffix in mem_tot from SGE")
my_machine_dict[host.attrib['name']]['mem_total'] = \
float(hostvalues.text[:-1]) * float(multip)
break
return my_machine_dict | [
"def",
"_sge_get_mem",
"(",
"xmlstring",
",",
"queue_name",
")",
":",
"rootxml",
"=",
"ET",
".",
"fromstring",
"(",
"xmlstring",
")",
"my_machine_dict",
"=",
"{",
"}",
"# on some machines rootxml.tag looks like \"{...}qhost\" where the \"{...}\" gets prepended to all attribut... | Get memory information from qhost | [
"Get",
"memory",
"information",
"from",
"qhost"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/system.py#L159-L186 | train | 218,966 |
bcbio/bcbio-nextgen | bcbio/provenance/system.py | get_info | def get_info(dirs, parallel, resources=None):
"""Retrieve cluster or local filesystem resources from pre-retrieved information.
"""
# Allow custom specification of cores/memory in resources
if resources and isinstance(resources, dict) and "machine" in resources:
minfo = resources["machine"]
assert "memory" in minfo, "Require memory specification (Gb) in machine resources: %s" % minfo
assert "cores" in minfo, "Require core specification in machine resources: %s" % minfo
return minfo
if parallel["type"] in ["ipython"] and not parallel["queue"] == "localrun":
cache_file = _get_cache_file(dirs, parallel)
if utils.file_exists(cache_file):
with open(cache_file) as in_handle:
minfo = yaml.safe_load(in_handle)
return _combine_machine_info(minfo)
else:
return {}
else:
return _combine_machine_info(machine_info()) | python | def get_info(dirs, parallel, resources=None):
"""Retrieve cluster or local filesystem resources from pre-retrieved information.
"""
# Allow custom specification of cores/memory in resources
if resources and isinstance(resources, dict) and "machine" in resources:
minfo = resources["machine"]
assert "memory" in minfo, "Require memory specification (Gb) in machine resources: %s" % minfo
assert "cores" in minfo, "Require core specification in machine resources: %s" % minfo
return minfo
if parallel["type"] in ["ipython"] and not parallel["queue"] == "localrun":
cache_file = _get_cache_file(dirs, parallel)
if utils.file_exists(cache_file):
with open(cache_file) as in_handle:
minfo = yaml.safe_load(in_handle)
return _combine_machine_info(minfo)
else:
return {}
else:
return _combine_machine_info(machine_info()) | [
"def",
"get_info",
"(",
"dirs",
",",
"parallel",
",",
"resources",
"=",
"None",
")",
":",
"# Allow custom specification of cores/memory in resources",
"if",
"resources",
"and",
"isinstance",
"(",
"resources",
",",
"dict",
")",
"and",
"\"machine\"",
"in",
"resources"... | Retrieve cluster or local filesystem resources from pre-retrieved information. | [
"Retrieve",
"cluster",
"or",
"local",
"filesystem",
"resources",
"from",
"pre",
"-",
"retrieved",
"information",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/system.py#L194-L212 | train | 218,967 |
bcbio/bcbio-nextgen | bcbio/provenance/system.py | machine_info | def machine_info():
"""Retrieve core and memory information for the current machine.
"""
import psutil
BYTES_IN_GIG = 1073741824.0
free_bytes = psutil.virtual_memory().total
return [{"memory": float("%.1f" % (free_bytes / BYTES_IN_GIG)), "cores": multiprocessing.cpu_count(),
"name": socket.gethostname()}] | python | def machine_info():
"""Retrieve core and memory information for the current machine.
"""
import psutil
BYTES_IN_GIG = 1073741824.0
free_bytes = psutil.virtual_memory().total
return [{"memory": float("%.1f" % (free_bytes / BYTES_IN_GIG)), "cores": multiprocessing.cpu_count(),
"name": socket.gethostname()}] | [
"def",
"machine_info",
"(",
")",
":",
"import",
"psutil",
"BYTES_IN_GIG",
"=",
"1073741824.0",
"free_bytes",
"=",
"psutil",
".",
"virtual_memory",
"(",
")",
".",
"total",
"return",
"[",
"{",
"\"memory\"",
":",
"float",
"(",
"\"%.1f\"",
"%",
"(",
"free_bytes"... | Retrieve core and memory information for the current machine. | [
"Retrieve",
"core",
"and",
"memory",
"information",
"for",
"the",
"current",
"machine",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/system.py#L214-L221 | train | 218,968 |
bcbio/bcbio-nextgen | bcbio/rnaseq/dexseq.py | run_count | def run_count(bam_file, dexseq_gff, stranded, out_file, data):
"""
run dexseq_count on a BAM file
"""
assert file_exists(bam_file), "%s does not exist." % bam_file
sort_order = bam._get_sort_order(bam_file, {})
assert sort_order, "Cannot determine sort order of %s." % bam_file
strand_flag = _strand_flag(stranded)
assert strand_flag, "%s is not a valid strandedness value." % stranded
if not dexseq_gff:
logger.info("No DEXSeq GFF file was found, skipping exon-level counting.")
return None
elif not file_exists(dexseq_gff):
logger.info("%s was not found, so exon-level counting is being "
"skipped." % dexseq_gff)
return None
dexseq_count = _dexseq_count_path()
if not dexseq_count:
logger.info("DEXseq is not installed, skipping exon-level counting.")
return None
if dd.get_aligner(data) == "bwa":
logger.info("Can't use DEXSeq with bwa alignments, skipping exon-level counting.")
return None
sort_flag = "name" if sort_order == "queryname" else "pos"
is_paired = bam.is_paired(bam_file)
paired_flag = "yes" if is_paired else "no"
bcbio_python = sys.executable
if file_exists(out_file):
return out_file
cmd = ("{bcbio_python} {dexseq_count} -f bam -r {sort_flag} -p {paired_flag} "
"-s {strand_flag} {dexseq_gff} {bam_file} {tx_out_file}")
message = "Counting exon-level counts with %s and %s." % (bam_file, dexseq_gff)
with file_transaction(data, out_file) as tx_out_file:
do.run(cmd.format(**locals()), message)
return out_file | python | def run_count(bam_file, dexseq_gff, stranded, out_file, data):
"""
run dexseq_count on a BAM file
"""
assert file_exists(bam_file), "%s does not exist." % bam_file
sort_order = bam._get_sort_order(bam_file, {})
assert sort_order, "Cannot determine sort order of %s." % bam_file
strand_flag = _strand_flag(stranded)
assert strand_flag, "%s is not a valid strandedness value." % stranded
if not dexseq_gff:
logger.info("No DEXSeq GFF file was found, skipping exon-level counting.")
return None
elif not file_exists(dexseq_gff):
logger.info("%s was not found, so exon-level counting is being "
"skipped." % dexseq_gff)
return None
dexseq_count = _dexseq_count_path()
if not dexseq_count:
logger.info("DEXseq is not installed, skipping exon-level counting.")
return None
if dd.get_aligner(data) == "bwa":
logger.info("Can't use DEXSeq with bwa alignments, skipping exon-level counting.")
return None
sort_flag = "name" if sort_order == "queryname" else "pos"
is_paired = bam.is_paired(bam_file)
paired_flag = "yes" if is_paired else "no"
bcbio_python = sys.executable
if file_exists(out_file):
return out_file
cmd = ("{bcbio_python} {dexseq_count} -f bam -r {sort_flag} -p {paired_flag} "
"-s {strand_flag} {dexseq_gff} {bam_file} {tx_out_file}")
message = "Counting exon-level counts with %s and %s." % (bam_file, dexseq_gff)
with file_transaction(data, out_file) as tx_out_file:
do.run(cmd.format(**locals()), message)
return out_file | [
"def",
"run_count",
"(",
"bam_file",
",",
"dexseq_gff",
",",
"stranded",
",",
"out_file",
",",
"data",
")",
":",
"assert",
"file_exists",
"(",
"bam_file",
")",
",",
"\"%s does not exist.\"",
"%",
"bam_file",
"sort_order",
"=",
"bam",
".",
"_get_sort_order",
"(... | run dexseq_count on a BAM file | [
"run",
"dexseq_count",
"on",
"a",
"BAM",
"file"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/dexseq.py#L27-L65 | train | 218,969 |
bcbio/bcbio-nextgen | bcbio/bam/trim.py | _trim_adapters | def _trim_adapters(fastq_files, out_dir, data):
"""
for small insert sizes, the read length can be longer than the insert
resulting in the reverse complement of the 3' adapter being sequenced.
this takes adapter sequences and trims the only the reverse complement
of the adapter
MYSEQUENCEAAAARETPADA -> MYSEQUENCEAAAA (no polyA trim)
"""
to_trim = _get_sequences_to_trim(data["config"], SUPPORTED_ADAPTERS)
if dd.get_trim_reads(data) == "fastp":
out_files, report_file = _fastp_trim(fastq_files, to_trim, out_dir, data)
else:
out_files, report_file = _atropos_trim(fastq_files, to_trim, out_dir, data)
# quality_format = _get_quality_format(data["config"])
# out_files = replace_directory(append_stem(fastq_files, "_%s.trimmed" % name), out_dir)
# log_file = "%s_log_cutadapt.txt" % splitext_plus(out_files[0])[0]
# out_files = _cutadapt_trim(fastq_files, quality_format, to_trim, out_files, log_file, data)
# if file_exists(log_file):
# content = open(log_file).read().replace(fastq_files[0], name)
# if len(fastq_files) > 1:
# content = content.replace(fastq_files[1], name)
# open(log_file, 'w').write(content)
return out_files | python | def _trim_adapters(fastq_files, out_dir, data):
"""
for small insert sizes, the read length can be longer than the insert
resulting in the reverse complement of the 3' adapter being sequenced.
this takes adapter sequences and trims the only the reverse complement
of the adapter
MYSEQUENCEAAAARETPADA -> MYSEQUENCEAAAA (no polyA trim)
"""
to_trim = _get_sequences_to_trim(data["config"], SUPPORTED_ADAPTERS)
if dd.get_trim_reads(data) == "fastp":
out_files, report_file = _fastp_trim(fastq_files, to_trim, out_dir, data)
else:
out_files, report_file = _atropos_trim(fastq_files, to_trim, out_dir, data)
# quality_format = _get_quality_format(data["config"])
# out_files = replace_directory(append_stem(fastq_files, "_%s.trimmed" % name), out_dir)
# log_file = "%s_log_cutadapt.txt" % splitext_plus(out_files[0])[0]
# out_files = _cutadapt_trim(fastq_files, quality_format, to_trim, out_files, log_file, data)
# if file_exists(log_file):
# content = open(log_file).read().replace(fastq_files[0], name)
# if len(fastq_files) > 1:
# content = content.replace(fastq_files[1], name)
# open(log_file, 'w').write(content)
return out_files | [
"def",
"_trim_adapters",
"(",
"fastq_files",
",",
"out_dir",
",",
"data",
")",
":",
"to_trim",
"=",
"_get_sequences_to_trim",
"(",
"data",
"[",
"\"config\"",
"]",
",",
"SUPPORTED_ADAPTERS",
")",
"if",
"dd",
".",
"get_trim_reads",
"(",
"data",
")",
"==",
"\"f... | for small insert sizes, the read length can be longer than the insert
resulting in the reverse complement of the 3' adapter being sequenced.
this takes adapter sequences and trims the only the reverse complement
of the adapter
MYSEQUENCEAAAARETPADA -> MYSEQUENCEAAAA (no polyA trim) | [
"for",
"small",
"insert",
"sizes",
"the",
"read",
"length",
"can",
"be",
"longer",
"than",
"the",
"insert",
"resulting",
"in",
"the",
"reverse",
"complement",
"of",
"the",
"3",
"adapter",
"being",
"sequenced",
".",
"this",
"takes",
"adapter",
"sequences",
"a... | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/trim.py#L36-L59 | train | 218,970 |
bcbio/bcbio-nextgen | bcbio/bam/trim.py | _cutadapt_trim | def _cutadapt_trim(fastq_files, quality_format, adapters, out_files, log_file, data):
"""Trimming with cutadapt.
"""
if all([utils.file_exists(x) for x in out_files]):
return out_files
cmd = _cutadapt_trim_cmd(fastq_files, quality_format, adapters, out_files, data)
if len(fastq_files) == 1:
of = [out_files[0], log_file]
message = "Trimming %s in single end mode with cutadapt." % (fastq_files[0])
with file_transaction(data, of) as of_tx:
of1_tx, log_tx = of_tx
do.run(cmd.format(**locals()), message)
else:
of = out_files + [log_file]
with file_transaction(data, of) as tx_out_files:
of1_tx, of2_tx, log_tx = tx_out_files
tmp_fq1 = utils.append_stem(of1_tx, ".tmp")
tmp_fq2 = utils.append_stem(of2_tx, ".tmp")
singles_file = of1_tx + ".single"
message = "Trimming %s and %s in paired end mode with cutadapt." % (fastq_files[0],
fastq_files[1])
do.run(cmd.format(**locals()), message)
return out_files | python | def _cutadapt_trim(fastq_files, quality_format, adapters, out_files, log_file, data):
"""Trimming with cutadapt.
"""
if all([utils.file_exists(x) for x in out_files]):
return out_files
cmd = _cutadapt_trim_cmd(fastq_files, quality_format, adapters, out_files, data)
if len(fastq_files) == 1:
of = [out_files[0], log_file]
message = "Trimming %s in single end mode with cutadapt." % (fastq_files[0])
with file_transaction(data, of) as of_tx:
of1_tx, log_tx = of_tx
do.run(cmd.format(**locals()), message)
else:
of = out_files + [log_file]
with file_transaction(data, of) as tx_out_files:
of1_tx, of2_tx, log_tx = tx_out_files
tmp_fq1 = utils.append_stem(of1_tx, ".tmp")
tmp_fq2 = utils.append_stem(of2_tx, ".tmp")
singles_file = of1_tx + ".single"
message = "Trimming %s and %s in paired end mode with cutadapt." % (fastq_files[0],
fastq_files[1])
do.run(cmd.format(**locals()), message)
return out_files | [
"def",
"_cutadapt_trim",
"(",
"fastq_files",
",",
"quality_format",
",",
"adapters",
",",
"out_files",
",",
"log_file",
",",
"data",
")",
":",
"if",
"all",
"(",
"[",
"utils",
".",
"file_exists",
"(",
"x",
")",
"for",
"x",
"in",
"out_files",
"]",
")",
"... | Trimming with cutadapt. | [
"Trimming",
"with",
"cutadapt",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/trim.py#L192-L214 | train | 218,971 |
bcbio/bcbio-nextgen | bcbio/bam/trim.py | _cutadapt_trim_cmd | def _cutadapt_trim_cmd(fastq_files, quality_format, adapters, out_files, data):
"""Trimming with cutadapt, using version installed with bcbio-nextgen.
"""
if all([utils.file_exists(x) for x in out_files]):
return out_files
if quality_format == "illumina":
quality_base = "64"
else:
quality_base = "33"
# --times=2 tries twice remove adapters which will allow things like:
# realsequenceAAAAAAadapter to remove both the poly-A and the adapter
# this behavior might not be what we want; we could also do two or
# more passes of cutadapt
cutadapt = os.path.join(os.path.dirname(sys.executable), "cutadapt")
adapter_cmd = " ".join(map(lambda x: "-a " + x, adapters))
ropts = " ".join(str(x) for x in
config_utils.get_resources("cutadapt", data["config"]).get("options", []))
base_cmd = ("{cutadapt} {ropts} --times=2 --quality-base={quality_base} "
"--quality-cutoff=5 --format=fastq "
"{adapter_cmd} ").format(**locals())
if len(fastq_files) == 2:
# support for the single-command paired trimming introduced in
# cutadapt 1.8
adapter_cmd = adapter_cmd.replace("-a ", "-A ")
base_cmd += "{adapter_cmd} ".format(adapter_cmd=adapter_cmd)
return _cutadapt_pe_cmd(fastq_files, out_files, quality_format, base_cmd, data)
else:
return _cutadapt_se_cmd(fastq_files, out_files, base_cmd, data) | python | def _cutadapt_trim_cmd(fastq_files, quality_format, adapters, out_files, data):
"""Trimming with cutadapt, using version installed with bcbio-nextgen.
"""
if all([utils.file_exists(x) for x in out_files]):
return out_files
if quality_format == "illumina":
quality_base = "64"
else:
quality_base = "33"
# --times=2 tries twice remove adapters which will allow things like:
# realsequenceAAAAAAadapter to remove both the poly-A and the adapter
# this behavior might not be what we want; we could also do two or
# more passes of cutadapt
cutadapt = os.path.join(os.path.dirname(sys.executable), "cutadapt")
adapter_cmd = " ".join(map(lambda x: "-a " + x, adapters))
ropts = " ".join(str(x) for x in
config_utils.get_resources("cutadapt", data["config"]).get("options", []))
base_cmd = ("{cutadapt} {ropts} --times=2 --quality-base={quality_base} "
"--quality-cutoff=5 --format=fastq "
"{adapter_cmd} ").format(**locals())
if len(fastq_files) == 2:
# support for the single-command paired trimming introduced in
# cutadapt 1.8
adapter_cmd = adapter_cmd.replace("-a ", "-A ")
base_cmd += "{adapter_cmd} ".format(adapter_cmd=adapter_cmd)
return _cutadapt_pe_cmd(fastq_files, out_files, quality_format, base_cmd, data)
else:
return _cutadapt_se_cmd(fastq_files, out_files, base_cmd, data) | [
"def",
"_cutadapt_trim_cmd",
"(",
"fastq_files",
",",
"quality_format",
",",
"adapters",
",",
"out_files",
",",
"data",
")",
":",
"if",
"all",
"(",
"[",
"utils",
".",
"file_exists",
"(",
"x",
")",
"for",
"x",
"in",
"out_files",
"]",
")",
":",
"return",
... | Trimming with cutadapt, using version installed with bcbio-nextgen. | [
"Trimming",
"with",
"cutadapt",
"using",
"version",
"installed",
"with",
"bcbio",
"-",
"nextgen",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/trim.py#L216-L244 | train | 218,972 |
bcbio/bcbio-nextgen | bcbio/bam/trim.py | _cutadapt_se_cmd | def _cutadapt_se_cmd(fastq_files, out_files, base_cmd, data):
"""
this has to use the -o option, not redirect to stdout in order for
gzipping to be supported
"""
min_length = dd.get_min_read_length(data)
cmd = base_cmd + " --minimum-length={min_length} ".format(**locals())
fq1 = objectstore.cl_input(fastq_files[0])
of1 = out_files[0]
cmd += " -o {of1_tx} " + str(fq1)
cmd = "%s | tee > {log_tx}" % cmd
return cmd | python | def _cutadapt_se_cmd(fastq_files, out_files, base_cmd, data):
"""
this has to use the -o option, not redirect to stdout in order for
gzipping to be supported
"""
min_length = dd.get_min_read_length(data)
cmd = base_cmd + " --minimum-length={min_length} ".format(**locals())
fq1 = objectstore.cl_input(fastq_files[0])
of1 = out_files[0]
cmd += " -o {of1_tx} " + str(fq1)
cmd = "%s | tee > {log_tx}" % cmd
return cmd | [
"def",
"_cutadapt_se_cmd",
"(",
"fastq_files",
",",
"out_files",
",",
"base_cmd",
",",
"data",
")",
":",
"min_length",
"=",
"dd",
".",
"get_min_read_length",
"(",
"data",
")",
"cmd",
"=",
"base_cmd",
"+",
"\" --minimum-length={min_length} \"",
".",
"format",
"("... | this has to use the -o option, not redirect to stdout in order for
gzipping to be supported | [
"this",
"has",
"to",
"use",
"the",
"-",
"o",
"option",
"not",
"redirect",
"to",
"stdout",
"in",
"order",
"for",
"gzipping",
"to",
"be",
"supported"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/trim.py#L246-L257 | train | 218,973 |
bcbio/bcbio-nextgen | bcbio/bam/trim.py | _cutadapt_pe_cmd | def _cutadapt_pe_cmd(fastq_files, out_files, quality_format, base_cmd, data):
"""
run cutadapt in paired end mode
"""
fq1, fq2 = [objectstore.cl_input(x) for x in fastq_files]
of1, of2 = out_files
base_cmd += " --minimum-length={min_length} ".format(min_length=dd.get_min_read_length(data))
first_cmd = base_cmd + " -o {of1_tx} -p {of2_tx} " + fq1 + " " + fq2
return first_cmd + "| tee > {log_tx};" | python | def _cutadapt_pe_cmd(fastq_files, out_files, quality_format, base_cmd, data):
"""
run cutadapt in paired end mode
"""
fq1, fq2 = [objectstore.cl_input(x) for x in fastq_files]
of1, of2 = out_files
base_cmd += " --minimum-length={min_length} ".format(min_length=dd.get_min_read_length(data))
first_cmd = base_cmd + " -o {of1_tx} -p {of2_tx} " + fq1 + " " + fq2
return first_cmd + "| tee > {log_tx};" | [
"def",
"_cutadapt_pe_cmd",
"(",
"fastq_files",
",",
"out_files",
",",
"quality_format",
",",
"base_cmd",
",",
"data",
")",
":",
"fq1",
",",
"fq2",
"=",
"[",
"objectstore",
".",
"cl_input",
"(",
"x",
")",
"for",
"x",
"in",
"fastq_files",
"]",
"of1",
",",
... | run cutadapt in paired end mode | [
"run",
"cutadapt",
"in",
"paired",
"end",
"mode"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/trim.py#L259-L267 | train | 218,974 |
bcbio/bcbio-nextgen | bcbio/variation/realign.py | gatk_realigner_targets | def gatk_realigner_targets(runner, align_bam, ref_file, config, dbsnp=None,
region=None, out_file=None, deep_coverage=False,
variant_regions=None, known_vrns=None):
"""Generate a list of interval regions for realignment around indels.
"""
if not known_vrns:
known_vrns = {}
if out_file:
out_file = "%s.intervals" % os.path.splitext(out_file)[0]
else:
out_file = "%s-realign.intervals" % os.path.splitext(align_bam)[0]
# check only for file existence; interval files can be empty after running
# on small chromosomes, so don't rerun in those cases
if not os.path.exists(out_file):
with file_transaction(config, out_file) as tx_out_file:
logger.debug("GATK RealignerTargetCreator: %s %s" %
(os.path.basename(align_bam), region))
params = ["-T", "RealignerTargetCreator",
"-I", align_bam,
"-R", ref_file,
"-o", tx_out_file,
"-l", "INFO",
]
region = subset_variant_regions(variant_regions, region, tx_out_file)
if region:
params += ["-L", region, "--interval_set_rule", "INTERSECTION"]
if known_vrns.get("train_indels"):
params += ["--known", known_vrns["train_indels"]]
if deep_coverage:
params += ["--mismatchFraction", "0.30",
"--maxIntervalSize", "650"]
runner.run_gatk(params, memscale={"direction": "decrease", "magnitude": 2})
return out_file | python | def gatk_realigner_targets(runner, align_bam, ref_file, config, dbsnp=None,
region=None, out_file=None, deep_coverage=False,
variant_regions=None, known_vrns=None):
"""Generate a list of interval regions for realignment around indels.
"""
if not known_vrns:
known_vrns = {}
if out_file:
out_file = "%s.intervals" % os.path.splitext(out_file)[0]
else:
out_file = "%s-realign.intervals" % os.path.splitext(align_bam)[0]
# check only for file existence; interval files can be empty after running
# on small chromosomes, so don't rerun in those cases
if not os.path.exists(out_file):
with file_transaction(config, out_file) as tx_out_file:
logger.debug("GATK RealignerTargetCreator: %s %s" %
(os.path.basename(align_bam), region))
params = ["-T", "RealignerTargetCreator",
"-I", align_bam,
"-R", ref_file,
"-o", tx_out_file,
"-l", "INFO",
]
region = subset_variant_regions(variant_regions, region, tx_out_file)
if region:
params += ["-L", region, "--interval_set_rule", "INTERSECTION"]
if known_vrns.get("train_indels"):
params += ["--known", known_vrns["train_indels"]]
if deep_coverage:
params += ["--mismatchFraction", "0.30",
"--maxIntervalSize", "650"]
runner.run_gatk(params, memscale={"direction": "decrease", "magnitude": 2})
return out_file | [
"def",
"gatk_realigner_targets",
"(",
"runner",
",",
"align_bam",
",",
"ref_file",
",",
"config",
",",
"dbsnp",
"=",
"None",
",",
"region",
"=",
"None",
",",
"out_file",
"=",
"None",
",",
"deep_coverage",
"=",
"False",
",",
"variant_regions",
"=",
"None",
... | Generate a list of interval regions for realignment around indels. | [
"Generate",
"a",
"list",
"of",
"interval",
"regions",
"for",
"realignment",
"around",
"indels",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/realign.py#L15-L47 | train | 218,975 |
bcbio/bcbio-nextgen | bcbio/variation/realign.py | gatk_indel_realignment_cl | def gatk_indel_realignment_cl(runner, align_bam, ref_file, intervals,
tmp_dir, region=None, deep_coverage=False,
known_vrns=None):
"""Prepare input arguments for GATK indel realignment.
"""
if not known_vrns:
known_vrns = {}
params = ["-T", "IndelRealigner",
"-I", align_bam,
"-R", ref_file,
"-targetIntervals", intervals,
]
if region:
params += ["-L", region]
if known_vrns.get("train_indels"):
params += ["--knownAlleles", known_vrns["train_indels"]]
if deep_coverage:
params += ["--maxReadsInMemory", "300000",
"--maxReadsForRealignment", str(int(5e5)),
"--maxReadsForConsensuses", "500",
"--maxConsensuses", "100"]
return runner.cl_gatk(params, tmp_dir) | python | def gatk_indel_realignment_cl(runner, align_bam, ref_file, intervals,
tmp_dir, region=None, deep_coverage=False,
known_vrns=None):
"""Prepare input arguments for GATK indel realignment.
"""
if not known_vrns:
known_vrns = {}
params = ["-T", "IndelRealigner",
"-I", align_bam,
"-R", ref_file,
"-targetIntervals", intervals,
]
if region:
params += ["-L", region]
if known_vrns.get("train_indels"):
params += ["--knownAlleles", known_vrns["train_indels"]]
if deep_coverage:
params += ["--maxReadsInMemory", "300000",
"--maxReadsForRealignment", str(int(5e5)),
"--maxReadsForConsensuses", "500",
"--maxConsensuses", "100"]
return runner.cl_gatk(params, tmp_dir) | [
"def",
"gatk_indel_realignment_cl",
"(",
"runner",
",",
"align_bam",
",",
"ref_file",
",",
"intervals",
",",
"tmp_dir",
",",
"region",
"=",
"None",
",",
"deep_coverage",
"=",
"False",
",",
"known_vrns",
"=",
"None",
")",
":",
"if",
"not",
"known_vrns",
":",
... | Prepare input arguments for GATK indel realignment. | [
"Prepare",
"input",
"arguments",
"for",
"GATK",
"indel",
"realignment",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/realign.py#L49-L70 | train | 218,976 |
bcbio/bcbio-nextgen | bcbio/variation/realign.py | has_aligned_reads | def has_aligned_reads(align_bam, region=None):
"""Check if the aligned BAM file has any reads in the region.
region can be a chromosome string ("chr22"),
a tuple region (("chr22", 1, 100)) or a file of regions.
"""
import pybedtools
if region is not None:
if isinstance(region, six.string_types) and os.path.isfile(region):
regions = [tuple(r) for r in pybedtools.BedTool(region)]
else:
regions = [region]
with pysam.Samfile(align_bam, "rb") as cur_bam:
if region is not None:
for region in regions:
if isinstance(region, six.string_types):
for item in cur_bam.fetch(str(region)):
return True
else:
for item in cur_bam.fetch(str(region[0]), int(region[1]), int(region[2])):
return True
else:
for item in cur_bam:
if not item.is_unmapped:
return True
return False | python | def has_aligned_reads(align_bam, region=None):
"""Check if the aligned BAM file has any reads in the region.
region can be a chromosome string ("chr22"),
a tuple region (("chr22", 1, 100)) or a file of regions.
"""
import pybedtools
if region is not None:
if isinstance(region, six.string_types) and os.path.isfile(region):
regions = [tuple(r) for r in pybedtools.BedTool(region)]
else:
regions = [region]
with pysam.Samfile(align_bam, "rb") as cur_bam:
if region is not None:
for region in regions:
if isinstance(region, six.string_types):
for item in cur_bam.fetch(str(region)):
return True
else:
for item in cur_bam.fetch(str(region[0]), int(region[1]), int(region[2])):
return True
else:
for item in cur_bam:
if not item.is_unmapped:
return True
return False | [
"def",
"has_aligned_reads",
"(",
"align_bam",
",",
"region",
"=",
"None",
")",
":",
"import",
"pybedtools",
"if",
"region",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"region",
",",
"six",
".",
"string_types",
")",
"and",
"os",
".",
"path",
".",
... | Check if the aligned BAM file has any reads in the region.
region can be a chromosome string ("chr22"),
a tuple region (("chr22", 1, 100)) or a file of regions. | [
"Check",
"if",
"the",
"aligned",
"BAM",
"file",
"has",
"any",
"reads",
"in",
"the",
"region",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/realign.py#L74-L99 | train | 218,977 |
bcbio/bcbio-nextgen | bcbio/cwl/defs.py | s | def s(name, parallel, inputs, outputs, image, programs=None, disk=None, cores=None, unlist=None,
no_files=False):
"""Represent a step in a workflow.
name -- The run function name, which must match a definition in distributed/multitasks
inputs -- List of input keys required for the function. Each key is of the type:
["toplevel", "sublevel"] -- an argument you could pass to toolz.get_in.
outputs -- List of outputs with information about file type. Use cwlout functions
programs -- Required programs for this step, used to define resource usage.
disk -- Information about disk usage requirements, specified as multipliers of
input files. Ensures enough disk present when that is a limiting factor
when selecting cloud node resources.
cores -- Maximum cores necessary for this step, for non-multicore processes.
unlist -- Variables being unlisted by this process. Useful for parallelization splitting and
batching from multiple variables, like variant calling.
no_files -- This step does not require file access.
parallel -- Parallelization approach. There are three different levels of parallelization,
each with subcomponents:
1. multi -- Multiple samples, parallelizing at the sample level. Used in top-level workflow.
- multi-parallel -- Run individual samples in parallel.
- multi-combined -- Run all samples together.
- multi-batch -- Run all samples together, converting into batches of grouped samples.
2. single -- A single sample, used in sub-workflows.
- single-split -- Split a sample into sub-components (by read sections).
- single-parallel -- Run sub-components of a sample in parallel.
- single-merge -- Merge multiple sub-components into a single sample.
- single-single -- Single sample, single item, nothing fancy.
3. batch -- Several related samples (tumor/normal, or populations). Used in sub-workflows.
- batch-split -- Split a batch of samples into sub-components (by genomic region).
- batch-parallel -- Run sub-components of a batch in parallel.
- batch-merge -- Merge sub-components back into a single batch.
- batch-single -- Run on a single batch.
"""
Step = collections.namedtuple("Step", "name parallel inputs outputs image programs disk cores unlist no_files")
if programs is None: programs = []
if unlist is None: unlist = []
return Step(name, parallel, inputs, outputs, image, programs, disk, cores, unlist, no_files) | python | def s(name, parallel, inputs, outputs, image, programs=None, disk=None, cores=None, unlist=None,
no_files=False):
"""Represent a step in a workflow.
name -- The run function name, which must match a definition in distributed/multitasks
inputs -- List of input keys required for the function. Each key is of the type:
["toplevel", "sublevel"] -- an argument you could pass to toolz.get_in.
outputs -- List of outputs with information about file type. Use cwlout functions
programs -- Required programs for this step, used to define resource usage.
disk -- Information about disk usage requirements, specified as multipliers of
input files. Ensures enough disk present when that is a limiting factor
when selecting cloud node resources.
cores -- Maximum cores necessary for this step, for non-multicore processes.
unlist -- Variables being unlisted by this process. Useful for parallelization splitting and
batching from multiple variables, like variant calling.
no_files -- This step does not require file access.
parallel -- Parallelization approach. There are three different levels of parallelization,
each with subcomponents:
1. multi -- Multiple samples, parallelizing at the sample level. Used in top-level workflow.
- multi-parallel -- Run individual samples in parallel.
- multi-combined -- Run all samples together.
- multi-batch -- Run all samples together, converting into batches of grouped samples.
2. single -- A single sample, used in sub-workflows.
- single-split -- Split a sample into sub-components (by read sections).
- single-parallel -- Run sub-components of a sample in parallel.
- single-merge -- Merge multiple sub-components into a single sample.
- single-single -- Single sample, single item, nothing fancy.
3. batch -- Several related samples (tumor/normal, or populations). Used in sub-workflows.
- batch-split -- Split a batch of samples into sub-components (by genomic region).
- batch-parallel -- Run sub-components of a batch in parallel.
- batch-merge -- Merge sub-components back into a single batch.
- batch-single -- Run on a single batch.
"""
Step = collections.namedtuple("Step", "name parallel inputs outputs image programs disk cores unlist no_files")
if programs is None: programs = []
if unlist is None: unlist = []
return Step(name, parallel, inputs, outputs, image, programs, disk, cores, unlist, no_files) | [
"def",
"s",
"(",
"name",
",",
"parallel",
",",
"inputs",
",",
"outputs",
",",
"image",
",",
"programs",
"=",
"None",
",",
"disk",
"=",
"None",
",",
"cores",
"=",
"None",
",",
"unlist",
"=",
"None",
",",
"no_files",
"=",
"False",
")",
":",
"Step",
... | Represent a step in a workflow.
name -- The run function name, which must match a definition in distributed/multitasks
inputs -- List of input keys required for the function. Each key is of the type:
["toplevel", "sublevel"] -- an argument you could pass to toolz.get_in.
outputs -- List of outputs with information about file type. Use cwlout functions
programs -- Required programs for this step, used to define resource usage.
disk -- Information about disk usage requirements, specified as multipliers of
input files. Ensures enough disk present when that is a limiting factor
when selecting cloud node resources.
cores -- Maximum cores necessary for this step, for non-multicore processes.
unlist -- Variables being unlisted by this process. Useful for parallelization splitting and
batching from multiple variables, like variant calling.
no_files -- This step does not require file access.
parallel -- Parallelization approach. There are three different levels of parallelization,
each with subcomponents:
1. multi -- Multiple samples, parallelizing at the sample level. Used in top-level workflow.
- multi-parallel -- Run individual samples in parallel.
- multi-combined -- Run all samples together.
- multi-batch -- Run all samples together, converting into batches of grouped samples.
2. single -- A single sample, used in sub-workflows.
- single-split -- Split a sample into sub-components (by read sections).
- single-parallel -- Run sub-components of a sample in parallel.
- single-merge -- Merge multiple sub-components into a single sample.
- single-single -- Single sample, single item, nothing fancy.
3. batch -- Several related samples (tumor/normal, or populations). Used in sub-workflows.
- batch-split -- Split a batch of samples into sub-components (by genomic region).
- batch-parallel -- Run sub-components of a batch in parallel.
- batch-merge -- Merge sub-components back into a single batch.
- batch-single -- Run on a single batch. | [
"Represent",
"a",
"step",
"in",
"a",
"workflow",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/defs.py#L17-L54 | train | 218,978 |
bcbio/bcbio-nextgen | bcbio/cwl/defs.py | w | def w(name, parallel, workflow, internal):
"""A workflow, allowing specification of sub-workflows for nested parallelization.
name and parallel are documented under the Step (s) function.
workflow -- a list of Step tuples defining the sub-workflow
internal -- variables used in the sub-workflow but not exposed to subsequent steps
"""
Workflow = collections.namedtuple("Workflow", "name parallel workflow internal")
return Workflow(name, parallel, workflow, internal) | python | def w(name, parallel, workflow, internal):
"""A workflow, allowing specification of sub-workflows for nested parallelization.
name and parallel are documented under the Step (s) function.
workflow -- a list of Step tuples defining the sub-workflow
internal -- variables used in the sub-workflow but not exposed to subsequent steps
"""
Workflow = collections.namedtuple("Workflow", "name parallel workflow internal")
return Workflow(name, parallel, workflow, internal) | [
"def",
"w",
"(",
"name",
",",
"parallel",
",",
"workflow",
",",
"internal",
")",
":",
"Workflow",
"=",
"collections",
".",
"namedtuple",
"(",
"\"Workflow\"",
",",
"\"name parallel workflow internal\"",
")",
"return",
"Workflow",
"(",
"name",
",",
"parallel",
"... | A workflow, allowing specification of sub-workflows for nested parallelization.
name and parallel are documented under the Step (s) function.
workflow -- a list of Step tuples defining the sub-workflow
internal -- variables used in the sub-workflow but not exposed to subsequent steps | [
"A",
"workflow",
"allowing",
"specification",
"of",
"sub",
"-",
"workflows",
"for",
"nested",
"parallelization",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/defs.py#L56-L64 | train | 218,979 |
bcbio/bcbio-nextgen | bcbio/cwl/defs.py | et | def et(name, parallel, inputs, outputs, expression):
"""Represent an ExpressionTool that reorders inputs using javascript.
"""
ExpressionTool = collections.namedtuple("ExpressionTool", "name inputs outputs expression parallel")
return ExpressionTool(name, inputs, outputs, expression, parallel) | python | def et(name, parallel, inputs, outputs, expression):
"""Represent an ExpressionTool that reorders inputs using javascript.
"""
ExpressionTool = collections.namedtuple("ExpressionTool", "name inputs outputs expression parallel")
return ExpressionTool(name, inputs, outputs, expression, parallel) | [
"def",
"et",
"(",
"name",
",",
"parallel",
",",
"inputs",
",",
"outputs",
",",
"expression",
")",
":",
"ExpressionTool",
"=",
"collections",
".",
"namedtuple",
"(",
"\"ExpressionTool\"",
",",
"\"name inputs outputs expression parallel\"",
")",
"return",
"ExpressionT... | Represent an ExpressionTool that reorders inputs using javascript. | [
"Represent",
"an",
"ExpressionTool",
"that",
"reorders",
"inputs",
"using",
"javascript",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/defs.py#L66-L70 | train | 218,980 |
bcbio/bcbio-nextgen | bcbio/cwl/defs.py | cwlout | def cwlout(key, valtype=None, extensions=None, fields=None, exclude=None):
"""Definition of an output variable, defining the type and associated secondary files.
"""
out = {"id": key}
if valtype:
out["type"] = valtype
if fields:
out["fields"] = fields
if extensions:
out["secondaryFiles"] = extensions
if exclude:
out["exclude"] = exclude
return out | python | def cwlout(key, valtype=None, extensions=None, fields=None, exclude=None):
"""Definition of an output variable, defining the type and associated secondary files.
"""
out = {"id": key}
if valtype:
out["type"] = valtype
if fields:
out["fields"] = fields
if extensions:
out["secondaryFiles"] = extensions
if exclude:
out["exclude"] = exclude
return out | [
"def",
"cwlout",
"(",
"key",
",",
"valtype",
"=",
"None",
",",
"extensions",
"=",
"None",
",",
"fields",
"=",
"None",
",",
"exclude",
"=",
"None",
")",
":",
"out",
"=",
"{",
"\"id\"",
":",
"key",
"}",
"if",
"valtype",
":",
"out",
"[",
"\"type\"",
... | Definition of an output variable, defining the type and associated secondary files. | [
"Definition",
"of",
"an",
"output",
"variable",
"defining",
"the",
"type",
"and",
"associated",
"secondary",
"files",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/defs.py#L72-L84 | train | 218,981 |
bcbio/bcbio-nextgen | bcbio/cwl/defs.py | _variant_hla | def _variant_hla(checkpoints):
"""Add hla analysis to workflow, if configured.
"""
if not checkpoints.get("hla"):
return [], []
hla = [s("hla_to_rec", "multi-batch",
[["hla", "fastq"],
["config", "algorithm", "hlacaller"]],
[cwlout("hla_rec", "record")],
"bcbio-vc", cores=1, no_files=True),
s("call_hla", "multi-parallel",
[["hla_rec"]],
[cwlout(["hla", "hlacaller"], ["string", "null"]),
cwlout(["hla", "call_file"], ["File", "null"])],
"bcbio-vc", ["optitype;env=python2", "razers3=3.5.0", "coincbc"])]
return hla, [["hla", "call_file"]] | python | def _variant_hla(checkpoints):
"""Add hla analysis to workflow, if configured.
"""
if not checkpoints.get("hla"):
return [], []
hla = [s("hla_to_rec", "multi-batch",
[["hla", "fastq"],
["config", "algorithm", "hlacaller"]],
[cwlout("hla_rec", "record")],
"bcbio-vc", cores=1, no_files=True),
s("call_hla", "multi-parallel",
[["hla_rec"]],
[cwlout(["hla", "hlacaller"], ["string", "null"]),
cwlout(["hla", "call_file"], ["File", "null"])],
"bcbio-vc", ["optitype;env=python2", "razers3=3.5.0", "coincbc"])]
return hla, [["hla", "call_file"]] | [
"def",
"_variant_hla",
"(",
"checkpoints",
")",
":",
"if",
"not",
"checkpoints",
".",
"get",
"(",
"\"hla\"",
")",
":",
"return",
"[",
"]",
",",
"[",
"]",
"hla",
"=",
"[",
"s",
"(",
"\"hla_to_rec\"",
",",
"\"multi-batch\"",
",",
"[",
"[",
"\"hla\"",
"... | Add hla analysis to workflow, if configured. | [
"Add",
"hla",
"analysis",
"to",
"workflow",
"if",
"configured",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/defs.py#L128-L143 | train | 218,982 |
bcbio/bcbio-nextgen | bcbio/cwl/defs.py | variant | def variant(samples):
"""Variant calling workflow definition for CWL generation.
"""
checkpoints = _variant_checkpoints(samples)
if checkpoints["align"]:
align_wf = _alignment(checkpoints)
alignin = [["files"], ["analysis"],
["config", "algorithm", "align_split_size"],
["reference", "fasta", "base"],
["rgnames", "pl"], ["rgnames", "sample"], ["rgnames", "pu"],
["rgnames", "lane"], ["rgnames", "rg"], ["rgnames", "lb"],
["reference", "aligner", "indexes"],
["config", "algorithm", "aligner"],
["config", "algorithm", "trim_reads"],
["config", "algorithm", "adapters"],
["config", "algorithm", "bam_clean"],
["config", "algorithm", "variant_regions"],
["config", "algorithm", "mark_duplicates"]]
if checkpoints["hla"]:
alignin.append(["config", "algorithm", "hlacaller"])
if checkpoints["umi"]:
alignin.append(["config", "algorithm", "umi_type"])
align = [s("alignment_to_rec", "multi-combined", alignin,
[cwlout("alignment_rec", "record")],
"bcbio-vc",
disk={"files": 1.5}, cores=1, no_files=True),
w("alignment", "multi-parallel", align_wf,
[["align_split"], ["process_alignment_rec"],
["work_bam"], ["config", "algorithm", "quality_format"]])]
else:
align = [s("organize_noalign", "multi-parallel",
["files"],
[cwlout(["align_bam"], ["File", "null"], [".bai"]),
cwlout(["work_bam_plus", "disc"], ["File", "null"]),
cwlout(["work_bam_plus", "sr"], ["File", "null"]),
cwlout(["hla", "fastq"], ["File", "null"])],
"bcbio-vc", cores=1)]
align_out = [["rgnames", "sample"], ["align_bam"]]
pp_align, pp_align_out = _postprocess_alignment(checkpoints)
if checkpoints["umi"]:
align_out += [["umi_bam"]]
vc, vc_out = _variant_vc(checkpoints)
sv, sv_out = _variant_sv(checkpoints)
hla, hla_out = _variant_hla(checkpoints)
qc, qc_out = _qc_workflow(checkpoints)
steps = align + pp_align + hla + vc + sv + qc
final_outputs = align_out + pp_align_out + vc_out + hla_out + sv_out + qc_out
return steps, final_outputs | python | def variant(samples):
"""Variant calling workflow definition for CWL generation.
"""
checkpoints = _variant_checkpoints(samples)
if checkpoints["align"]:
align_wf = _alignment(checkpoints)
alignin = [["files"], ["analysis"],
["config", "algorithm", "align_split_size"],
["reference", "fasta", "base"],
["rgnames", "pl"], ["rgnames", "sample"], ["rgnames", "pu"],
["rgnames", "lane"], ["rgnames", "rg"], ["rgnames", "lb"],
["reference", "aligner", "indexes"],
["config", "algorithm", "aligner"],
["config", "algorithm", "trim_reads"],
["config", "algorithm", "adapters"],
["config", "algorithm", "bam_clean"],
["config", "algorithm", "variant_regions"],
["config", "algorithm", "mark_duplicates"]]
if checkpoints["hla"]:
alignin.append(["config", "algorithm", "hlacaller"])
if checkpoints["umi"]:
alignin.append(["config", "algorithm", "umi_type"])
align = [s("alignment_to_rec", "multi-combined", alignin,
[cwlout("alignment_rec", "record")],
"bcbio-vc",
disk={"files": 1.5}, cores=1, no_files=True),
w("alignment", "multi-parallel", align_wf,
[["align_split"], ["process_alignment_rec"],
["work_bam"], ["config", "algorithm", "quality_format"]])]
else:
align = [s("organize_noalign", "multi-parallel",
["files"],
[cwlout(["align_bam"], ["File", "null"], [".bai"]),
cwlout(["work_bam_plus", "disc"], ["File", "null"]),
cwlout(["work_bam_plus", "sr"], ["File", "null"]),
cwlout(["hla", "fastq"], ["File", "null"])],
"bcbio-vc", cores=1)]
align_out = [["rgnames", "sample"], ["align_bam"]]
pp_align, pp_align_out = _postprocess_alignment(checkpoints)
if checkpoints["umi"]:
align_out += [["umi_bam"]]
vc, vc_out = _variant_vc(checkpoints)
sv, sv_out = _variant_sv(checkpoints)
hla, hla_out = _variant_hla(checkpoints)
qc, qc_out = _qc_workflow(checkpoints)
steps = align + pp_align + hla + vc + sv + qc
final_outputs = align_out + pp_align_out + vc_out + hla_out + sv_out + qc_out
return steps, final_outputs | [
"def",
"variant",
"(",
"samples",
")",
":",
"checkpoints",
"=",
"_variant_checkpoints",
"(",
"samples",
")",
"if",
"checkpoints",
"[",
"\"align\"",
"]",
":",
"align_wf",
"=",
"_alignment",
"(",
"checkpoints",
")",
"alignin",
"=",
"[",
"[",
"\"files\"",
"]",
... | Variant calling workflow definition for CWL generation. | [
"Variant",
"calling",
"workflow",
"definition",
"for",
"CWL",
"generation",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/defs.py#L414-L461 | train | 218,983 |
bcbio/bcbio-nextgen | bcbio/structural/plot.py | breakpoints_by_caller | def breakpoints_by_caller(bed_files):
"""
given a list of BED files of the form
chrom start end caller
return a BedTool of breakpoints as each line with
the fourth column the caller with evidence for the breakpoint
chr1 1 10 caller1 -> chr1 1 1 caller1
chr1 1 20 caller2 chr1 1 1 caller2
chr1 10 10 caller1
chr1 20 20 caller2
"""
merged = concat(bed_files)
if not merged:
return []
grouped_start = merged.groupby(g=[1, 2, 2], c=4, o=["distinct"]).filter(lambda r: r.end > r.start).saveas()
grouped_end = merged.groupby(g=[1, 3, 3], c=4, o=["distinct"]).filter(lambda r: r.end > r.start).saveas()
together = concat([grouped_start, grouped_end])
if together:
final = together.expand(c=4)
final = final.sort()
return final | python | def breakpoints_by_caller(bed_files):
"""
given a list of BED files of the form
chrom start end caller
return a BedTool of breakpoints as each line with
the fourth column the caller with evidence for the breakpoint
chr1 1 10 caller1 -> chr1 1 1 caller1
chr1 1 20 caller2 chr1 1 1 caller2
chr1 10 10 caller1
chr1 20 20 caller2
"""
merged = concat(bed_files)
if not merged:
return []
grouped_start = merged.groupby(g=[1, 2, 2], c=4, o=["distinct"]).filter(lambda r: r.end > r.start).saveas()
grouped_end = merged.groupby(g=[1, 3, 3], c=4, o=["distinct"]).filter(lambda r: r.end > r.start).saveas()
together = concat([grouped_start, grouped_end])
if together:
final = together.expand(c=4)
final = final.sort()
return final | [
"def",
"breakpoints_by_caller",
"(",
"bed_files",
")",
":",
"merged",
"=",
"concat",
"(",
"bed_files",
")",
"if",
"not",
"merged",
":",
"return",
"[",
"]",
"grouped_start",
"=",
"merged",
".",
"groupby",
"(",
"g",
"=",
"[",
"1",
",",
"2",
",",
"2",
"... | given a list of BED files of the form
chrom start end caller
return a BedTool of breakpoints as each line with
the fourth column the caller with evidence for the breakpoint
chr1 1 10 caller1 -> chr1 1 1 caller1
chr1 1 20 caller2 chr1 1 1 caller2
chr1 10 10 caller1
chr1 20 20 caller2 | [
"given",
"a",
"list",
"of",
"BED",
"files",
"of",
"the",
"form",
"chrom",
"start",
"end",
"caller",
"return",
"a",
"BedTool",
"of",
"breakpoints",
"as",
"each",
"line",
"with",
"the",
"fourth",
"column",
"the",
"caller",
"with",
"evidence",
"for",
"the",
... | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/plot.py#L17-L37 | train | 218,984 |
bcbio/bcbio-nextgen | bcbio/structural/plot.py | _get_sv_callers | def _get_sv_callers(items):
"""
return a sorted list of all of the structural variant callers run
"""
callers = []
for data in items:
for sv in data.get("sv", []):
callers.append(sv["variantcaller"])
return list(set([x for x in callers if x != "sv-ensemble"])).sort() | python | def _get_sv_callers(items):
"""
return a sorted list of all of the structural variant callers run
"""
callers = []
for data in items:
for sv in data.get("sv", []):
callers.append(sv["variantcaller"])
return list(set([x for x in callers if x != "sv-ensemble"])).sort() | [
"def",
"_get_sv_callers",
"(",
"items",
")",
":",
"callers",
"=",
"[",
"]",
"for",
"data",
"in",
"items",
":",
"for",
"sv",
"in",
"data",
".",
"get",
"(",
"\"sv\"",
",",
"[",
"]",
")",
":",
"callers",
".",
"append",
"(",
"sv",
"[",
"\"variantcaller... | return a sorted list of all of the structural variant callers run | [
"return",
"a",
"sorted",
"list",
"of",
"all",
"of",
"the",
"structural",
"variant",
"callers",
"run"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/plot.py#L39-L47 | train | 218,985 |
bcbio/bcbio-nextgen | bcbio/structural/plot.py | _prioritize_plot_regions | def _prioritize_plot_regions(region_bt, data, out_dir=None):
"""Avoid plotting large numbers of regions due to speed issues. Prioritize most interesting.
XXX For now, just removes larger regions and avoid plotting thousands of regions.
Longer term we'll insert biology-based prioritization.
"""
max_plots = 1000
max_size = 100 * 1000 # 100kb
out_file = "%s-priority%s" % utils.splitext_plus(region_bt.fn)
if out_dir:
out_file = os.path.join(out_dir, os.path.basename(out_file))
num_plots = 0
if not utils.file_uptodate(out_file, region_bt.fn):
with file_transaction(data, out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
for r in region_bt:
if r.stop - r.start < max_size:
if num_plots < max_plots:
num_plots += 1
out_handle.write("%s\t%s\t%s\n" % (r.chrom, r.start, r.stop))
return out_file | python | def _prioritize_plot_regions(region_bt, data, out_dir=None):
"""Avoid plotting large numbers of regions due to speed issues. Prioritize most interesting.
XXX For now, just removes larger regions and avoid plotting thousands of regions.
Longer term we'll insert biology-based prioritization.
"""
max_plots = 1000
max_size = 100 * 1000 # 100kb
out_file = "%s-priority%s" % utils.splitext_plus(region_bt.fn)
if out_dir:
out_file = os.path.join(out_dir, os.path.basename(out_file))
num_plots = 0
if not utils.file_uptodate(out_file, region_bt.fn):
with file_transaction(data, out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
for r in region_bt:
if r.stop - r.start < max_size:
if num_plots < max_plots:
num_plots += 1
out_handle.write("%s\t%s\t%s\n" % (r.chrom, r.start, r.stop))
return out_file | [
"def",
"_prioritize_plot_regions",
"(",
"region_bt",
",",
"data",
",",
"out_dir",
"=",
"None",
")",
":",
"max_plots",
"=",
"1000",
"max_size",
"=",
"100",
"*",
"1000",
"# 100kb",
"out_file",
"=",
"\"%s-priority%s\"",
"%",
"utils",
".",
"splitext_plus",
"(",
... | Avoid plotting large numbers of regions due to speed issues. Prioritize most interesting.
XXX For now, just removes larger regions and avoid plotting thousands of regions.
Longer term we'll insert biology-based prioritization. | [
"Avoid",
"plotting",
"large",
"numbers",
"of",
"regions",
"due",
"to",
"speed",
"issues",
".",
"Prioritize",
"most",
"interesting",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/plot.py#L76-L96 | train | 218,986 |
bcbio/bcbio-nextgen | bcbio/structural/plot.py | by_regions | def by_regions(items):
"""Plot for a union set of combined ensemble regions across all of the data
items.
"""
work_dir = os.path.join(dd.get_work_dir(items[0]), "structural", "coverage")
safe_makedir(work_dir)
out_file = os.path.join(work_dir, "%s-coverage.pdf" % (dd.get_sample_name(items[0])))
if file_exists(out_file):
items = _add_regional_coverage_plot(items, out_file)
else:
bed_files = _get_ensemble_bed_files(items)
merged = bed.merge(bed_files)
breakpoints = breakpoints_by_caller(bed_files)
if merged:
priority_merged = _prioritize_plot_regions(merged, items[0])
out_file = plot_multiple_regions_coverage(items, out_file, items[0],
priority_merged, breakpoints)
items = _add_regional_coverage_plot(items, out_file)
return items | python | def by_regions(items):
"""Plot for a union set of combined ensemble regions across all of the data
items.
"""
work_dir = os.path.join(dd.get_work_dir(items[0]), "structural", "coverage")
safe_makedir(work_dir)
out_file = os.path.join(work_dir, "%s-coverage.pdf" % (dd.get_sample_name(items[0])))
if file_exists(out_file):
items = _add_regional_coverage_plot(items, out_file)
else:
bed_files = _get_ensemble_bed_files(items)
merged = bed.merge(bed_files)
breakpoints = breakpoints_by_caller(bed_files)
if merged:
priority_merged = _prioritize_plot_regions(merged, items[0])
out_file = plot_multiple_regions_coverage(items, out_file, items[0],
priority_merged, breakpoints)
items = _add_regional_coverage_plot(items, out_file)
return items | [
"def",
"by_regions",
"(",
"items",
")",
":",
"work_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dd",
".",
"get_work_dir",
"(",
"items",
"[",
"0",
"]",
")",
",",
"\"structural\"",
",",
"\"coverage\"",
")",
"safe_makedir",
"(",
"work_dir",
")",
"out_... | Plot for a union set of combined ensemble regions across all of the data
items. | [
"Plot",
"for",
"a",
"union",
"set",
"of",
"combined",
"ensemble",
"regions",
"across",
"all",
"of",
"the",
"data",
"items",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/plot.py#L98-L116 | train | 218,987 |
bcbio/bcbio-nextgen | bcbio/structural/shared.py | finalize_sv | def finalize_sv(orig_vcf, data, items):
"""Finalize structural variants, adding effects and splitting if needed.
"""
paired = vcfutils.get_paired(items)
# For paired/somatic, attach combined calls to tumor sample
if paired:
sample_vcf = orig_vcf if paired.tumor_name == dd.get_sample_name(data) else None
else:
sample_vcf = "%s-%s.vcf.gz" % (utils.splitext_plus(orig_vcf)[0], dd.get_sample_name(data))
sample_vcf = vcfutils.select_sample(orig_vcf, dd.get_sample_name(data), sample_vcf, data["config"])
if sample_vcf:
effects_vcf, _ = effects.add_to_vcf(sample_vcf, data, "snpeff")
else:
effects_vcf = None
return effects_vcf or sample_vcf | python | def finalize_sv(orig_vcf, data, items):
"""Finalize structural variants, adding effects and splitting if needed.
"""
paired = vcfutils.get_paired(items)
# For paired/somatic, attach combined calls to tumor sample
if paired:
sample_vcf = orig_vcf if paired.tumor_name == dd.get_sample_name(data) else None
else:
sample_vcf = "%s-%s.vcf.gz" % (utils.splitext_plus(orig_vcf)[0], dd.get_sample_name(data))
sample_vcf = vcfutils.select_sample(orig_vcf, dd.get_sample_name(data), sample_vcf, data["config"])
if sample_vcf:
effects_vcf, _ = effects.add_to_vcf(sample_vcf, data, "snpeff")
else:
effects_vcf = None
return effects_vcf or sample_vcf | [
"def",
"finalize_sv",
"(",
"orig_vcf",
",",
"data",
",",
"items",
")",
":",
"paired",
"=",
"vcfutils",
".",
"get_paired",
"(",
"items",
")",
"# For paired/somatic, attach combined calls to tumor sample",
"if",
"paired",
":",
"sample_vcf",
"=",
"orig_vcf",
"if",
"p... | Finalize structural variants, adding effects and splitting if needed. | [
"Finalize",
"structural",
"variants",
"adding",
"effects",
"and",
"splitting",
"if",
"needed",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/shared.py#L25-L39 | train | 218,988 |
bcbio/bcbio-nextgen | bcbio/structural/shared.py | _get_sv_exclude_file | def _get_sv_exclude_file(items):
"""Retrieve SV file of regions to exclude.
"""
sv_bed = utils.get_in(items[0], ("genome_resources", "variation", "sv_repeat"))
if sv_bed and os.path.exists(sv_bed):
return sv_bed | python | def _get_sv_exclude_file(items):
"""Retrieve SV file of regions to exclude.
"""
sv_bed = utils.get_in(items[0], ("genome_resources", "variation", "sv_repeat"))
if sv_bed and os.path.exists(sv_bed):
return sv_bed | [
"def",
"_get_sv_exclude_file",
"(",
"items",
")",
":",
"sv_bed",
"=",
"utils",
".",
"get_in",
"(",
"items",
"[",
"0",
"]",
",",
"(",
"\"genome_resources\"",
",",
"\"variation\"",
",",
"\"sv_repeat\"",
")",
")",
"if",
"sv_bed",
"and",
"os",
".",
"path",
"... | Retrieve SV file of regions to exclude. | [
"Retrieve",
"SV",
"file",
"of",
"regions",
"to",
"exclude",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/shared.py#L86-L91 | train | 218,989 |
bcbio/bcbio-nextgen | bcbio/structural/shared.py | _get_variant_regions | def _get_variant_regions(items):
"""Retrieve variant regions defined in any of the input items.
"""
return list(filter(lambda x: x is not None,
[tz.get_in(("config", "algorithm", "variant_regions"), data)
for data in items
if tz.get_in(["config", "algorithm", "coverage_interval"], data) != "genome"])) | python | def _get_variant_regions(items):
"""Retrieve variant regions defined in any of the input items.
"""
return list(filter(lambda x: x is not None,
[tz.get_in(("config", "algorithm", "variant_regions"), data)
for data in items
if tz.get_in(["config", "algorithm", "coverage_interval"], data) != "genome"])) | [
"def",
"_get_variant_regions",
"(",
"items",
")",
":",
"return",
"list",
"(",
"filter",
"(",
"lambda",
"x",
":",
"x",
"is",
"not",
"None",
",",
"[",
"tz",
".",
"get_in",
"(",
"(",
"\"config\"",
",",
"\"algorithm\"",
",",
"\"variant_regions\"",
")",
",",
... | Retrieve variant regions defined in any of the input items. | [
"Retrieve",
"variant",
"regions",
"defined",
"in",
"any",
"of",
"the",
"input",
"items",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/shared.py#L93-L99 | train | 218,990 |
bcbio/bcbio-nextgen | bcbio/structural/shared.py | prepare_exclude_file | def prepare_exclude_file(items, base_file, chrom=None):
"""Prepare a BED file for exclusion.
Excludes high depth and centromere regions which contribute to long run times and
false positive structural variant calls.
"""
items = shared.add_highdepth_genome_exclusion(items)
out_file = "%s-exclude%s.bed" % (utils.splitext_plus(base_file)[0], "-%s" % chrom if chrom else "")
if not utils.file_exists(out_file) and not utils.file_exists(out_file + ".gz"):
with shared.bedtools_tmpdir(items[0]):
with file_transaction(items[0], out_file) as tx_out_file:
# Get a bedtool for the full region if no variant regions
want_bedtool = callable.get_ref_bedtool(tz.get_in(["reference", "fasta", "base"], items[0]),
items[0]["config"], chrom)
want_bedtool = pybedtools.BedTool(shared.subset_variant_regions(want_bedtool.saveas().fn,
chrom, tx_out_file, items))
sv_exclude_bed = _get_sv_exclude_file(items)
if sv_exclude_bed and len(want_bedtool) > 0:
want_bedtool = want_bedtool.subtract(sv_exclude_bed, nonamecheck=True).saveas()
full_bedtool = callable.get_ref_bedtool(tz.get_in(["reference", "fasta", "base"], items[0]),
items[0]["config"])
if len(want_bedtool) > 0:
full_bedtool.subtract(want_bedtool, nonamecheck=True).saveas(tx_out_file)
else:
full_bedtool.saveas(tx_out_file)
return out_file | python | def prepare_exclude_file(items, base_file, chrom=None):
"""Prepare a BED file for exclusion.
Excludes high depth and centromere regions which contribute to long run times and
false positive structural variant calls.
"""
items = shared.add_highdepth_genome_exclusion(items)
out_file = "%s-exclude%s.bed" % (utils.splitext_plus(base_file)[0], "-%s" % chrom if chrom else "")
if not utils.file_exists(out_file) and not utils.file_exists(out_file + ".gz"):
with shared.bedtools_tmpdir(items[0]):
with file_transaction(items[0], out_file) as tx_out_file:
# Get a bedtool for the full region if no variant regions
want_bedtool = callable.get_ref_bedtool(tz.get_in(["reference", "fasta", "base"], items[0]),
items[0]["config"], chrom)
want_bedtool = pybedtools.BedTool(shared.subset_variant_regions(want_bedtool.saveas().fn,
chrom, tx_out_file, items))
sv_exclude_bed = _get_sv_exclude_file(items)
if sv_exclude_bed and len(want_bedtool) > 0:
want_bedtool = want_bedtool.subtract(sv_exclude_bed, nonamecheck=True).saveas()
full_bedtool = callable.get_ref_bedtool(tz.get_in(["reference", "fasta", "base"], items[0]),
items[0]["config"])
if len(want_bedtool) > 0:
full_bedtool.subtract(want_bedtool, nonamecheck=True).saveas(tx_out_file)
else:
full_bedtool.saveas(tx_out_file)
return out_file | [
"def",
"prepare_exclude_file",
"(",
"items",
",",
"base_file",
",",
"chrom",
"=",
"None",
")",
":",
"items",
"=",
"shared",
".",
"add_highdepth_genome_exclusion",
"(",
"items",
")",
"out_file",
"=",
"\"%s-exclude%s.bed\"",
"%",
"(",
"utils",
".",
"splitext_plus"... | Prepare a BED file for exclusion.
Excludes high depth and centromere regions which contribute to long run times and
false positive structural variant calls. | [
"Prepare",
"a",
"BED",
"file",
"for",
"exclusion",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/shared.py#L112-L137 | train | 218,991 |
bcbio/bcbio-nextgen | bcbio/structural/shared.py | exclude_by_ends | def exclude_by_ends(in_file, exclude_file, data, in_params=None):
"""Exclude calls based on overlap of the ends with exclusion regions.
Removes structural variants with either end being in a repeat: a large
source of false positives.
Parameters tuned based on removal of LCR overlapping false positives in DREAM
synthetic 3 data.
"""
params = {"end_buffer": 50,
"rpt_pct": 0.9,
"total_rpt_pct": 0.2,
"sv_pct": 0.5}
if in_params:
params.update(in_params)
assert in_file.endswith(".bed")
out_file = "%s-norepeats%s" % utils.splitext_plus(in_file)
to_filter = collections.defaultdict(list)
removed = 0
if not utils.file_uptodate(out_file, in_file):
with file_transaction(data, out_file) as tx_out_file:
with shared.bedtools_tmpdir(data):
for coord, end_name in [(1, "end1"), (2, "end2")]:
base, ext = utils.splitext_plus(tx_out_file)
end_file = _create_end_file(in_file, coord, params, "%s-%s%s" % (base, end_name, ext))
to_filter = _find_to_filter(end_file, exclude_file, params, to_filter)
with open(tx_out_file, "w") as out_handle:
with open(in_file) as in_handle:
for line in in_handle:
key = "%s:%s-%s" % tuple(line.strip().split("\t")[:3])
total_rpt_size = sum(to_filter.get(key, [0]))
if total_rpt_size <= (params["total_rpt_pct"] * params["end_buffer"]):
out_handle.write(line)
else:
removed += 1
return out_file, removed | python | def exclude_by_ends(in_file, exclude_file, data, in_params=None):
"""Exclude calls based on overlap of the ends with exclusion regions.
Removes structural variants with either end being in a repeat: a large
source of false positives.
Parameters tuned based on removal of LCR overlapping false positives in DREAM
synthetic 3 data.
"""
params = {"end_buffer": 50,
"rpt_pct": 0.9,
"total_rpt_pct": 0.2,
"sv_pct": 0.5}
if in_params:
params.update(in_params)
assert in_file.endswith(".bed")
out_file = "%s-norepeats%s" % utils.splitext_plus(in_file)
to_filter = collections.defaultdict(list)
removed = 0
if not utils.file_uptodate(out_file, in_file):
with file_transaction(data, out_file) as tx_out_file:
with shared.bedtools_tmpdir(data):
for coord, end_name in [(1, "end1"), (2, "end2")]:
base, ext = utils.splitext_plus(tx_out_file)
end_file = _create_end_file(in_file, coord, params, "%s-%s%s" % (base, end_name, ext))
to_filter = _find_to_filter(end_file, exclude_file, params, to_filter)
with open(tx_out_file, "w") as out_handle:
with open(in_file) as in_handle:
for line in in_handle:
key = "%s:%s-%s" % tuple(line.strip().split("\t")[:3])
total_rpt_size = sum(to_filter.get(key, [0]))
if total_rpt_size <= (params["total_rpt_pct"] * params["end_buffer"]):
out_handle.write(line)
else:
removed += 1
return out_file, removed | [
"def",
"exclude_by_ends",
"(",
"in_file",
",",
"exclude_file",
",",
"data",
",",
"in_params",
"=",
"None",
")",
":",
"params",
"=",
"{",
"\"end_buffer\"",
":",
"50",
",",
"\"rpt_pct\"",
":",
"0.9",
",",
"\"total_rpt_pct\"",
":",
"0.2",
",",
"\"sv_pct\"",
"... | Exclude calls based on overlap of the ends with exclusion regions.
Removes structural variants with either end being in a repeat: a large
source of false positives.
Parameters tuned based on removal of LCR overlapping false positives in DREAM
synthetic 3 data. | [
"Exclude",
"calls",
"based",
"on",
"overlap",
"of",
"the",
"ends",
"with",
"exclusion",
"regions",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/shared.py#L139-L174 | train | 218,992 |
bcbio/bcbio-nextgen | bcbio/structural/shared.py | _find_to_filter | def _find_to_filter(in_file, exclude_file, params, to_exclude):
"""Identify regions in the end file that overlap the exclusion file.
We look for ends with a large percentage in a repeat or where the end contains
an entire repeat.
"""
for feat in pybedtools.BedTool(in_file).intersect(pybedtools.BedTool(exclude_file), wao=True, nonamecheck=True):
us_chrom, us_start, us_end, name, other_chrom, other_start, other_end, overlap = feat.fields
if float(overlap) > 0:
other_size = float(other_end) - float(other_start)
other_pct = float(overlap) / other_size
us_pct = float(overlap) / (float(us_end) - float(us_start))
if us_pct > params["sv_pct"] or (other_pct > params["rpt_pct"]):
to_exclude[name].append(float(overlap))
return to_exclude | python | def _find_to_filter(in_file, exclude_file, params, to_exclude):
"""Identify regions in the end file that overlap the exclusion file.
We look for ends with a large percentage in a repeat or where the end contains
an entire repeat.
"""
for feat in pybedtools.BedTool(in_file).intersect(pybedtools.BedTool(exclude_file), wao=True, nonamecheck=True):
us_chrom, us_start, us_end, name, other_chrom, other_start, other_end, overlap = feat.fields
if float(overlap) > 0:
other_size = float(other_end) - float(other_start)
other_pct = float(overlap) / other_size
us_pct = float(overlap) / (float(us_end) - float(us_start))
if us_pct > params["sv_pct"] or (other_pct > params["rpt_pct"]):
to_exclude[name].append(float(overlap))
return to_exclude | [
"def",
"_find_to_filter",
"(",
"in_file",
",",
"exclude_file",
",",
"params",
",",
"to_exclude",
")",
":",
"for",
"feat",
"in",
"pybedtools",
".",
"BedTool",
"(",
"in_file",
")",
".",
"intersect",
"(",
"pybedtools",
".",
"BedTool",
"(",
"exclude_file",
")",
... | Identify regions in the end file that overlap the exclusion file.
We look for ends with a large percentage in a repeat or where the end contains
an entire repeat. | [
"Identify",
"regions",
"in",
"the",
"end",
"file",
"that",
"overlap",
"the",
"exclusion",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/shared.py#L176-L190 | train | 218,993 |
bcbio/bcbio-nextgen | bcbio/structural/shared.py | get_sv_chroms | def get_sv_chroms(items, exclude_file):
"""Retrieve chromosomes to process on, avoiding extra skipped chromosomes.
"""
exclude_regions = {}
for region in pybedtools.BedTool(exclude_file):
if int(region.start) == 0:
exclude_regions[region.chrom] = int(region.end)
out = []
with pysam.Samfile(dd.get_align_bam(items[0]) or dd.get_work_bam(items[0]))as pysam_work_bam:
for chrom, length in zip(pysam_work_bam.references, pysam_work_bam.lengths):
exclude_length = exclude_regions.get(chrom, 0)
if exclude_length < length:
out.append(chrom)
return out | python | def get_sv_chroms(items, exclude_file):
"""Retrieve chromosomes to process on, avoiding extra skipped chromosomes.
"""
exclude_regions = {}
for region in pybedtools.BedTool(exclude_file):
if int(region.start) == 0:
exclude_regions[region.chrom] = int(region.end)
out = []
with pysam.Samfile(dd.get_align_bam(items[0]) or dd.get_work_bam(items[0]))as pysam_work_bam:
for chrom, length in zip(pysam_work_bam.references, pysam_work_bam.lengths):
exclude_length = exclude_regions.get(chrom, 0)
if exclude_length < length:
out.append(chrom)
return out | [
"def",
"get_sv_chroms",
"(",
"items",
",",
"exclude_file",
")",
":",
"exclude_regions",
"=",
"{",
"}",
"for",
"region",
"in",
"pybedtools",
".",
"BedTool",
"(",
"exclude_file",
")",
":",
"if",
"int",
"(",
"region",
".",
"start",
")",
"==",
"0",
":",
"e... | Retrieve chromosomes to process on, avoiding extra skipped chromosomes. | [
"Retrieve",
"chromosomes",
"to",
"process",
"on",
"avoiding",
"extra",
"skipped",
"chromosomes",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/shared.py#L209-L222 | train | 218,994 |
bcbio/bcbio-nextgen | bcbio/structural/shared.py | _extract_split_and_discordants | def _extract_split_and_discordants(in_bam, work_dir, data):
"""Retrieve split-read alignments from input BAM file.
"""
sr_file = os.path.join(work_dir, "%s-sr.bam" % os.path.splitext(os.path.basename(in_bam))[0])
disc_file = os.path.join(work_dir, "%s-disc.bam" % os.path.splitext(os.path.basename(in_bam))[0])
if not utils.file_exists(sr_file) or not utils.file_exists(disc_file):
with file_transaction(data, sr_file) as tx_sr_file:
with file_transaction(data, disc_file) as tx_disc_file:
cores = dd.get_num_cores(data)
ref_file = dd.get_ref_file(data)
cmd = ("extract-sv-reads -e --threads {cores} -T {ref_file} "
"-i {in_bam} -s {tx_sr_file} -d {tx_disc_file}")
do.run(cmd.format(**locals()), "extract split and discordant reads", data)
for fname in [sr_file, disc_file]:
bam.index(fname, data["config"])
return sr_file, disc_file | python | def _extract_split_and_discordants(in_bam, work_dir, data):
"""Retrieve split-read alignments from input BAM file.
"""
sr_file = os.path.join(work_dir, "%s-sr.bam" % os.path.splitext(os.path.basename(in_bam))[0])
disc_file = os.path.join(work_dir, "%s-disc.bam" % os.path.splitext(os.path.basename(in_bam))[0])
if not utils.file_exists(sr_file) or not utils.file_exists(disc_file):
with file_transaction(data, sr_file) as tx_sr_file:
with file_transaction(data, disc_file) as tx_disc_file:
cores = dd.get_num_cores(data)
ref_file = dd.get_ref_file(data)
cmd = ("extract-sv-reads -e --threads {cores} -T {ref_file} "
"-i {in_bam} -s {tx_sr_file} -d {tx_disc_file}")
do.run(cmd.format(**locals()), "extract split and discordant reads", data)
for fname in [sr_file, disc_file]:
bam.index(fname, data["config"])
return sr_file, disc_file | [
"def",
"_extract_split_and_discordants",
"(",
"in_bam",
",",
"work_dir",
",",
"data",
")",
":",
"sr_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"work_dir",
",",
"\"%s-sr.bam\"",
"%",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
... | Retrieve split-read alignments from input BAM file. | [
"Retrieve",
"split",
"-",
"read",
"alignments",
"from",
"input",
"BAM",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/shared.py#L226-L241 | train | 218,995 |
bcbio/bcbio-nextgen | bcbio/structural/shared.py | find_existing_split_discordants | def find_existing_split_discordants(data):
"""Check for pre-calculated split reads and discordants done as part of alignment streaming.
"""
in_bam = dd.get_align_bam(data)
sr_file = "%s-sr.bam" % os.path.splitext(in_bam)[0]
disc_file = "%s-disc.bam" % os.path.splitext(in_bam)[0]
if utils.file_exists(sr_file) and utils.file_exists(disc_file):
return sr_file, disc_file
else:
sr_file = dd.get_sr_bam(data)
disc_file = dd.get_disc_bam(data)
if sr_file and utils.file_exists(sr_file) and disc_file and utils.file_exists(disc_file):
return sr_file, disc_file
else:
return None, None | python | def find_existing_split_discordants(data):
"""Check for pre-calculated split reads and discordants done as part of alignment streaming.
"""
in_bam = dd.get_align_bam(data)
sr_file = "%s-sr.bam" % os.path.splitext(in_bam)[0]
disc_file = "%s-disc.bam" % os.path.splitext(in_bam)[0]
if utils.file_exists(sr_file) and utils.file_exists(disc_file):
return sr_file, disc_file
else:
sr_file = dd.get_sr_bam(data)
disc_file = dd.get_disc_bam(data)
if sr_file and utils.file_exists(sr_file) and disc_file and utils.file_exists(disc_file):
return sr_file, disc_file
else:
return None, None | [
"def",
"find_existing_split_discordants",
"(",
"data",
")",
":",
"in_bam",
"=",
"dd",
".",
"get_align_bam",
"(",
"data",
")",
"sr_file",
"=",
"\"%s-sr.bam\"",
"%",
"os",
".",
"path",
".",
"splitext",
"(",
"in_bam",
")",
"[",
"0",
"]",
"disc_file",
"=",
"... | Check for pre-calculated split reads and discordants done as part of alignment streaming. | [
"Check",
"for",
"pre",
"-",
"calculated",
"split",
"reads",
"and",
"discordants",
"done",
"as",
"part",
"of",
"alignment",
"streaming",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/shared.py#L243-L257 | train | 218,996 |
bcbio/bcbio-nextgen | bcbio/structural/shared.py | get_split_discordants | def get_split_discordants(data, work_dir):
"""Retrieve split and discordant reads, potentially calculating with extract_sv_reads as needed.
"""
align_bam = dd.get_align_bam(data)
sr_bam, disc_bam = find_existing_split_discordants(data)
if not sr_bam:
work_dir = (work_dir if not os.access(os.path.dirname(align_bam), os.W_OK | os.X_OK)
else os.path.dirname(align_bam))
sr_bam, disc_bam = _extract_split_and_discordants(align_bam, work_dir, data)
return sr_bam, disc_bam | python | def get_split_discordants(data, work_dir):
"""Retrieve split and discordant reads, potentially calculating with extract_sv_reads as needed.
"""
align_bam = dd.get_align_bam(data)
sr_bam, disc_bam = find_existing_split_discordants(data)
if not sr_bam:
work_dir = (work_dir if not os.access(os.path.dirname(align_bam), os.W_OK | os.X_OK)
else os.path.dirname(align_bam))
sr_bam, disc_bam = _extract_split_and_discordants(align_bam, work_dir, data)
return sr_bam, disc_bam | [
"def",
"get_split_discordants",
"(",
"data",
",",
"work_dir",
")",
":",
"align_bam",
"=",
"dd",
".",
"get_align_bam",
"(",
"data",
")",
"sr_bam",
",",
"disc_bam",
"=",
"find_existing_split_discordants",
"(",
"data",
")",
"if",
"not",
"sr_bam",
":",
"work_dir",... | Retrieve split and discordant reads, potentially calculating with extract_sv_reads as needed. | [
"Retrieve",
"split",
"and",
"discordant",
"reads",
"potentially",
"calculating",
"with",
"extract_sv_reads",
"as",
"needed",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/shared.py#L259-L268 | train | 218,997 |
bcbio/bcbio-nextgen | bcbio/structural/shared.py | get_cur_batch | def get_cur_batch(items):
"""Retrieve name of the batch shared between all items in a group.
"""
batches = []
for data in items:
batch = tz.get_in(["metadata", "batch"], data, [])
batches.append(set(batch) if isinstance(batch, (list, tuple)) else set([batch]))
combo_batches = reduce(lambda b1, b2: b1.intersection(b2), batches)
if len(combo_batches) == 1:
return combo_batches.pop()
elif len(combo_batches) == 0:
return None
else:
raise ValueError("Found multiple overlapping batches: %s -- %s" % (combo_batches, batches)) | python | def get_cur_batch(items):
"""Retrieve name of the batch shared between all items in a group.
"""
batches = []
for data in items:
batch = tz.get_in(["metadata", "batch"], data, [])
batches.append(set(batch) if isinstance(batch, (list, tuple)) else set([batch]))
combo_batches = reduce(lambda b1, b2: b1.intersection(b2), batches)
if len(combo_batches) == 1:
return combo_batches.pop()
elif len(combo_batches) == 0:
return None
else:
raise ValueError("Found multiple overlapping batches: %s -- %s" % (combo_batches, batches)) | [
"def",
"get_cur_batch",
"(",
"items",
")",
":",
"batches",
"=",
"[",
"]",
"for",
"data",
"in",
"items",
":",
"batch",
"=",
"tz",
".",
"get_in",
"(",
"[",
"\"metadata\"",
",",
"\"batch\"",
"]",
",",
"data",
",",
"[",
"]",
")",
"batches",
".",
"appen... | Retrieve name of the batch shared between all items in a group. | [
"Retrieve",
"name",
"of",
"the",
"batch",
"shared",
"between",
"all",
"items",
"in",
"a",
"group",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/shared.py#L270-L283 | train | 218,998 |
bcbio/bcbio-nextgen | bcbio/structural/shared.py | calc_paired_insert_stats | def calc_paired_insert_stats(in_bam, nsample=1000000):
"""Retrieve statistics for paired end read insert distances.
"""
dists = []
n = 0
with pysam.Samfile(in_bam, "rb") as in_pysam:
for read in in_pysam:
if read.is_proper_pair and read.is_read1:
n += 1
dists.append(abs(read.isize))
if n >= nsample:
break
return insert_size_stats(dists) | python | def calc_paired_insert_stats(in_bam, nsample=1000000):
"""Retrieve statistics for paired end read insert distances.
"""
dists = []
n = 0
with pysam.Samfile(in_bam, "rb") as in_pysam:
for read in in_pysam:
if read.is_proper_pair and read.is_read1:
n += 1
dists.append(abs(read.isize))
if n >= nsample:
break
return insert_size_stats(dists) | [
"def",
"calc_paired_insert_stats",
"(",
"in_bam",
",",
"nsample",
"=",
"1000000",
")",
":",
"dists",
"=",
"[",
"]",
"n",
"=",
"0",
"with",
"pysam",
".",
"Samfile",
"(",
"in_bam",
",",
"\"rb\"",
")",
"as",
"in_pysam",
":",
"for",
"read",
"in",
"in_pysam... | Retrieve statistics for paired end read insert distances. | [
"Retrieve",
"statistics",
"for",
"paired",
"end",
"read",
"insert",
"distances",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/shared.py#L307-L319 | train | 218,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.