idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
30,100
def _sge_get_slots ( xmlstring ) : rootxml = ET . fromstring ( xmlstring ) my_machine_dict = { } for queue_list in rootxml . iter ( "Queue-List" ) : my_hostname = queue_list . find ( "name" ) . text . rsplit ( "@" ) [ - 1 ] my_slots = queue_list . find ( "slots_total" ) . text my_machine_dict [ my_hostname ] = { } my_m...
Get slot information from qstat
30,101
def _sge_get_mem ( xmlstring , queue_name ) : rootxml = ET . fromstring ( xmlstring ) my_machine_dict = { } rootTag = rootxml . tag . rstrip ( "qhost" ) for host in rootxml . findall ( rootTag + 'host' ) : for queues in host . findall ( rootTag + 'queue' ) : if not queue_name or any ( q in queues . attrib [ 'name' ] fo...
Get memory information from qhost
30,102
def get_info ( dirs , parallel , resources = None ) : 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 mac...
Retrieve cluster or local filesystem resources from pre - retrieved information .
30,103
def machine_info ( ) : 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 ( ) } ]
Retrieve core and memory information for the current machine .
30,104
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 ( bam_file , { } ) assert sort_order , "Cannot determine sort order of %s." % bam_file strand_flag = _strand_flag ( stranded ) assert strand_flag , ...
run dexseq_count on a BAM file
30,105
def _trim_adapters ( fastq_files , out_dir , data ) : 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 , t...
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
30,106
def _cutadapt_trim ( fastq_files , quality_format , adapters , out_files , log_file , data ) : 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...
Trimming with cutadapt .
30,107
def _cutadapt_trim_cmd ( fastq_files , quality_format , adapters , out_files , data ) : 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" cutadapt = os . path . join ( os . path . dirname ( sys . executable ) ,...
Trimming with cutadapt using version installed with bcbio - nextgen .
30,108
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 ( ** locals ( ) ) fq1 = objectstore . cl_input ( fastq_files [ 0 ] ) of1 = out_files [ 0 ] cmd += " -o {of1_tx} " + str ( fq1 ) cmd = "%s | tee ...
this has to use the - o option not redirect to stdout in order for gzipping to be supported
30,109
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 , 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 ...
run cutadapt in paired end mode
30,110
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 ) : if not known_vrns : known_vrns = { } if out_file : out_file = "%s.intervals" % os . path . splitext ( out_file ) [ 0 ] else : out_...
Generate a list of interval regions for realignment around indels .
30,111
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 : known_vrns = { } params = [ "-T" , "IndelRealigner" , "-I" , align_bam , "-R" , ref_file , "-targetIntervals" , intervals , ] if region : params += [ "-...
Prepare input arguments for GATK indel realignment .
30,112
def has_aligned_reads ( align_bam , region = None ) : 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 cu...
Check if the aligned BAM file has any reads in the region .
30,113
def s ( name , parallel , inputs , outputs , image , programs = None , disk = None , cores = None , unlist = None , no_files = False ) : 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 =...
Represent a step in a workflow .
30,114
def w ( name , parallel , workflow , internal ) : Workflow = collections . namedtuple ( "Workflow" , "name parallel workflow internal" ) return Workflow ( name , parallel , workflow , internal )
A workflow allowing specification of sub - workflows for nested parallelization .
30,115
def et ( name , parallel , inputs , outputs , expression ) : ExpressionTool = collections . namedtuple ( "ExpressionTool" , "name inputs outputs expression parallel" ) return ExpressionTool ( name , inputs , outputs , expression , parallel )
Represent an ExpressionTool that reorders inputs using javascript .
30,116
def cwlout ( key , valtype = None , extensions = None , fields = None , exclude = None ) : 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
Definition of an output variable defining the type and associated secondary files .
30,117
def _variant_hla ( checkpoints ) : 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" , ...
Add hla analysis to workflow if configured .
30,118
def variant ( samples ) : 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" ] , ...
Variant calling workflow definition for CWL generation .
30,119
def breakpoints_by_caller ( bed_files ) : 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" ] ...
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
30,120
def _get_sv_callers ( items ) : 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 ( )
return a sorted list of all of the structural variant callers run
30,121
def _prioritize_plot_regions ( region_bt , data , out_dir = None ) : max_plots = 1000 max_size = 100 * 1000 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...
Avoid plotting large numbers of regions due to speed issues . Prioritize most interesting .
30,122
def by_regions ( 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 ( i...
Plot for a union set of combined ensemble regions across all of the data items .
30,123
def finalize_sv ( orig_vcf , data , items ) : paired = vcfutils . get_paired ( items ) 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 = vcfuti...
Finalize structural variants adding effects and splitting if needed .
30,124
def _get_sv_exclude_file ( items ) : sv_bed = utils . get_in ( items [ 0 ] , ( "genome_resources" , "variation" , "sv_repeat" ) ) if sv_bed and os . path . exists ( sv_bed ) : return sv_bed
Retrieve SV file of regions to exclude .
30,125
def _get_variant_regions ( 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" ] ) )
Retrieve variant regions defined in any of the input items .
30,126
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 ( base_file ) [ 0 ] , "-%s" % chrom if chrom else "" ) if not utils . file_exists ( out_file ) and not utils . file_exists ( out_file + ".gz" ...
Prepare a BED file for exclusion .
30,127
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" : 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...
Exclude calls based on overlap of the ends with exclusion regions .
30,128
def _find_to_filter ( in_file , exclude_file , params , to_exclude ) : 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 ( o...
Identify regions in the end file that overlap the exclusion file .
30,129
def get_sv_chroms ( items , exclude_file ) : 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 ] ) ) a...
Retrieve chromosomes to process on avoiding extra skipped chromosomes .
30,130
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 . 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...
Retrieve split - read alignments from input BAM file .
30,131
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 = "%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 :...
Check for pre - calculated split reads and discordants done as part of alignment streaming .
30,132
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 = ( 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 , di...
Retrieve split and discordant reads potentially calculating with extract_sv_reads as needed .
30,133
def get_cur_batch ( items ) : 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...
Retrieve name of the batch shared between all items in a group .
30,134
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 : 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 )
Retrieve statistics for paired end read insert distances .
30,135
def calc_paired_insert_stats_save ( in_bam , stat_file , nsample = 1000000 ) : if utils . file_exists ( stat_file ) : with open ( stat_file ) as in_handle : return yaml . safe_load ( in_handle ) else : stats = calc_paired_insert_stats ( in_bam , nsample ) with open ( stat_file , "w" ) as out_handle : yaml . safe_dump (...
Calculate paired stats saving to a file for re - runs .
30,136
def _accumulate_remotes ( synapse_parent_id , syn ) : remotes = { } s_base_folder = syn . get ( synapse_parent_id ) for ( s_dirpath , s_dirpath_id ) , _ , s_filenames in synapseutils . walk ( syn , synapse_parent_id ) : remotes [ s_dirpath ] = s_dirpath_id if s_filenames : for s_filename , s_filename_id in s_filenames ...
Retrieve references to all remote directories and files .
30,137
def _remote_folder ( dirpath , remotes , syn ) : if dirpath in remotes : return remotes [ dirpath ] , remotes else : parent_dir , cur_dir = os . path . split ( dirpath ) parent_folder , remotes = _remote_folder ( parent_dir , remotes , syn ) s_cur_dir = syn . store ( synapseclient . Folder ( cur_dir , parent = parent_f...
Retrieve the remote folder for files creating if necessary .
30,138
def run ( items , background = None ) : if not background : background = [ ] background_bams = [ ] paired = vcfutils . get_paired_bams ( [ x [ "align_bam" ] for x in items ] , items ) if paired : inputs = [ paired . tumor_data ] if paired . normal_bam : background = [ paired . normal_data ] background_bams = [ paired ....
Detect copy number variations from batched set of samples using WHAM .
30,139
def _run_wham ( inputs , background_bams ) : out_file = os . path . join ( _sv_workdir ( inputs [ 0 ] ) , "%s-wham.vcf.gz" % dd . get_sample_name ( inputs [ 0 ] ) ) if not utils . file_exists ( out_file ) : with file_transaction ( inputs [ 0 ] , out_file ) as tx_out_file : cores = dd . get_cores ( inputs [ 0 ] ) ref_fi...
Run WHAM on a defined set of inputs and targets .
30,140
def filter_by_background ( in_vcf , full_vcf , background , data ) : Filter = collections . namedtuple ( 'Filter' , [ 'id' , 'desc' ] ) back_filter = Filter ( id = 'InBackground' , desc = 'Rejected due to presence in background sample' ) out_file = "%s-filter.vcf" % utils . splitext_plus ( in_vcf ) [ 0 ] if not utils ....
Filter SV calls also present in background samples .
30,141
def run_region ( data , region , vrn_files , out_file ) : broad_runner = broad . runner_from_config ( data [ "config" ] ) if broad_runner . gatk_type ( ) == "gatk4" : genomics_db = _run_genomicsdb_import ( vrn_files , region , out_file , data ) return _run_genotype_gvcfs_genomicsdb ( genomics_db , region , out_file , d...
Perform variant calling on gVCF inputs in a specific genomic region .
30,142
def _incomplete_genomicsdb ( dbdir ) : for test_file in [ "callset.json" , "vidmap.json" , "genomicsdb_array/genomicsdb_meta.json" ] : if not os . path . exists ( os . path . join ( dbdir , test_file ) ) : return True return False
Check if a GenomicsDB output is incomplete and we should regenerate .
30,143
def _run_genotype_gvcfs_gatk3 ( data , region , vrn_files , ref_file , out_file ) : if not utils . file_exists ( out_file ) : broad_runner = broad . runner_from_config ( data [ "config" ] ) with file_transaction ( data , out_file ) as tx_out_file : assoc_files = tz . get_in ( ( "genome_resources" , "variation" ) , data...
Performs genotyping of gVCFs into final VCF files .
30,144
def _batch_gvcfs ( data , region , vrn_files , ref_file , out_file = None ) : if out_file is None : out_file = vrn_files [ 0 ] max_batch = int ( dd . get_joint_group_size ( data ) ) if len ( vrn_files ) > max_batch : out = [ ] num_batches = int ( math . ceil ( float ( len ( vrn_files ) ) / max_batch ) ) for i , batch_v...
Perform batching of gVCF files if above recommended input count .
30,145
def _get_preseq_params ( data , preseq_cmd , read_count ) : defaults = { 'seg_len' : 100000 , 'steps' : 300 , 'extrap_fraction' : 3 , 'extrap' : None , 'step' : None , 'options' : '' , } params = { } main_opts = [ ( "-e" , "-extrap" ) , ( "-l" , "-seg_len" ) , ( "-s" , "-step" ) ] other_opts = config_utils . get_resour...
Get parameters through resources . If step or extrap limit are not provided then calculate optimal values based on read count .
30,146
def split_somatic ( items ) : items = [ _clean_flat_variantcaller ( x ) for x in items ] somatic_groups , somatic , non_somatic = vcfutils . somatic_batches ( items ) germline_added = set ( [ ] ) germline = [ ] for somatic_group in somatic_groups : paired = vcfutils . get_paired ( somatic_group ) if paired and paired ....
Split somatic batches adding a germline target .
30,147
def _clean_flat_variantcaller ( data ) : vc = dd . get_variantcaller ( data ) if isinstance ( vc , ( list , tuple ) ) and all ( [ x . count ( ":" ) == 1 for x in vc ] ) : out = { } for v in vc : k , v = v . split ( ":" ) if k in out : out [ k ] . append ( v ) else : out [ k ] = [ v ] data = dd . set_variantcaller ( dat...
Convert flattened dictionary from CWL representation into dictionary .
30,148
def remove_align_qc_tools ( data ) : align_qc = set ( [ "qsignature" , "coverage" , "picard" , "samtools" , "fastqc" ] ) data [ "config" ] [ "algorithm" ] [ "qc" ] = [ t for t in dd . get_algorithm_qc ( data ) if t not in align_qc ] return data
Remove alignment based QC tools we don t need for data replicates .
30,149
def extract ( data , items , out_dir = None ) : if vcfutils . get_paired_phenotype ( data ) : if len ( items ) == 1 : germline_vcf = _remove_prioritization ( data [ "vrn_file" ] , data , out_dir ) germline_vcf = vcfutils . bgzip_and_index ( germline_vcf , data [ "config" ] ) data [ "vrn_file_plus" ] = { "germline" : ge...
Extract germline calls for the given sample if tumor only .
30,150
def fix_germline_samplename ( in_file , sample_name , data ) : out_file = "%s-fixnames%s" % utils . splitext_plus ( in_file ) if not utils . file_exists ( out_file ) : with file_transaction ( data , out_file ) as tx_out_file : sample_file = "%s-samples.txt" % utils . splitext_plus ( tx_out_file ) [ 0 ] with open ( samp...
Replace germline sample names originally from normal BAM file .
30,151
def _remove_prioritization ( in_file , data , out_dir = None ) : out_file = "%s-germline.vcf" % utils . splitext_plus ( in_file ) [ 0 ] if out_dir : out_file = os . path . join ( out_dir , os . path . basename ( out_file ) ) if not utils . file_uptodate ( out_file , in_file ) and not utils . file_uptodate ( out_file + ...
Remove tumor - only prioritization and return non - filtered calls .
30,152
def _extract_germline ( in_file , data ) : out_file = "%s-germline.vcf" % utils . splitext_plus ( in_file ) [ 0 ] if not utils . file_uptodate ( out_file , in_file ) and not utils . file_uptodate ( out_file + ".gz" , in_file ) : with file_transaction ( data , out_file ) as tx_out_file : reader = cyvcf2 . VCF ( str ( in...
Extract germline calls non - somatic non - filtered calls .
30,153
def _is_somatic ( rec ) : if _has_somatic_flag ( rec ) : return True if _is_mutect2_somatic ( rec ) : return True ss_flag = rec . INFO . get ( "SS" ) if ss_flag is not None : if str ( ss_flag ) == "2" : return True status_flag = rec . INFO . get ( "STATUS" ) if status_flag is not None : if str ( status_flag ) . lower (...
Handle somatic classifications from MuTect MuTect2 VarDict and VarScan
30,154
def _is_germline ( rec ) : if _has_somatic_flag ( rec ) : return False if _is_mutect2_somatic ( rec ) : return False ss_flag = rec . INFO . get ( "SS" ) if ss_flag is not None : if str ( ss_flag ) == "1" : return True pp = rec . INFO . get ( "PP" ) if pp and float ( pp ) / float ( rec . QUAL ) >= 0.5 : return True stat...
Handle somatic INFO classifications from MuTect MuTect2 VarDict VarScan and Octopus .
30,155
def get_sort_cmd ( tmp_dir = None ) : has_versionsort = subprocess . check_output ( "sort --help | grep version-sort; exit 0" , shell = True ) . strip ( ) if has_versionsort : cmd = "sort -V" else : cmd = "sort" if tmp_dir and os . path . exists ( tmp_dir ) and os . path . isdir ( tmp_dir ) : cmd += " -T %s" % tmp_dir ...
Retrieve GNU coreutils sort command using version - sort if available .
30,156
def check_bed_contigs ( in_file , data ) : if not dd . get_ref_file ( data ) : return contigs = set ( [ ] ) with utils . open_gzipsafe ( in_file ) as in_handle : for line in in_handle : if not line . startswith ( ( "#" , "track" , "browser" , "@" ) ) and line . strip ( ) : contigs . add ( line . split ( ) [ 0 ] ) ref_c...
Ensure BED file contigs match the reference genome .
30,157
def check_bed_coords ( in_file , data ) : if dd . get_ref_file ( data ) : contig_sizes = { } for contig in ref . file_contigs ( dd . get_ref_file ( data ) ) : contig_sizes [ contig . name ] = contig . size with utils . open_gzipsafe ( in_file ) as in_handle : for line in in_handle : if not line . startswith ( ( "#" , "...
Ensure BED file coordinates match reference genome .
30,158
def clean_file ( in_file , data , prefix = "" , bedprep_dir = None , simple = None ) : simple = "iconv -c -f utf-8 -t ascii | sed 's/ //g' |" if simple else "" if in_file : if not bedprep_dir : bedprep_dir = utils . safe_makedir ( os . path . join ( data [ "dirs" ] [ "work" ] , "bedprep" ) ) if prefix and os . path . b...
Prepare a clean sorted input BED file without headers
30,159
def remove_bad ( ) : for line in sys . stdin : parts = line . strip ( ) . split ( "\t" ) if len ( parts ) == 1 and len ( line . strip ( ) . split ( ) ) > 1 : parts = line . strip ( ) . split ( ) if line . strip ( ) and len ( parts ) > 2 and int ( parts [ 2 ] ) > int ( parts [ 1 ] ) : sys . stdout . write ( "\t" . join ...
Remove non - increasing BED lines which will cause variant callers to choke .
30,160
def merge_overlaps ( in_file , data , distance = None , out_dir = None ) : config = data [ "config" ] if in_file : bedtools = config_utils . get_program ( "bedtools" , config , default = "bedtools" ) work_dir = tz . get_in ( [ "dirs" , "work" ] , data ) if out_dir : bedprep_dir = out_dir elif work_dir : bedprep_dir = u...
Merge bed file intervals to avoid overlapping regions . Output is always a 3 column file .
30,161
def population_variant_regions ( items , merged = False ) : def _get_variant_regions ( data ) : out = dd . get_variant_regions ( data ) or dd . get_sample_callable ( data ) if merged and dd . get_variant_regions ( data ) : merged_out = dd . get_variant_regions_merged ( data ) if merged_out : out = merged_out else : out...
Retrieve the variant region BED file from a population of items .
30,162
def combine ( in_files , out_file , config ) : if not utils . file_exists ( out_file ) : with file_transaction ( config , out_file ) as tx_out_file : with open ( tx_out_file , "w" ) as out_handle : for in_file in in_files : with open ( in_file ) as in_handle : shutil . copyfileobj ( in_handle , out_handle ) return out_...
Combine multiple BED files into a single output .
30,163
def intersect_two ( f1 , f2 , work_dir , data ) : bedtools = config_utils . get_program ( "bedtools" , data , default = "bedtools" ) f1_exists = f1 and utils . file_exists ( f1 ) f2_exists = f2 and utils . file_exists ( f2 ) if not f1_exists and not f2_exists : return None elif f1_exists and not f2_exists : return f1 e...
Intersect two regions handling cases where either file is not present .
30,164
def subset_to_genome ( in_file , out_file , data ) : if not utils . file_uptodate ( out_file , in_file ) : contigs = set ( [ x . name for x in ref . file_contigs ( dd . get_ref_file ( data ) ) ] ) with utils . open_gzipsafe ( in_file ) as in_handle : with file_transaction ( data , out_file ) as tx_out_file : with open ...
Subset a BED file to only contain contigs present in the reference genome .
30,165
def run ( align_bams , items , ref_file , assoc_files , region , out_file ) : if not utils . file_exists ( out_file ) : paired = vcfutils . get_paired_bams ( align_bams , items ) vrs = bedutils . population_variant_regions ( items ) target = shared . subset_variant_regions ( vrs , region , out_file , items = items , do...
Run octopus variant calling handling both somatic and germline calling .
30,166
def _produce_compatible_vcf ( out_file , data , is_somatic ) : base , ext = utils . splitext_plus ( out_file ) legacy_file = "%s.legacy%s" % ( base , ext ) if is_somatic : legacy_file = _covert_to_diploid ( legacy_file , data ) final_file = "%s.vcf.gz" % base cat_cmd = "zcat" if legacy_file . endswith ( ".gz" ) else "c...
Create a compatible VCF that downstream tools can deal with .
30,167
def _covert_to_diploid ( in_file , data ) : sample = dd . get_sample_name ( data ) out_file = "%s-diploid.vcf" % utils . splitext_plus ( in_file ) [ 0 ] in_vcf = pysam . VariantFile ( in_file ) out_vcf = pysam . VariantFile ( out_file , 'w' , header = in_vcf . header ) for record in in_vcf : gt = list ( record . sample...
Converts non - diploid somatic outputs into diploid .
30,168
def _run_germline ( align_bams , items , ref_file , target , out_file ) : align_bams = " " . join ( align_bams ) cores = dd . get_num_cores ( items [ 0 ] ) cmd = ( "octopus --threads {cores} --reference {ref_file} --reads {align_bams} " "--regions-file {target} " "--working-directory {tmp_dir} " "-o {tx_out_file} --leg...
Run germline calling handling populations .
30,169
def _run_somatic ( paired , ref_file , target , out_file ) : align_bams = paired . tumor_bam if paired . normal_bam : align_bams += " %s --normal-sample %s" % ( paired . normal_bam , paired . normal_name ) cores = dd . get_num_cores ( paired . tumor_data ) min_af = max ( [ float ( dd . get_min_allele_fraction ( paired ...
Run somatic calling with octopus handling both paired and tumor - only cases .
30,170
def _is_umi_consensus_bam ( in_file ) : cmd = "samtools view -h %s | head -500000 | samtools view -c -f 1024" count = subprocess . check_output ( cmd % in_file , shell = True ) return int ( count ) == 0
Check if input BAM file generated by fgbio consensus calls on UMIs .
30,171
def update_file ( finfo , sample_info , config ) : ffinal = filesystem . update_file ( finfo , sample_info , config , pass_uptodate = True ) if os . path . isdir ( ffinal ) : to_transfer = [ ] for path , dirs , files in os . walk ( ffinal ) : for f in files : full_f = os . path . join ( path , f ) k = full_f . replace ...
Update the file to an Amazon S3 bucket using server side encryption .
30,172
def _upload_file_aws_cli ( local_fname , bucket , keyname , config = None , mditems = None ) : s3_fname = "s3://%s/%s" % ( bucket , keyname ) args = [ "--sse" , "--expected-size" , str ( os . path . getsize ( local_fname ) ) ] if config : if config . get ( "region" ) : args += [ "--region" , config . get ( "region" ) ]...
Streaming upload via the standard AWS command line interface .
30,173
def upload_file_boto ( fname , remote_fname , mditems = None ) : r_fname = objectstore . parse_remote ( remote_fname ) conn = objectstore . connect ( remote_fname ) bucket = conn . lookup ( r_fname . bucket ) if not bucket : bucket = conn . create_bucket ( r_fname . bucket , location = objectstore . get_region ( remote...
Upload a file using boto instead of external tools .
30,174
def run ( bam_file , sample , out_dir ) : out = { } peaks = sample . get ( "peaks_files" , { } ) . get ( "main" ) if peaks : out . update ( _reads_in_peaks ( bam_file , peaks , sample ) ) return out
Standard QC metrics for chipseq
30,175
def _reads_in_peaks ( bam_file , peaks_file , sample ) : if not peaks_file : return { } rip = number_of_mapped_reads ( sample , bam_file , bed_file = peaks_file ) return { "metrics" : { "RiP" : rip } }
Calculate number of reads in peaks
30,176
def chipqc ( bam_file , sample , out_dir ) : sample_name = dd . get_sample_name ( sample ) logger . warning ( "ChIPQC is unstable right now, if it breaks, turn off the tool." ) if utils . file_exists ( out_dir ) : return _get_output ( out_dir ) with tx_tmpdir ( ) as tmp_dir : rcode = _sample_template ( sample , tmp_dir...
Attempt code to run ChIPQC bioconductor packate in one sample
30,177
def _sample_template ( sample , out_dir ) : bam_fn = dd . get_work_bam ( sample ) genome = dd . get_genome_build ( sample ) if genome in supported : peaks = sample . get ( "peaks_files" , [ ] ) . get ( "main" ) if peaks : r_code = ( "library(ChIPQC);\n" "sample = ChIPQCsample(\"{bam_fn}\"," "\"{peaks}\", " "annotation ...
R code to get QC for one sample
30,178
def _change_sample_name ( in_file , sample_name , data = None ) : out_file = append_stem ( in_file , "_fixed" ) with file_transaction ( data , out_file ) as tx_out : with open ( tx_out , "w" ) as out_handle : with open ( in_file ) as in_handle : for line in in_handle : if line . startswith ( "Status" ) : line = "Status...
Fix name in feature counts log file to get the same name in multiqc report .
30,179
def _format_count_file ( count_file , data ) : COUNT_COLUMN = 5 out_file = os . path . splitext ( count_file ) [ 0 ] + ".fixed.counts" if file_exists ( out_file ) : return out_file df = pd . io . parsers . read_table ( count_file , sep = "\t" , index_col = 0 , header = 1 ) df_sub = df . ix [ : , COUNT_COLUMN ] with fil...
this cuts the count file produced from featureCounts down to a two column file of gene ids and number of reads mapping to each gene
30,180
def run_qc ( _ , data , out_dir ) : if cwlutils . is_cwl_run ( data ) : qc_data = run_peddy ( [ data ] , out_dir ) if tz . get_in ( [ "summary" , "qc" , "peddy" ] , qc_data ) : return tz . get_in ( [ "summary" , "qc" , "peddy" ] , qc_data )
Run quality control in QC environment on a single sample .
30,181
def run ( name , chip_bam , input_bam , genome_build , out_dir , method , resources , data ) : config = dd . get_config ( data ) out_file = os . path . join ( out_dir , name + "_peaks_macs2.xls" ) macs2_file = os . path . join ( out_dir , name + "_peaks.xls" ) if utils . file_exists ( out_file ) : _compres_bdg_files ( ...
Run macs2 for chip and input samples avoiding errors due to samples .
30,182
def _macs2_cmd ( method = "chip" ) : if method . lower ( ) == "chip" : cmd = ( "{macs2} callpeak -t {chip_bam} -c {input_bam} {paired} " " {genome_size} -n {name} -B {options}" ) elif method . lower ( ) == "atac" : cmd = ( "{macs2} callpeak -t {chip_bam} --nomodel " " {paired} {genome_size} -n {name} -B {options}" " --...
Main command for macs2 tool .
30,183
def to_cram ( data ) : data = utils . to_single_data ( data ) cram_file = cram . compress ( dd . get_work_bam ( data ) or dd . get_align_bam ( data ) , data ) out_key = "archive_bam" if cwlutils . is_cwl_run ( data ) else "work_bam" data [ out_key ] = cram_file return [ [ data ] ]
Convert BAM archive files into indexed CRAM .
30,184
def compress ( samples , run_parallel ) : to_cram = [ ] finished = [ ] for data in [ x [ 0 ] for x in samples ] : if "cram" in dd . get_archive ( data ) or "cram-lossless" in dd . get_archive ( data ) : to_cram . append ( [ data ] ) else : finished . append ( [ data ] ) crammed = run_parallel ( "archive_to_cram" , to_c...
Perform compression of output files for long term storage .
30,185
def run ( _ , data , out_dir = None ) : stats_file , idxstats_file = _get_stats_files ( data , out_dir ) samtools = config_utils . get_program ( "samtools" , data [ "config" ] ) bam_file = dd . get_align_bam ( data ) or dd . get_work_bam ( data ) if not utils . file_exists ( stats_file ) : utils . safe_makedir ( out_di...
Run samtools stats with reports on mapped reads duplicates and insert sizes .
30,186
def run_and_save ( data ) : run ( None , data ) stats_file , idxstats_file = _get_stats_files ( data ) data = tz . update_in ( data , [ "depth" , "samtools" , "stats" ] , lambda x : stats_file ) data = tz . update_in ( data , [ "depth" , "samtools" , "idxstats" ] , lambda x : idxstats_file ) return data
Run QC saving file outputs in data dictionary .
30,187
def _get_stats_files ( data , out_dir = None ) : if not out_dir : out_dir = utils . safe_makedir ( os . path . join ( dd . get_work_dir ( data ) , "qc" , dd . get_sample_name ( data ) , "samtools" ) ) stats_file = tz . get_in ( [ "depth" , "samtools" , "stats" ] , data ) idxstats_file = tz . get_in ( [ "depth" , "samto...
Retrieve stats files from pre - existing dictionary or filesystem .
30,188
def _descr_str ( descr , data , region ) : if data : name = dd . get_sample_name ( data ) if name : descr = "{0} : {1}" . format ( descr , name ) elif "work_bam" in data : descr = "{0} : {1}" . format ( descr , os . path . basename ( data [ "work_bam" ] ) ) if region : descr = "{0} : {1}" . format ( descr , region ) re...
Add additional useful information from data to description string .
30,189
def get_indelcaller ( d_or_c ) : config = d_or_c if isinstance ( d_or_c , dict ) and "config" in d_or_c else d_or_c indelcaller = config [ "algorithm" ] . get ( "indelcaller" , "" ) if not indelcaller : indelcaller = "" if isinstance ( indelcaller , ( list , tuple ) ) : indelcaller = indelcaller [ 0 ] if ( len ( indelc...
Retrieve string for indelcaller to use or empty string if not specified .
30,190
def split_snps_indels ( orig_file , ref_file , config ) : base , ext = utils . splitext_plus ( orig_file ) snp_file = "{base}-snp{ext}" . format ( base = base , ext = ext ) indel_file = "{base}-indel{ext}" . format ( base = base , ext = ext ) for out_file , select_arg in [ ( snp_file , "--types snps" ) , ( indel_file ,...
Split a variant call file into SNPs and INDELs for processing .
30,191
def get_samples ( in_file ) : with utils . open_gzipsafe ( in_file ) as in_handle : for line in in_handle : if line . startswith ( "#CHROM" ) : parts = line . strip ( ) . split ( "\t" ) return parts [ 9 : ] raise ValueError ( "Did not find sample header in VCF file %s" % in_file )
Retrieve samples present in a VCF file
30,192
def _get_exclude_samples ( in_file , to_exclude ) : include , exclude = [ ] , [ ] to_exclude = set ( to_exclude ) for s in get_samples ( in_file ) : if s in to_exclude : exclude . append ( s ) else : include . append ( s ) return include , exclude
Identify samples in the exclusion list which are actually in the VCF .
30,193
def exclude_samples ( in_file , out_file , to_exclude , ref_file , config , filters = None ) : include , exclude = _get_exclude_samples ( in_file , to_exclude ) if len ( exclude ) == 0 : out_file = in_file elif not utils . file_exists ( out_file ) : with file_transaction ( config , out_file ) as tx_out_file : bcftools ...
Exclude specific samples from an input VCF file .
30,194
def select_sample ( in_file , sample , out_file , config , filters = None ) : if not utils . file_exists ( out_file ) : with file_transaction ( config , out_file ) as tx_out_file : if len ( get_samples ( in_file ) ) == 1 : shutil . copy ( in_file , tx_out_file ) else : if in_file . endswith ( ".gz" ) : bgzip_and_index ...
Select a single sample from the supplied multisample VCF file .
30,195
def merge_variant_files ( orig_files , out_file , ref_file , config , region = None ) : in_pipeline = False if isinstance ( orig_files , dict ) : file_key = config [ "file_key" ] in_pipeline = True orig_files = orig_files [ file_key ] out_file = _do_merge ( orig_files , out_file , config , region ) if in_pipeline : ret...
Combine multiple VCF files with different samples into a single output file .
30,196
def _do_merge ( orig_files , out_file , config , region ) : if not utils . file_exists ( out_file ) : with file_transaction ( config , out_file ) as tx_out_file : _check_samples_nodups ( orig_files ) prep_files = run_multicore ( p_bgzip_and_index , [ [ x , config ] for x in orig_files ] , config ) input_vcf_file = "%s-...
Do the actual work of merging with bcftools merge .
30,197
def _check_samples_nodups ( fnames ) : counts = defaultdict ( int ) for f in fnames : for s in get_samples ( f ) : counts [ s ] += 1 duplicates = [ s for s , c in counts . items ( ) if c > 1 ] if duplicates : raise ValueError ( "Duplicate samples found in inputs %s: %s" % ( duplicates , fnames ) )
Ensure a set of input VCFs do not have duplicate samples .
30,198
def _sort_by_region ( fnames , regions , ref_file , config ) : contig_order = { } for i , sq in enumerate ( ref . file_contigs ( ref_file , config ) ) : contig_order [ sq . name ] = i sitems = [ ] assert len ( regions ) == len ( fnames ) , ( regions , fnames ) added_fnames = set ( [ ] ) for region , fname in zip ( regi...
Sort a set of regionally split files by region for ordered output .
30,199
def concat_variant_files ( orig_files , out_file , regions , ref_file , config ) : if not utils . file_exists ( out_file ) : input_file_list = _get_file_list ( orig_files , out_file , regions , ref_file , config ) try : out_file = _run_concat_variant_files_gatk4 ( input_file_list , out_file , config ) except subprocess...
Concatenate multiple variant files from regions into a single output file .