idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
30,000
def runner ( parallel , config ) : def run_parallel ( fn_name , items ) : items = [ x for x in items if x is not None ] if len ( items ) == 0 : return [ ] items = diagnostics . track_parallel ( items , fn_name ) fn , fn_name = ( fn_name , fn_name . __name__ ) if callable ( fn_name ) else ( get_fn ( fn_name , parallel )...
Run functions provided by string name on multiple cores on the current machine .
30,001
def zeromq_aware_logging ( f ) : @ functools . wraps ( f ) def wrapper ( * args , ** kwargs ) : config = None for arg in args : if config_utils . is_std_config_arg ( arg ) : config = arg break elif config_utils . is_nested_config_arg ( arg ) : config = arg [ "config" ] elif isinstance ( arg , ( list , tuple ) ) and con...
Ensure multiprocessing logging uses ZeroMQ queues .
30,002
def run_multicore ( fn , items , config , parallel = None ) : if len ( items ) == 0 : return [ ] if parallel is None or "num_jobs" not in parallel : if parallel is None : parallel = { "type" : "local" , "cores" : config [ "algorithm" ] . get ( "num_cores" , 1 ) } sysinfo = system . get_info ( { } , parallel ) parallel ...
Run the function using multiple cores on the given items to process .
30,003
def _add_umis_with_fastp ( read_fq , umi_fq , out_fq , cores ) : with utils . open_gzipsafe ( umi_fq ) as in_handle : in_handle . readline ( ) umi_size = len ( in_handle . readline ( ) . strip ( ) ) cmd = ( "fastp -Q -A -L -G -w 1 --in1 {read_fq} --in2 {umi_fq} " "--umi --umi_prefix UMI --umi_loc read2 --umi_len {umi_s...
Add UMIs to reads from separate UMI file using fastp .
30,004
def _find_umi ( files ) : base = os . path . basename ( _commonprefix ( files ) ) def _file_ext ( f ) : exts = utils . splitext_plus ( os . path . basename ( f ) . replace ( base , "" ) ) [ 0 ] . split ( "_" ) exts = [ x for x in exts if x ] return exts [ 0 ] exts = dict ( [ ( _file_ext ( f ) , f ) for f in files ] ) i...
Find UMI file using different naming schemes .
30,005
def _commonprefix ( files ) : out = os . path . commonprefix ( files ) out = out . rstrip ( "_R" ) out = out . rstrip ( "_I" ) out = out . rstrip ( "_" ) return out
Retrieve a common prefix for files without extra _R1 _I1 extensions .
30,006
def cutoff_w_expression ( vcf_file , expression , data , name = "+" , filterext = "" , extra_cmd = "" , limit_regions = "variant_regions" ) : base , ext = utils . splitext_plus ( vcf_file ) out_file = "{base}-filter{filterext}{ext}" . format ( ** locals ( ) ) if not utils . file_exists ( out_file ) : with file_transact...
Perform cutoff - based soft filtering using bcftools expressions like %QUAL < 20 || DP < 4 .
30,007
def _freebayes_custom ( in_file , ref_file , data ) : if vcfutils . get_paired_phenotype ( data ) : return None config = data [ "config" ] bv_ver = programs . get_version ( "bcbio_variation" , config = config ) if LooseVersion ( bv_ver ) < LooseVersion ( "0.1.1" ) : return None out_file = "%s-filter%s" % os . path . sp...
Custom FreeBayes filtering using bcbio . variation tuned to human NA12878 results .
30,008
def _freebayes_cutoff ( in_file , data ) : if not vcfutils . vcf_has_variants ( in_file ) : base , ext = utils . splitext_plus ( in_file ) out_file = "{base}-filter{ext}" . format ( ** locals ( ) ) if not utils . file_exists ( out_file ) : shutil . copy ( in_file , out_file ) if out_file . endswith ( ".vcf.gz" ) : out_...
Perform filtering of FreeBayes results flagging low confidence calls .
30,009
def _calc_vcf_stats ( in_file ) : out_file = "%s-stats.yaml" % utils . splitext_plus ( in_file ) [ 0 ] if not utils . file_exists ( out_file ) : stats = { "avg_depth" : _average_called_depth ( in_file ) } with open ( out_file , "w" ) as out_handle : yaml . safe_dump ( stats , out_handle , default_flow_style = False , a...
Calculate statistics on VCF for filtering saving to a file for quick re - runs .
30,010
def _average_called_depth ( in_file ) : import cyvcf2 depths = [ ] for rec in cyvcf2 . VCF ( str ( in_file ) ) : d = rec . INFO . get ( "DP" ) if d is not None : depths . append ( int ( d ) ) if len ( depths ) > 0 : return int ( math . ceil ( numpy . mean ( depths ) ) ) else : return 0
Retrieve the average depth of called reads in the provided VCF .
30,011
def platypus ( in_file , data ) : filters = ( '(FR[0] <= 0.5 && TC < 4 && %QUAL < 20) || ' '(TC < 13 && %QUAL < 10) || ' '(FR[0] > 0.5 && TC < 4 && %QUAL < 50)' ) limit_regions = "variant_regions" if not vcfutils . is_gvcf_file ( in_file ) else None return cutoff_w_expression ( in_file , filters , data , name = "PlatQu...
Filter Platypus calls removing Q20 filter and replacing with depth and quality based filter .
30,012
def gatk_snp_cutoff ( in_file , data ) : filters = [ "MQRankSum < -12.5" , "ReadPosRankSum < -8.0" ] variantcaller = utils . get_in ( data , ( "config" , "algorithm" , "variantcaller" ) ) if variantcaller not in [ "gatk-haplotype" , "haplotyper" ] : filters . append ( "HaplotypeScore > 13.0" ) if not ( vcfutils . is_gv...
Perform cutoff - based soft filtering on GATK SNPs using best - practice recommendations .
30,013
def random_regions ( base , n , size ) : spread = size // 2 base_info = collections . defaultdict ( list ) for space , start , end in base : base_info [ space ] . append ( start + spread ) base_info [ space ] . append ( end - spread ) regions = [ ] for _ in range ( n ) : space = random . choice ( base_info . keys ( ) )...
Generate n random regions of size in the provided base spread .
30,014
def all_regions ( self ) : regions = [ ] for sq in self . _bam . header [ "SQ" ] : regions . append ( ( sq [ "SN" ] , 1 , int ( sq [ "LN" ] ) ) ) return regions
Get a tuple of all chromosome start and end regions .
30,015
def read_count ( self , space , start , end ) : read_counts = 0 for read in self . _bam . fetch ( space , start , end ) : read_counts += 1 return self . _normalize ( read_counts , self . _total )
Retrieve the normalized read count in the provided region .
30,016
def coverage_pileup ( self , space , start , end ) : return ( ( col . pos , self . _normalize ( col . n , self . _total ) ) for col in self . _bam . pileup ( space , start , end ) )
Retrieve pileup coverage across a specified region .
30,017
def _prepare_summary ( evolve_file , ssm_file , cnv_file , work_dir , somatic_info ) : out_file = os . path . join ( work_dir , "%s-phylowgs.txt" % somatic_info . tumor_name ) if not utils . file_uptodate ( out_file , evolve_file ) : with file_transaction ( somatic_info . tumor_data , out_file ) as tx_out_file : with o...
Prepare a summary with gene - labelled heterogeneity from PhyloWGS predictions .
30,018
def _gids_to_genes ( gids , ssm_locs , cnv_ssms , data ) : locs = collections . defaultdict ( set ) for gid in gids : cur_locs = [ ] try : cur_locs . append ( ssm_locs [ gid ] ) except KeyError : for ssm_loc in cnv_ssms . get ( gid , [ ] ) : cur_locs . append ( ssm_locs [ ssm_loc ] ) for chrom , pos in cur_locs : locs ...
Convert support ids for SNPs and SSMs into associated genes .
30,019
def _evolve_reader ( in_file ) : cur_id_list = None cur_tree = None with open ( in_file ) as in_handle : for line in in_handle : if line . startswith ( "id," ) : if cur_id_list : yield cur_id_list , cur_tree cur_id_list = [ ] cur_tree = None elif cur_tree is not None : if line . strip ( ) and not line . startswith ( "N...
Generate a list of region IDs and trees from a top_k_trees evolve . py file .
30,020
def _read_cnv_ssms ( in_file ) : out = { } with open ( in_file ) as in_handle : in_handle . readline ( ) for line in in_handle : parts = line . strip ( ) . split ( ) if len ( parts ) > 3 : cnvid , _ , _ , ssms = parts out [ cnvid ] = [ x . split ( "," ) [ 0 ] for x in ssms . split ( ";" ) ] return out
Map CNVs to associated SSMs
30,021
def _read_ssm_locs ( in_file ) : out = { } with open ( in_file ) as in_handle : in_handle . readline ( ) for line in in_handle : sid , loc = line . split ( ) [ : 2 ] chrom , pos = loc . split ( "_" ) out [ sid ] = ( chrom , int ( pos ) ) return out
Map SSMs to chromosomal locations .
30,022
def _run_evolve ( ssm_file , cnv_file , work_dir , data ) : exe = os . path . join ( os . path . dirname ( sys . executable ) , "evolve.py" ) assert os . path . exists ( exe ) , "Could not find evolve script for PhyloWGS runs." out_dir = os . path . join ( work_dir , "evolve" ) out_file = os . path . join ( out_dir , "...
Run evolve . py to infer subclonal composition .
30,023
def _prep_inputs ( vrn_info , cnv_info , somatic_info , work_dir , config ) : exe = os . path . join ( os . path . dirname ( sys . executable ) , "create_phylowgs_inputs.py" ) assert os . path . exists ( exe ) , "Could not find input prep script for PhyloWGS runs." ssm_file = os . path . join ( work_dir , "ssm_data.txt...
Prepare inputs for running PhyloWGS from variant and CNV calls .
30,024
def _prep_cnv_file ( in_file , work_dir , somatic_info ) : out_file = os . path . join ( work_dir , "%s-prep%s" % utils . splitext_plus ( os . path . basename ( in_file ) ) ) if not utils . file_uptodate ( out_file , in_file ) : with file_transaction ( somatic_info . tumor_data , out_file ) as tx_out_file : with open (...
Prepare Battenberg CNV file for ingest by PhyloWGS .
30,025
def _prep_vrn_file ( in_file , vcaller , work_dir , somatic_info , ignore_file , config ) : if vcaller . startswith ( "vardict" ) : variant_type = "vardict" elif vcaller == "mutect" : variant_type = "mutect-smchet" else : raise ValueError ( "Unexpected variant caller for PhyloWGS prep: %s" % vcaller ) out_file = os . p...
Create a variant file to feed into the PhyloWGS prep script limiting records .
30,026
def run_prepare ( * data ) : out_dir = os . path . join ( dd . get_work_dir ( data [ 0 ] [ 0 ] ) , "seqcluster" , "prepare" ) out_dir = os . path . abspath ( safe_makedir ( out_dir ) ) prepare_dir = os . path . join ( out_dir , "prepare" ) tools = dd . get_expression_caller ( data [ 0 ] [ 0 ] ) if len ( tools ) == 0 : ...
Run seqcluster prepare to merge all samples in one file
30,027
def run_align ( * data ) : work_dir = dd . get_work_dir ( data [ 0 ] [ 0 ] ) out_dir = op . join ( work_dir , "seqcluster" , "prepare" ) seq_out = op . join ( out_dir , "seqs.fastq" ) bam_dir = op . join ( work_dir , "align" ) new_bam_file = op . join ( bam_dir , "seqs.bam" ) tools = dd . get_expression_caller ( data [...
Prepare data to run alignment step only once for each project
30,028
def run_cluster ( * data ) : sample = data [ 0 ] [ 0 ] tools = dd . get_expression_caller ( data [ 0 ] [ 0 ] ) work_dir = dd . get_work_dir ( sample ) out_dir = op . join ( work_dir , "seqcluster" , "cluster" ) out_dir = op . abspath ( safe_makedir ( out_dir ) ) prepare_dir = op . join ( work_dir , "seqcluster" , "prep...
Run seqcluster cluster to detect smallRNA clusters
30,029
def _cluster ( bam_file , ma_file , out_dir , reference , annotation_file = None ) : seqcluster = op . join ( get_bcbio_bin ( ) , "seqcluster" ) if annotation_file : annotation_file = "-g " + annotation_file else : annotation_file = "" if not file_exists ( op . join ( out_dir , "counts.tsv" ) ) : cmd = ( "{seqcluster} ...
Connect to seqcluster to run cluster with python directly
30,030
def _report ( data , reference ) : seqcluster = op . join ( get_bcbio_bin ( ) , "seqcluster" ) work_dir = dd . get_work_dir ( data ) out_dir = safe_makedir ( os . path . join ( work_dir , "seqcluster" , "report" ) ) out_file = op . join ( out_dir , "seqcluster.db" ) json = op . join ( work_dir , "seqcluster" , "cluster...
Run report of seqcluster to get browser options for results
30,031
def report ( data ) : work_dir = dd . get_work_dir ( data [ 0 ] [ 0 ] ) out_dir = op . join ( work_dir , "report" ) safe_makedir ( out_dir ) summary_file = op . join ( out_dir , "summary.csv" ) with file_transaction ( summary_file ) as out_tx : with open ( out_tx , 'w' ) as out_handle : out_handle . write ( "sample_id,...
Create a Rmd report for small RNAseq analysis
30,032
def _modify_report ( summary_path , out_dir ) : summary_path = op . abspath ( summary_path ) template = op . normpath ( op . join ( op . dirname ( op . realpath ( template_seqcluster . __file__ ) ) , "report.rmd" ) ) content = open ( template ) . read ( ) out_content = string . Template ( content ) . safe_substitute ( ...
Read Rmd template and dump with project path .
30,033
def _make_isomir_counts ( data , srna_type = "seqbuster" , out_dir = None , stem = "" ) : work_dir = dd . get_work_dir ( data [ 0 ] [ 0 ] ) if not out_dir : out_dir = op . join ( work_dir , "mirbase" ) out_novel_isomir = append_stem ( op . join ( out_dir , "counts.tsv" ) , stem ) out_novel_mirna = append_stem ( op . jo...
Parse miraligner files to create count matrix .
30,034
def _split_regions ( chrom , start , end ) : window_size = 1e5 if end - start < window_size * 5 : return [ ( chrom , start , end ) ] else : out = [ ] for r in pybedtools . BedTool ( ) . window_maker ( w = window_size , b = pybedtools . BedTool ( "%s\t%s\t%s" % ( chrom , start , end ) , from_string = True ) ) : out . ap...
Split regions longer than 100kb into smaller sections .
30,035
def plot_multiple_regions_coverage ( samples , out_file , data , region_bed = None , stem_bed = None ) : 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 isi...
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
30,036
def _config_params ( base_config , assoc_files , region , out_file , items ) : 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 ( ite...
Add parameters based on configuration variables associated files and genomic regions .
30,037
def _mutect_call_prep ( align_bams , items , ref_file , assoc_files , region = None , out_file = None ) : 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_con...
Preparation work for MuTect .
30,038
def _SID_call_prep ( align_bams , items , ref_file , assoc_files , region = None , out_file = None ) : 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" ] paired = vcfutils . get_paired_b...
Preparation work for SomaticIndelDetector .
30,039
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 ( 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...
Adjust MuTect output to match other callers .
30,040
def prep_gemini_db ( fnames , call_info , samples , extras ) : 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 , na...
Prepare a gemini database from VCF inputs prepared with snpEff .
30,041
def _back_compatible_gemini ( conf_files , data ) : 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...
Provide old install directory for configuration with GEMINI supplied tidy VCFs .
30,042
def run_vcfanno ( vcf_file , data , decomposed = False ) : 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 ...
Run vcfanno providing annotations from external databases if needed .
30,043
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 ( samples ) return { "gender" : { "male" : 1 , "female" : 2 , "unknown" : 0 } . get ( get_gender ( data ) ) , "individual_id" : dd . get_sample_name ( data ) , "...
Retrieve all PED info from metadata
30,044
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 . path . join ( out_dir , os . path . basename ( out_file ) ) sample_ped_lines = { } header = [ "#Family_ID" , "Individual_ID" , "Paternal_ID" , "Maternal_ID" , "Sex" ,...
Create a GEMINI - compatible PED file including gender family and phenotype information .
30,045
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 . startswith ( "#" ) : count += 1 if count > small_thresh : return False return True
Check for small VCFs which we want to analyze quicker .
30,046
def get_multisample_vcf ( fnames , name , caller , data ) : 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 ...
Retrieve a multiple sample VCF file in a standard location .
30,047
def get_gemini_files ( data ) : try : from gemini import annotations , config except ImportError : return { } return { "base" : config . read_gemini_config ( ) [ "annotation_dir" ] , "files" : annotations . get_anno_files ( ) . values ( ) }
Enumerate available gemini data files in a standard installation .
30,048
def _group_by_batches ( samples , check_fn ) : 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 :...
Group data items into batches providing details to retrieve results .
30,049
def prep_db_parallel ( samples , parallel_fn ) : 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 (...
Prepares gemini databases in parallel handling jointly called populations .
30,050
def _get_s3_files ( local_dir , file_info , params ) : 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...
Retrieve s3 files to local directory handling STORMSeq inputs .
30,051
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 ) : 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...
gzip a fastq file if it is not already gzipped handling conversion from bzip to gzipped files
30,052
def _pipeline_needs_fastq ( config , data ) : aligner = config [ "algorithm" ] . get ( "aligner" ) support_bam = aligner in alignment . metadata . get ( "support_bam" , [ ] ) return aligner and not support_bam
Determine if the pipeline can proceed with a BAM file or needs fastq conversion .
30,053
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 .
30,054
def merge ( files , out_file , config ) : 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...
merge smartly fastq files . It recognizes paired fastq files .
30,055
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 " % ( files ) ) assert all ( map ( utils . file_exists , files ) ) , ( "Not all of the files to merge " "exist: %s" % ( files ) ) if not file_exi...
merge list of fastq files into one
30,056
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" ) as out_handle : for line in in_handle : if line . startswith ( "#" ) or line . startswith ( "browser" ) or line . startswith ( "track" ) : continue else : ...
clean a BED file
30,057
def concat ( bed_files , catted = None ) : bed_files = [ x for x in bed_files if x ] if len ( bed_files ) == 0 : if catted : 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 :...
recursively concat a set of BED files returning a sorted bedtools object of the result
30,058
def merge ( bedfiles ) : if isinstance ( bedfiles , list ) : catted = concat ( bedfiles ) else : catted = concat ( [ bedfiles ] ) if catted : return concat ( bedfiles ) . sort ( ) . merge ( ) else : return catted
given a BED file or list of BED files merge them an return a bedtools object
30,059
def select_unaligned_read_pairs ( in_bam , extra , out_dir , config ) : 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 ) : wit...
Retrieve unaligned read pairs from input alignment BAM as two fastq files .
30,060
def remove_nopairs ( in_bam , out_dir , config ) : 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...
Remove any reads without both pairs present in the file .
30,061
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 ( in_bam , "tier{}" . format ( tier_num ) , work_dir , config ) if nomap_fq1 is not None : base_name = "{}-tier{}out" . format ( os . path ...
Perform the alignment of non - mapped reads from previous tier .
30,062
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 ( [ "bamToBed" , "-i" , in_bam , "-tag" , "NM" ] , stdout = out_handle ) return out_file
Convert BAM to bed file using BEDTools .
30,063
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 , pair_stats ) dedup_bed = dedup_discordants ( pair_bed ) return run_hydra ( dedup_bed , pair_stats ) else : return None
Detect structural variation breakpoints with hydra .
30,064
def detect_sv ( align_bam , genome_build , dirs , config ) : 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" , Tr...
Detect structural variation from discordant aligned pairs .
30,065
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 .
30,066
def recv ( self , timeout = None ) : 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 LogRecor...
Overwrite standard recv for timeout calls to catch interrupt errors .
30,067
def run ( align_bams , items , ref_file , assoc_files , region = None , out_file = None ) : 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 =...
Run tumor only pisces calling
30,068
def _prep_genome ( out_dir , data ) : 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 . ...
Create prepped reference directory for pisces .
30,069
def run ( align_bams , items , ref_file , assoc_files , region , out_file ) : 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 cu...
Return DeepVariant calling on germline samples .
30,070
def _run_germline ( bam_file , data , ref_file , region , out_file ) : 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_b...
Single sample germline variant calling .
30,071
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" ) ) example_dir = utils . safe_makedir ( os . path . join ( work_dir , "examples" ) ) if len ( glob . glob ( os . path . join ( example_dir , "%s.tfrecord*.gz" % dd...
Create example pileup images to feed into variant calling .
30,072
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 ( tf_out_file ) : with file_transaction ( data , tf_out_file ) as tx_out_file : model = "wes" if strelka2 . coverage_interval_from_bed ( region_bed ) =...
Call variants from prepared pileup examples creating tensorflow record file .
30,073
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 ) as tx_out_file : cmd = [ "dv_postprocess_variants.py" , "--ref" , ref_file , "--infile" , record_file , "--outfile" , tx_out_file ] do . run ( cmd ...
Post - process variants converting into standard VCF file .
30,074
def run ( bam_file , data , out_dir ) : 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 qsign...
Run SignatureGenerator to create normalize vcf that later will be input of qsignature_summary
30,075
def summary ( * samples ) : 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" , ...
Run SignatureCompareRelatedSimple module from qsignature tool .
30,076
def _parse_qsignature_output ( in_file , out_file , warning_file , data ) : 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...
Parse xml file produced by qsignature
30,077
def _slice_bam_chr21 ( in_bam , data ) : 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 =...
return only one BAM file with only chromosome 21
30,078
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 = ( "grep chr21 {vcf_file} > {tmp_file}" ) . format ( ** locals ( ) ) out = subprocess . check_output ( cmd , shell = True ) return tmp_file
Slice chr21 of qsignature SNPs to reduce computation time
30,079
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 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...
Combine multiple input files fixing file paths if needed .
30,080
def _fill_file_path ( line , data ) : 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 ...
Fill in a full file path in the configuration file from data dictionary .
30,081
def find_annotations ( data , retriever = None ) : 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 ...
Find annotation configuration files for vcfanno using pre - installed inputs .
30,082
def annotate_gemini ( data , retriever = None ) : 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" ] ] )
Annotate with population calls if have data installed .
30,083
def _annotate_somatic ( data , retriever = None ) : 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
Annotate somatic calls if we have cosmic data installed .
30,084
def is_human ( data , builds = None ) : 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" ] : retur...
Check if human optionally with build number search by name or extra GL contigs .
30,085
def _get_resource_programs ( progs , algs ) : 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" ...
Retrieve programs used in analysis based on algorithm configurations . Handles special cases like aligners and variant callers .
30,086
def _parent_prefix ( prefix ) : 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 ) r...
Identify a parent prefix we should add to resources if present in a caller name .
30,087
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 ] : memory = float ( min_memory [ p ] ) / cores return cores , memory
Ensure setting match minimum resources required for used programs .
30,088
def _get_prog_memory ( resources , cores_per_job ) : 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 ( "core...
Get expected memory usage in Gb per core for a program from resource specification .
30,089
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 : return cores , total_mem , 1.0 total_mem = min ( float ( total_mem ) , float ( sysinfo [ "memory" ] ) - system_memory ) cores = min ( cores , int ( sy...
Scale multicore usage to avoid excessive memory usage based on system information .
30,090
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" ] ) / 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...
When scheduling jobs with single cores avoid overscheduling due to memory .
30,091
def calculate ( parallel , items , sysinfo , config , multiplier = 1 , max_multicore = None ) : assert len ( items ) > 0 , "Finding job resources but no items to process" all_cores = [ ] all_memory = [ ] system_memory = 0.10 algs = [ config_utils . get_algorithm_config ( x ) for x in items ] progs = _get_resource_progr...
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 ...
30,092
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 ) : return out_file safe_makedir ( align_dir ) hisat2_ss = config_utils . get_program ( "hisat2_extract_splice_sites.py" , data ) cmd = "{hisat2_ss} {gtf_...
if not pre - created make a splicesites file to use with hisat2
30,093
def get_splicejunction_file ( align_dir , data ) : 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...
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
30,094
def write_info ( dirs , parallel , config ) : 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 , conf...
Write cluster or local filesystem resources spinning up cluster if not present .
30,095
def _get_machine_info ( parallel , sys_config , dirs , config ) : if parallel . get ( "queue" ) and parallel . get ( "scheduler" ) : 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 [ paral...
Get machine resource information from the job scheduler via either the command line or the queue .
30,096
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 ) ) . decode ( ) . split ( ) mem = float ( mem . replace ( '+' , '' ) ) num_cpus = int ( num_cpus . replace ( '+' , '' ) ) bcbio_mem = 2000 controller_mem ...
Returns machine information for a slurm job scheduler .
30,097
def _torque_info ( queue ) : 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...
Return machine information for a torque job scheduler using pbsnodes .
30,098
def _torque_queue_nodes ( queue ) : 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 (...
Retrieve the nodes available for a queue .
30,099
def _sge_info ( queue ) : 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...
Returns machine information for an sge job scheduler .