idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
29,600 | def _combine_cwl_records ( recs , record_name , parallel ) : if parallel not in [ "multi-batch" , "single-split" , "multi-combined" , "batch-single" ] : assert len ( recs ) == 1 , pprint . pformat ( recs ) return { record_name : recs [ 0 ] } else : return { record_name : recs } | Provide a list of nexted CWL records keyed by output key . |
29,601 | def _collapse_to_cwl_record_single ( data , want_attrs , input_files ) : out = { } for key in want_attrs : key_parts = key . split ( "__" ) out [ key ] = _to_cwl ( tz . get_in ( key_parts , data ) , input_files ) return out | Convert a single sample into a CWL record . |
29,602 | def _nested_cwl_record ( xs , want_attrs , input_files ) : if isinstance ( xs , ( list , tuple ) ) : return [ _nested_cwl_record ( x , want_attrs , input_files ) for x in xs ] else : assert isinstance ( xs , dict ) , pprint . pformat ( xs ) return _collapse_to_cwl_record_single ( xs , want_attrs , input_files ) | Convert arbitrarily nested samples into a nested list of dictionaries . |
29,603 | def _collapse_to_cwl_record ( samples , want_attrs , input_files ) : input_keys = sorted ( list ( set ( ) . union ( * [ d [ "cwl_keys" ] for d in samples ] ) ) , key = lambda x : ( - len ( x ) , tuple ( x ) ) ) out = { } for key in input_keys : if key in want_attrs : key_parts = key . split ( "__" ) vals = [ ] cur = [ ... | Convert nested samples from batches into a CWL record based on input keys . |
29,604 | def _file_and_exists ( val , input_files ) : return ( ( os . path . exists ( val ) and os . path . isfile ( val ) ) or val in input_files ) | Check if an input is a file and exists . |
29,605 | def _to_cwl ( val , input_files ) : if isinstance ( val , six . string_types ) : if _file_and_exists ( val , input_files ) : val = { "class" : "File" , "path" : val } secondary = [ ] for idx in [ ".bai" , ".tbi" , ".gbi" , ".fai" , ".crai" , ".db" ] : idx_file = val [ "path" ] + idx if _file_and_exists ( idx_file , inp... | Convert a value into CWL formatted JSON handling files and complex things . |
29,606 | def _remove_duplicate_files ( xs ) : seen = set ( [ ] ) out = [ ] for x in xs : if x [ "path" ] not in seen : out . append ( x ) seen . add ( x [ "path" ] ) return out | Remove files specified multiple times in a list . |
29,607 | def _update_nested ( key , val , data , allow_overwriting = False ) : if isinstance ( val , dict ) : for sub_key , sub_val in val . items ( ) : data = _update_nested ( key + [ sub_key ] , sub_val , data , allow_overwriting = allow_overwriting ) else : already_there = tz . get_in ( key , data ) is not None if already_th... | Update the data object avoiding over - writing with nested dictionaries . |
29,608 | def start ( args ) : application = tornado . web . Application ( [ ( r"/run" , run . get_handler ( args ) ) , ( r"/status" , run . StatusHandler ) ] ) application . runmonitor = RunMonitor ( ) application . listen ( args . port ) tornado . ioloop . IOLoop . instance ( ) . start ( ) | Run server with provided command line arguments . |
29,609 | def add_subparser ( subparsers ) : parser = subparsers . add_parser ( "server" , help = "Run a bcbio-nextgen server allowing remote job execution." ) parser . add_argument ( "-c" , "--config" , help = ( "Global YAML configuration file specifying system details." "Defaults to installed bcbio_system.yaml" ) ) parser . ad... | Add command line arguments as server subparser . |
29,610 | def write_versions ( dirs , items ) : genomes = { } for d in items : genomes [ d [ "genome_build" ] ] = d . get ( "reference" , { } ) . get ( "versions" ) out_file = _get_out_file ( dirs ) found_versions = False if genomes and out_file : with open ( out_file , "w" ) as out_handle : writer = csv . writer ( out_handle ) ... | Write data versioning for genomes present in the configuration . |
29,611 | def combine_calls ( * args ) : if len ( args ) == 3 : is_cwl = False batch_id , samples , data = args caller_names , vrn_files = _organize_variants ( samples , batch_id ) else : is_cwl = True samples = [ utils . to_single_data ( x ) for x in args ] samples = [ cwlutils . unpack_tarballs ( x , x ) for x in samples ] dat... | Combine multiple callsets into a final set of merged calls . |
29,612 | def combine_calls_parallel ( samples , run_parallel ) : batch_groups , extras = _group_by_batches ( samples , _has_ensemble ) out = [ ] if batch_groups : processed = run_parallel ( "combine_calls" , ( ( b , xs , xs [ 0 ] ) for b , xs in batch_groups . items ( ) ) ) for batch_id , callinfo in processed : for data in bat... | Combine calls using batched Ensemble approach . |
29,613 | def _group_by_batches ( samples , check_fn ) : batch_groups = collections . defaultdict ( list ) extras = [ ] for data in [ x [ 0 ] for x in samples ] : if check_fn ( data ) : batch_groups [ multi . get_batch_for_key ( data ) ] . append ( data ) else : extras . append ( [ data ] ) return batch_groups , extras | Group calls by batches processing families together during ensemble calling . |
29,614 | def _organize_variants ( samples , batch_id ) : caller_names = [ x [ "variantcaller" ] for x in samples [ 0 ] [ "variants" ] ] calls = collections . defaultdict ( list ) for data in samples : for vrn in data [ "variants" ] : calls [ vrn [ "variantcaller" ] ] . append ( vrn [ "vrn_file" ] ) data = samples [ 0 ] vrn_file... | Retrieve variant calls for all samples merging batched samples into single VCF . |
29,615 | def _handle_somatic_ensemble ( vrn_file , data ) : if tz . get_in ( [ "metadata" , "phenotype" ] , data , "" ) . lower ( ) . startswith ( "tumor" ) : vrn_file_temp = vrn_file . replace ( ".vcf" , "_tumorOnly_noFilteredCalls.vcf" ) vrn_file = vcfutils . select_sample ( in_file = vrn_file , sample = data [ "name" ] [ 1 ]... | For somatic ensemble discard normal samples and filtered variants from vcfs . |
29,616 | def _run_ensemble ( batch_id , vrn_files , config_file , base_dir , ref_file , data ) : out_vcf_file = os . path . join ( base_dir , "{0}-ensemble.vcf" . format ( batch_id ) ) out_bed_file = os . path . join ( base_dir , "{0}-callregions.bed" . format ( batch_id ) ) work_dir = "%s-work" % os . path . splitext ( out_vcf... | Run an ensemble call using merging and SVM - based approach in bcbio . variation |
29,617 | def _write_config_file ( batch_id , caller_names , base_dir , data ) : config_dir = utils . safe_makedir ( os . path . join ( base_dir , "config" ) ) config_file = os . path . join ( config_dir , "{0}-ensemble.yaml" . format ( batch_id ) ) algorithm = data [ "config" ] [ "algorithm" ] econfig = { "ensemble" : algorithm... | Write YAML configuration to generate an ensemble set of combined calls . |
29,618 | def _get_num_pass ( data , n ) : numpass = tz . get_in ( [ "config" , "algorithm" , "ensemble" , "numpass" ] , data ) if numpass : return int ( numpass ) trusted_pct = tz . get_in ( [ "config" , "algorithm" , "ensemble" , "trusted_pct" ] , data ) if trusted_pct : return int ( math . ceil ( float ( trusted_pct ) * n ) )... | Calculate the number of samples needed to pass ensemble calling . |
29,619 | def _run_ensemble_intersection ( batch_id , vrn_files , callers , base_dir , edata ) : out_vcf_file = os . path . join ( base_dir , "{0}-ensemble.vcf.gz" . format ( batch_id ) ) if not utils . file_exists ( out_vcf_file ) : num_pass = _get_num_pass ( edata , len ( vrn_files ) ) cmd = [ config_utils . get_program ( "bcb... | Run intersection n out of x based ensemble method using bcbio . variation . recall . |
29,620 | def _get_callable_regions ( data ) : import pybedtools callable_files = data . get ( "callable_regions" ) if callable_files : assert len ( callable_files ) == 1 regions = [ ( r . chrom , int ( r . start ) , int ( r . stop ) ) for r in pybedtools . BedTool ( callable_files [ 0 ] ) ] else : work_bam = list ( tz . take ( ... | Retrieve regions to parallelize by from callable regions or chromosomes . |
29,621 | def _split_by_callable_region ( data ) : batch = tz . get_in ( ( "metadata" , "batch" ) , data ) jointcaller = tz . get_in ( ( "config" , "algorithm" , "jointcaller" ) , data ) name = batch if batch else tz . get_in ( ( "rgnames" , "sample" ) , data ) out_dir = utils . safe_makedir ( os . path . join ( data [ "dirs" ] ... | Split by callable or variant regions . |
29,622 | def _is_jointcaller_compatible ( data ) : jointcaller = tz . get_in ( ( "config" , "algorithm" , "jointcaller" ) , data ) variantcaller = tz . get_in ( ( "config" , "algorithm" , "variantcaller" ) , data ) if isinstance ( variantcaller , ( list , tuple ) ) and len ( variantcaller ) == 1 : variantcaller = variantcaller ... | Match variant caller inputs to compatible joint callers . |
29,623 | def square_off ( samples , run_parallel ) : to_process = [ ] extras = [ ] for data in [ utils . to_single_data ( x ) for x in samples ] : added = False if tz . get_in ( ( "metadata" , "batch" ) , data ) : for add in genotype . handle_multiple_callers ( data , "jointcaller" , require_bam = False ) : if _is_jointcaller_c... | Perform joint calling at all variants within a batch . |
29,624 | def _combine_to_jointcaller ( processed ) : by_vrn_file = collections . OrderedDict ( ) for data in ( x [ 0 ] for x in processed ) : key = ( tz . get_in ( ( "config" , "algorithm" , "jointcaller" ) , data ) , data [ "vrn_file" ] ) if key not in by_vrn_file : by_vrn_file [ key ] = [ ] by_vrn_file [ key ] . append ( data... | Add joint calling information to variants while collapsing independent regions . |
29,625 | def square_batch_region ( data , region , bam_files , vrn_files , out_file ) : from bcbio . variation import sentieon , strelka2 if not utils . file_exists ( out_file ) : jointcaller = tz . get_in ( ( "config" , "algorithm" , "jointcaller" ) , data ) if jointcaller in [ "%s-joint" % x for x in SUPPORTED [ "general" ] ]... | Perform squaring of a batch in a supplied region with input BAMs |
29,626 | def _fix_orig_vcf_refs ( data ) : variantcaller = tz . get_in ( ( "config" , "algorithm" , "variantcaller" ) , data ) if variantcaller : data [ "vrn_file_orig" ] = data [ "vrn_file" ] for i , sub in enumerate ( data . get ( "group_orig" , [ ] ) ) : sub_vrn = sub . pop ( "vrn_file" , None ) if sub_vrn : sub [ "vrn_file_... | Supply references to initial variantcalls if run in addition to batching . |
29,627 | def _square_batch_bcbio_variation ( data , region , bam_files , vrn_files , out_file , todo = "square" ) : ref_file = tz . get_in ( ( "reference" , "fasta" , "base" ) , data ) cores = tz . get_in ( ( "config" , "algorithm" , "num_cores" ) , data , 1 ) resources = config_utils . get_resources ( "bcbio-variation-recall" ... | Run squaring or merging analysis using bcbio . variation . recall . |
29,628 | def run ( items ) : items = [ utils . to_single_data ( x ) for x in items ] work_dir = _sv_workdir ( items [ 0 ] ) input_backs = list ( set ( filter ( lambda x : x is not None , [ dd . get_background_cnv_reference ( d , "seq2c" ) for d in items ] ) ) ) coverage_file = _combine_coverages ( items , work_dir , input_backs... | Normalization and log2 ratio calculation plus CNV calling for full cohort . |
29,629 | def prep_seq2c_bed ( data ) : if dd . get_background_cnv_reference ( data , "seq2c" ) : bed_file = _background_to_bed ( dd . get_background_cnv_reference ( data , "seq2c" ) , data ) else : bed_file = regions . get_sv_bed ( data ) if bed_file : bed_file = bedutils . clean_file ( bed_file , data , prefix = "svregions-" )... | Selecting the bed file cleaning and properly annotating for Seq2C |
29,630 | def _background_to_bed ( back_file , data ) : out_file = os . path . join ( utils . safe_makedir ( os . path . join ( dd . get_work_dir ( data ) , "bedprep" ) ) , "%s-regions.bed" % utils . splitext_plus ( os . path . basename ( back_file ) ) [ 0 ] ) if not utils . file_exists ( out_file ) : with file_transaction ( dat... | Convert a seq2c background file with calls into BED regions for coverage . |
29,631 | def _get_seq2c_options ( data ) : cov2lr_possible_opts = [ "-F" ] defaults = { } ropts = config_utils . get_resources ( "seq2c" , data [ "config" ] ) . get ( "options" , [ ] ) assert len ( ropts ) % 2 == 0 , "Expect even number of options for seq2c" % ropts defaults . update ( dict ( tz . partition ( 2 , ropts ) ) ) co... | Get adjustable through resources or default options for seq2c . |
29,632 | def to_vcf ( in_tsv , data ) : call_convert = { "Amp" : "DUP" , "Del" : "DEL" } out_file = "%s.vcf" % utils . splitext_plus ( in_tsv ) [ 0 ] if not utils . file_uptodate ( out_file , in_tsv ) : with file_transaction ( data , out_file ) as tx_out_file : with open ( in_tsv ) as in_handle : with open ( tx_out_file , "w" )... | Convert seq2c output file into BED output . |
29,633 | def _combine_coverages ( items , work_dir , input_backs = None ) : out_file = os . path . join ( work_dir , "sample_coverages.txt" ) if not utils . file_exists ( out_file ) : with file_transaction ( items [ 0 ] , out_file ) as tx_out_file : with open ( tx_out_file , 'w' ) as out_f : for data in items : cov_file = tz . ... | Combine coverage cnns calculated for individual inputs into single file . |
29,634 | def _calculate_mapping_reads ( items , work_dir , input_backs = None ) : out_file = os . path . join ( work_dir , "mapping_reads.txt" ) if not utils . file_exists ( out_file ) : lines = [ ] for data in items : count = 0 for line in subprocess . check_output ( [ "samtools" , "idxstats" , dd . get_align_bam ( data ) ] ) ... | Calculate read counts from samtools idxstats for each sample . |
29,635 | def get_resources ( genome , ref_file , data ) : base_dir = os . path . normpath ( os . path . dirname ( ref_file ) ) resource_file = os . path . join ( base_dir , "%s-resources.yaml" % genome . replace ( "-test" , "" ) ) if not os . path . exists ( resource_file ) : raise IOError ( "Did not find resource file for %s: ... | Retrieve genome information from a genome - references . yaml file . |
29,636 | def add_required_resources ( resources ) : required = [ [ "variation" , "cosmic" ] , [ "variation" , "clinvar" ] , [ "variation" , "dbsnp" ] , [ "variation" , "lcr" ] , [ "variation" , "polyx" ] , [ "variation" , "encode_blacklist" ] , [ "variation" , "gc_profile" ] , [ "variation" , "germline_het_pon" ] , [ "variation... | Add default or empty values for required resources referenced in CWL |
29,637 | def ensure_annotations ( resources , data ) : transcript_gff = tz . get_in ( [ "rnaseq" , "transcripts" ] , resources ) if transcript_gff and utils . file_exists ( transcript_gff ) : out_dir = os . path . join ( tz . get_in ( [ "dirs" , "work" ] , data ) , "inputs" , "data" , "annotations" ) resources [ "rnaseq" ] [ "g... | Prepare any potentially missing annotations for downstream processing in a local directory . |
29,638 | def abs_file_paths ( xs , base_dir = None , ignore_keys = None , fileonly_keys = None , cur_key = None , do_download = True ) : ignore_keys = set ( [ ] ) if ignore_keys is None else set ( ignore_keys ) fileonly_keys = set ( [ ] ) if fileonly_keys is None else set ( fileonly_keys ) if base_dir is None : base_dir = os . ... | Normalize any file paths found in a subdirectory of configuration input . |
29,639 | def _get_galaxy_tool_info ( galaxy_base ) : ini_file = os . path . join ( galaxy_base , "universe_wsgi.ini" ) info = { "tool_data_table_config_path" : os . path . join ( galaxy_base , "tool_data_table_conf.xml" ) , "tool_data_path" : os . path . join ( galaxy_base , "tool-data" ) } config = configparser . ConfigParser ... | Retrieve Galaxy tool - data information from defaults or galaxy config file . |
29,640 | def get_builds ( galaxy_base ) : name = "samtools" galaxy_config = _get_galaxy_tool_info ( galaxy_base ) galaxy_dt = _get_galaxy_data_table ( name , galaxy_config [ "tool_data_table_config_path" ] ) loc_file , need_remap = _get_galaxy_loc_file ( name , galaxy_dt , galaxy_config [ "tool_data_path" ] , galaxy_base ) asse... | Retrieve configured genome builds and reference files using Galaxy configuration files . |
29,641 | def _get_jvm_opts ( config , tmp_dir ) : resources = config_utils . get_resources ( "varscan" , config ) jvm_opts = resources . get ( "jvm_opts" , [ "-Xmx750m" , "-Xmx2g" ] ) jvm_opts = config_utils . adjust_opts ( jvm_opts , { "algorithm" : { "memory_adjust" : { "magnitude" : 1.1 , "direction" : "decrease" } } } ) jvm... | Retrieve common options for running VarScan . Handles jvm_opts setting user and country to English to avoid issues with different locales producing non - compliant VCF . |
29,642 | def _varscan_options_from_config ( config ) : opts = [ "--min-coverage 5" , "--p-value 0.98" , "--strand-filter 1" ] resources = config_utils . get_resources ( "varscan" , config ) if resources . get ( "options" ) : opts += [ str ( x ) for x in resources [ "options" ] ] return opts | Retrieve additional options for VarScan from the configuration . |
29,643 | def spv_freq_filter ( line , tumor_index ) : if line . startswith ( "#CHROM" ) : headers = [ ( '##FILTER=<ID=SpvFreq,Description="High frequency (tumor FREQ > 0.35) ' 'and low p-value for somatic (SPV < 0.05)">' ) ] return "\n" . join ( headers ) + "\n" + line elif line . startswith ( "#" ) : return line else : parts =... | Filter VarScan calls based on the SPV value and frequency . |
29,644 | def _create_sample_list ( in_bams , vcf_file ) : out_file = "%s-sample_list.txt" % os . path . splitext ( vcf_file ) [ 0 ] with open ( out_file , "w" ) as out_handle : for in_bam in in_bams : with pysam . Samfile ( in_bam , "rb" ) as work_bam : for rg in work_bam . header . get ( "RG" , [ ] ) : out_handle . write ( "%s... | Pull sample names from input BAMs and create input sample list . |
29,645 | def _varscan_work ( align_bams , ref_file , items , target_regions , out_file ) : config = items [ 0 ] [ "config" ] orig_out_file = out_file out_file = orig_out_file . replace ( ".vcf.gz" , ".vcf" ) max_read_depth = "1000" sample_list = _create_sample_list ( align_bams , out_file ) mpileup = samtools . prep_mpileup ( a... | Perform SNP and indel genotyping with VarScan . |
29,646 | def apply ( object , args = None , kwargs = None ) : if args is None : args = ( ) if kwargs is None : kwargs = { } return object ( * args , ** kwargs ) | Python3 apply replacement for double unpacking of inputs during apply . |
29,647 | def add_genes ( in_file , data , max_distance = 10000 , work_dir = None ) : gene_file = regions . get_sv_bed ( data , "exons" , out_dir = os . path . dirname ( in_file ) ) if gene_file and utils . file_exists ( in_file ) : out_file = "%s-annotated.bed" % utils . splitext_plus ( in_file ) [ 0 ] if work_dir : out_file = ... | Add gene annotations to a BED file from pre - prepared RNA - seq data . |
29,648 | def _add_genes_to_bed ( in_file , gene_file , fai_file , out_file , data , max_distance = 10000 ) : try : input_rec = next ( iter ( pybedtools . BedTool ( in_file ) ) ) except StopIteration : utils . copy_plus ( in_file , out_file ) return extra_fields = list ( range ( 4 , len ( input_rec . fields ) + 1 ) ) gene_index ... | Re - usable subcomponent that annotates BED file genes from another BED |
29,649 | def create ( parallel ) : queue = { k : v for k , v in parallel . items ( ) if k in [ "queue" , "cores_per_job" , "mem" ] } yield queue | Create a queue based on the provided parallel arguments . |
29,650 | def runner ( queue , parallel ) : def run ( fn_name , items ) : logger . info ( "clusterk: %s" % fn_name ) assert "wrapper" in parallel , "Clusterk requires bcbio-nextgen-vm wrapper" fn = getattr ( __import__ ( "{base}.clusterktasks" . format ( base = parallel [ "module" ] ) , fromlist = [ "clusterktasks" ] ) , paralle... | Run individual jobs on an existing queue . |
29,651 | def is_gene_list ( bed_file ) : with utils . open_gzipsafe ( bed_file ) as in_handle : for line in in_handle : if not line . startswith ( "#" ) : if len ( line . split ( ) ) == 1 : return True else : return False | Check if the file is only a list of genes not a BED |
29,652 | def _find_gene_list_from_bed ( bed_file , base_file , data ) : if is_gene_list ( bed_file ) : return bed_file out_file = "%s-genes.txt" % utils . splitext_plus ( base_file ) [ 0 ] if not os . path . exists ( out_file ) : genes = set ( [ ] ) import pybedtools with utils . open_gzipsafe ( bed_file ) as in_handle : for r ... | Retrieve list of gene names from input BED file . |
29,653 | def _combine_files ( tsv_files , work_dir , data ) : header = "\t" . join ( [ "caller" , "sample" , "chrom" , "start" , "end" , "svtype" , "lof" , "annotation" , "split_read_support" , "paired_support_PE" , "paired_support_PR" ] ) sample = dd . get_sample_name ( data ) out_file = os . path . join ( work_dir , "%s-prior... | Combine multiple priority tsv files into a final sorted output . |
29,654 | def _cnvkit_prioritize ( sample , genes , allele_file , metrics_file ) : mdf = pd . read_table ( metrics_file ) mdf . columns = [ x . lower ( ) for x in mdf . columns ] if len ( genes ) > 0 : mdf = mdf [ mdf [ "gene" ] . str . contains ( "|" . join ( genes ) ) ] mdf = mdf [ [ "chromosome" , "start" , "end" , "gene" , "... | Summarize non - diploid calls with copy numbers and confidence intervals . |
29,655 | def _cnv_prioritize ( data ) : supported = { "cnvkit" : { "inputs" : [ "call_file" , "segmetrics" ] , "fn" : _cnvkit_prioritize } } pcall = None priority_files = None for call in data . get ( "sv" , [ ] ) : if call [ "variantcaller" ] in supported : priority_files = [ call . get ( x ) for x in supported [ call [ "varia... | Perform confidence interval based prioritization for CNVs . |
29,656 | def get_default_jvm_opts ( tmp_dir = None , parallel_gc = False ) : opts = [ "-XX:+UseSerialGC" ] if not parallel_gc else [ ] if tmp_dir : opts . append ( "-Djava.io.tmpdir=%s" % tmp_dir ) return opts | Retrieve default JVM tuning options |
29,657 | def _get_gatk_opts ( config , names , tmp_dir = None , memscale = None , include_gatk = True , parallel_gc = False ) : if include_gatk and "gatk4" in dd . get_tools_off ( { "config" : config } ) : opts = [ "-U" , "LENIENT_VCF_PROCESSING" , "--read_filter" , "BadCigar" , "--read_filter" , "NotPrimaryAlignment" ] else : ... | Retrieve GATK memory specifications moving down a list of potential specifications . |
29,658 | def _clean_java_out ( version_str ) : out = [ ] for line in version_str . decode ( ) . split ( "\n" ) : if line . startswith ( "Picked up" ) : pass if line . find ( "setlocale" ) > 0 : pass else : out . append ( line ) return "\n" . join ( out ) | Remove extra environmental information reported in java when querying for versions . |
29,659 | def get_mutect_version ( mutect_jar ) : cl = [ "java" , "-Xms128m" , "-Xmx256m" ] + get_default_jvm_opts ( ) + [ "-jar" , mutect_jar , "-h" ] with closing ( subprocess . Popen ( cl , stdout = subprocess . PIPE , stderr = subprocess . STDOUT ) . stdout ) as stdout : if "SomaticIndelDetector" in stdout . read ( ) . strip... | Retrieves version from input jar name since there is not an easy way to get MuTect version . Check mutect jar for SomaticIndelDetector which is an Appistry feature |
29,660 | def gatk_cmd ( name , jvm_opts , params , config = None ) : if name == "gatk" : if isinstance ( config , dict ) and "config" not in config : data = { "config" : config } else : data = config if not data or "gatk4" not in dd . get_tools_off ( data ) : return _gatk4_cmd ( jvm_opts , params , data ) else : name = "gatk3" ... | Retrieve PATH to gatk using locally installed java . |
29,661 | def _gatk4_cmd ( jvm_opts , params , data ) : gatk_cmd = utils . which ( os . path . join ( os . path . dirname ( os . path . realpath ( sys . executable ) ) , "gatk" ) ) return "%s && export PATH=%s:\"$PATH\" && gatk --java-options '%s' %s" % ( utils . clear_java_home ( ) , utils . get_java_binpath ( gatk_cmd ) , " " ... | Retrieve unified command for GATK4 using gatk . GATK3 is gatk3 . |
29,662 | def runner_from_path ( cmd , config ) : if cmd . endswith ( "picard" ) : return PicardCmdRunner ( cmd , config ) else : raise ValueError ( "Do not support PATH running for %s" % cmd ) | Simple command line runner that expects a bash cmd in the PATH . |
29,663 | def _set_default_versions ( self , config ) : out = [ ] for name in [ "gatk" , "gatk4" , "picard" , "mutect" ] : v = tz . get_in ( [ "resources" , name , "version" ] , config ) if not v : try : v = programs . get_version ( name , config = config ) except KeyError : v = None out . append ( v ) self . _gatk_version , sel... | Retrieve pre - computed version information for expensive to retrieve versions . Starting up GATK takes a lot of resources so we do it once at start of analysis . |
29,664 | def new_resources ( self , program ) : resources = config_utils . get_resources ( program , self . _config ) if resources . get ( "jvm_opts" ) : self . _jvm_opts = resources . get ( "jvm_opts" ) | Set new resource usage for the given program . This allows customization of memory usage for particular sub - programs of GATK like HaplotypeCaller . |
29,665 | def run_fn ( self , name , * args , ** kwds ) : fn = None to_check = [ picardrun ] for ns in to_check : try : fn = getattr ( ns , name ) break except AttributeError : pass assert fn is not None , "Could not find function %s in %s" % ( name , to_check ) return fn ( self , * args , ** kwds ) | Run pre - built functionality that used Broad tools by name . |
29,666 | def cl_picard ( self , command , options , memscale = None ) : options = [ "%s=%s" % ( x , y ) for x , y in options ] options . append ( "VALIDATION_STRINGENCY=SILENT" ) return self . _get_picard_cmd ( command , memscale = memscale ) + options | Prepare a Picard commandline . |
29,667 | def run ( self , command , options , pipe = False , get_stdout = False , memscale = None ) : cl = self . cl_picard ( command , options , memscale = memscale ) if pipe : subprocess . Popen ( cl ) elif get_stdout : p = subprocess . Popen ( cl , stdout = subprocess . PIPE ) stdout = p . stdout . read ( ) p . wait ( ) p . ... | Run a Picard command with the provided option pairs . |
29,668 | def cl_mutect ( self , params , tmp_dir ) : gatk_jar = self . _get_jar ( "muTect" , [ "mutect" ] ) jvm_opts = config_utils . adjust_opts ( self . _jvm_opts , { "algorithm" : { "memory_adjust" : { "magnitude" : 1.1 , "direction" : "decrease" } } } ) return [ "java" ] + jvm_opts + get_default_jvm_opts ( tmp_dir ) + [ "-j... | Define parameters to run the mutect paired algorithm . |
29,669 | def run_gatk ( self , params , tmp_dir = None , log_error = True , data = None , region = None , memscale = None , parallel_gc = False , ld_preload = False ) : needs_java7 = LooseVersion ( self . get_gatk_version ( ) ) < LooseVersion ( "3.6" ) if needs_java7 : setpath . remove_bcbiopath ( ) with tx_tmpdir ( self . _con... | Top level interface to running a GATK command . |
29,670 | def get_gatk_version ( self ) : if self . _gatk_version is None : self . _set_default_versions ( self . _config ) if "gatk4" not in dd . get_tools_off ( { "config" : self . _config } ) : if self . _gatk4_version is None : self . _gatk4_version = "4.0" return self . _gatk4_version elif self . _gatk_version is not None :... | Retrieve GATK version handling locally and config cached versions . Calling version can be expensive due to all the startup and shutdown of JVMs so we prefer cached version information . |
29,671 | def get_mutect_version ( self ) : if self . _mutect_version is None : mutect_jar = self . _get_jar ( "muTect" , [ "mutect" ] ) self . _mutect_version = get_mutect_version ( mutect_jar ) return self . _mutect_version | Retrieve the Mutect version . |
29,672 | def gatk_major_version ( self ) : full_version = self . get_gatk_version ( ) if full_version . startswith ( "nightly-" ) : return "3.6" parts = full_version . split ( "-" ) if len ( parts ) == 4 : appistry_release , version , subversion , githash = parts elif len ( parts ) == 3 : version , subversion , githash = parts ... | Retrieve the GATK major version handling multiple GATK distributions . |
29,673 | def _get_picard_cmd ( self , command , memscale = None ) : resources = config_utils . get_resources ( "picard" , self . _config ) if memscale : jvm_opts = get_picard_opts ( self . _config , memscale = memscale ) elif resources . get ( "jvm_opts" ) : jvm_opts = resources . get ( "jvm_opts" ) else : jvm_opts = self . _jv... | Retrieve the base Picard command handling both shell scripts and directory of jars . |
29,674 | def _get_jar ( self , command , alts = None , allow_missing = False ) : dirs = [ ] for bdir in [ self . _gatk_dir , self . _picard_ref ] : dirs . extend ( [ bdir , os . path . join ( bdir , os . pardir , "gatk" ) ] ) if alts is None : alts = [ ] for check_cmd in [ command ] + alts : for dir_check in dirs : try : check_... | Retrieve the jar for running the specified command . |
29,675 | def cpmap ( cores = 1 ) : if int ( cores ) == 1 : yield itertools . imap else : if futures is None : raise ImportError ( "concurrent.futures not available" ) pool = futures . ProcessPoolExecutor ( cores ) yield pool . map pool . shutdown ( ) | Configurable parallel map context manager . |
29,676 | def map_wrap ( f ) : @ functools . wraps ( f ) def wrapper ( * args , ** kwargs ) : return f ( * args , ** kwargs ) return wrapper | Wrap standard function to easily pass into map processing . |
29,677 | def unpack_worlds ( items ) : if isinstance ( items [ 0 ] , ( list , tuple ) ) and len ( items [ 0 ] ) == 1 : out = [ ] for d in items : assert len ( d ) == 1 and isinstance ( d [ 0 ] , dict ) , len ( d ) out . append ( d [ 0 ] ) elif isinstance ( items , ( list , tuple ) ) and len ( items ) == 1 and isinstance ( items... | Handle all the ways we can pass multiple samples for back - compatibility . |
29,678 | def safe_makedir ( dname ) : if not dname : return dname num_tries = 0 max_tries = 5 while not os . path . exists ( dname ) : try : os . makedirs ( dname ) except OSError : if num_tries > max_tries : raise num_tries += 1 time . sleep ( 2 ) return dname | Make a directory if it doesn t exist handling concurrent race conditions . |
29,679 | def tmpfile ( * args , ** kwargs ) : ( fd , fname ) = tempfile . mkstemp ( * args , ** kwargs ) try : yield fname finally : os . close ( fd ) if os . path . exists ( fname ) : os . remove ( fname ) | Make a tempfile safely cleaning up file descriptors on completion . |
29,680 | def file_exists ( fname ) : try : return fname and os . path . exists ( fname ) and os . path . getsize ( fname ) > 0 except OSError : return False | Check if a file exists and is non - empty . |
29,681 | def get_size ( path ) : if os . path . isfile ( path ) : return os . path . getsize ( path ) return sum ( get_size ( os . path . join ( path , f ) ) for f in os . listdir ( path ) ) | Returns the size in bytes if path is a file or the size of all files in path if it s a directory . Analogous to du - s . |
29,682 | def read_galaxy_amqp_config ( galaxy_config , base_dir ) : galaxy_config = add_full_path ( galaxy_config , base_dir ) config = six . moves . configparser . ConfigParser ( ) config . read ( galaxy_config ) amqp_config = { } for option in config . options ( "galaxy_amqp" ) : amqp_config [ option ] = config . get ( "galax... | Read connection information on the RabbitMQ server from Galaxy config . |
29,683 | def move_safe ( origin , target ) : if origin == target : return origin if file_exists ( target ) : return target shutil . move ( origin , target ) return target | Move file skip if exists |
29,684 | def file_plus_index ( fname ) : exts = { ".vcf" : ".idx" , ".bam" : ".bai" , ".vcf.gz" : ".tbi" , ".bed.gz" : ".tbi" , ".fq.gz" : ".gbi" } ext = splitext_plus ( fname ) [ - 1 ] if ext in exts : return [ fname , fname + exts [ ext ] ] else : return [ fname ] | Convert a file name into the file plus required indexes . |
29,685 | def remove_plus ( orig ) : for ext in [ "" , ".idx" , ".gbi" , ".tbi" , ".bai" ] : if os . path . exists ( orig + ext ) : remove_safe ( orig + ext ) | Remove a fils including biological index files . |
29,686 | def copy_plus ( orig , new ) : for ext in [ "" , ".idx" , ".gbi" , ".tbi" , ".bai" ] : if os . path . exists ( orig + ext ) and ( not os . path . lexists ( new + ext ) or not os . path . exists ( new + ext ) ) : shutil . copyfile ( orig + ext , new + ext ) | Copy a fils including biological index files . |
29,687 | def merge_config_files ( fnames ) : def _load_yaml ( fname ) : with open ( fname ) as in_handle : config = yaml . safe_load ( in_handle ) return config out = _load_yaml ( fnames [ 0 ] ) for fname in fnames [ 1 : ] : cur = _load_yaml ( fname ) for k , v in cur . items ( ) : if k in out and isinstance ( out [ k ] , dict ... | Merge configuration files preferring definitions in latter files . |
29,688 | def deepish_copy ( org ) : out = dict ( ) . fromkeys ( org ) for k , v in org . items ( ) : if isinstance ( v , dict ) : out [ k ] = deepish_copy ( v ) else : try : out [ k ] = v . copy ( ) except AttributeError : try : out [ k ] = v [ : ] except TypeError : out [ k ] = v return out | Improved speed deep copy for dictionaries of simple python types . |
29,689 | def reservoir_sample ( stream , num_items , item_parser = lambda x : x ) : kept = [ ] for index , item in enumerate ( stream ) : if index < num_items : kept . append ( item_parser ( item ) ) else : r = random . randint ( 0 , index ) if r < num_items : kept [ r ] = item_parser ( item ) return kept | samples num_items from the stream keeping each with equal probability |
29,690 | def dictapply ( d , fn ) : for k , v in d . items ( ) : if isinstance ( v , dict ) : v = dictapply ( v , fn ) else : d [ k ] = fn ( v ) return d | apply a function to all non - dict values in a dictionary |
29,691 | def Rscript_cmd ( ) : rscript = which ( os . path . join ( get_bcbio_bin ( ) , "Rscript" ) ) if rscript : return rscript else : return which ( "Rscript" ) | Retrieve path to locally installed Rscript or first in PATH . |
29,692 | def R_package_resource ( package , resource ) : package_path = R_package_path ( package ) if not package_path : return None package_resource = os . path . join ( package_path , resource ) if not file_exists ( package_resource ) : return None else : return package_resource | return a path to an R package resource if it is available |
29,693 | def get_java_binpath ( cmd = None ) : if os . environ . get ( "BCBIO_JAVA_HOME" ) : test_cmd = os . path . join ( os . environ [ "BCBIO_JAVA_HOME" ] , "bin" , "java" ) if os . path . exists ( test_cmd ) : cmd = test_cmd if not cmd : cmd = Rscript_cmd ( ) return os . path . dirname ( cmd ) | Retrieve path for java to use handling custom BCBIO_JAVA_HOME |
29,694 | def clear_java_home ( ) : if os . environ . get ( "BCBIO_JAVA_HOME" ) : test_cmd = os . path . join ( os . environ [ "BCBIO_JAVA_HOME" ] , "bin" , "java" ) if os . path . exists ( test_cmd ) : return "export JAVA_HOME=%s" % os . environ [ "BCBIO_JAVA_HOME" ] return "unset JAVA_HOME" | Clear JAVA_HOME environment or reset to BCBIO_JAVA_HOME . |
29,695 | def perl_cmd ( ) : perl = which ( os . path . join ( get_bcbio_bin ( ) , "perl" ) ) if perl : return perl else : return which ( "perl" ) | Retrieve path to locally installed conda Perl or first in PATH . |
29,696 | def get_perl_exports ( tmpdir = None ) : perl_path = os . path . dirname ( perl_cmd ( ) ) out = "unset PERL5LIB && export PATH=%s:\"$PATH\"" % ( perl_path ) if tmpdir : out += " && export TMPDIR=%s" % ( tmpdir ) return out | Environmental exports to use conda installed perl . |
29,697 | def get_all_conda_bins ( ) : bcbio_bin = get_bcbio_bin ( ) conda_dir = os . path . dirname ( bcbio_bin ) if os . path . join ( "anaconda" , "envs" ) in conda_dir : conda_dir = os . path . join ( conda_dir [ : conda_dir . rfind ( os . path . join ( "anaconda" , "envs" ) ) ] , "anaconda" ) return [ bcbio_bin ] + list ( g... | Retrieve all possible conda bin directories including environments . |
29,698 | def get_program_python ( cmd ) : full_cmd = os . path . realpath ( which ( cmd ) ) cmd_python = os . path . join ( os . path . dirname ( full_cmd ) , "python" ) env_python = None if "envs" in cmd_python : parts = cmd_python . split ( os . sep ) env_python = os . path . join ( os . sep . join ( parts [ : parts . index (... | Get the full path to a python version linked to the command . |
29,699 | def local_path_export ( at_start = True , env_cmd = None ) : paths = [ get_bcbio_bin ( ) ] if env_cmd : env_path = os . path . dirname ( get_program_python ( env_cmd ) ) if env_path not in paths : paths . insert ( 0 , env_path ) if at_start : return "export PATH=%s:\"$PATH\" && " % ( ":" . join ( paths ) ) else : retur... | Retrieve paths to local install also including environment paths if env_cmd included . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.