idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
900
def rename_motifs ( motifs , stats = None ) : final_motifs = [ ] for i , motif in enumerate ( motifs ) : old = str ( motif ) motif . id = "GimmeMotifs_{}" . format ( i + 1 ) final_motifs . append ( motif ) if stats : stats [ str ( motif ) ] = stats [ old ] . copy ( ) if stats : return final_motifs , stats else : return final_motifs
Rename motifs to GimmeMotifs_1 .. GimmeMotifs_N . If stats object is passed stats will be copied .
901
def register_db ( cls , dbname ) : def decorator ( subclass ) : cls . _dbs [ dbname ] = subclass subclass . name = dbname return subclass return decorator
Register method to keep list of dbs .
902
def create ( cls , name , ncpus = None ) : try : return cls . _predictors [ name . lower ( ) ] ( ncpus = ncpus ) except KeyError : raise Exception ( "Unknown class" )
Create a Moap instance based on the predictor name .
903
def register_predictor ( cls , name ) : def decorator ( subclass ) : cls . _predictors [ name . lower ( ) ] = subclass subclass . name = name . lower ( ) return subclass return decorator
Register method to keep list of predictors .
904
def list_classification_predictors ( self ) : preds = [ self . create ( x ) for x in self . _predictors . keys ( ) ] return [ x . name for x in preds if x . ptype == "classification" ]
List available classification predictors .
905
def _activate ( self ) : if six . callable ( self . streamer ) : self . stream_ = self . streamer ( * ( self . args ) , ** ( self . kwargs ) ) else : self . stream_ = iter ( self . streamer )
Activates the stream .
906
def iterate ( self , max_iter = None ) : with self as active_streamer : for n , obj in enumerate ( active_streamer . stream_ ) : if max_iter is not None and n >= max_iter : break yield obj
Instantiate an iterator .
907
def cycle ( self , max_iter = None ) : count = 0 while True : for obj in self . iterate ( ) : count += 1 if max_iter is not None and count > max_iter : return yield obj
Iterate from the streamer infinitely .
908
def rank_motifs ( stats , metrics = ( "roc_auc" , "recall_at_fdr" ) ) : rank = { } combined_metrics = [ ] motif_ids = stats . keys ( ) background = list ( stats . values ( ) ) [ 0 ] . keys ( ) for metric in metrics : mean_metric_stats = [ np . mean ( [ stats [ m ] [ bg ] [ metric ] for bg in background ] ) for m in motif_ids ] ranked_metric_stats = rankdata ( mean_metric_stats ) combined_metrics . append ( ranked_metric_stats ) for motif , val in zip ( motif_ids , np . mean ( combined_metrics , 0 ) ) : rank [ motif ] = val return rank
Determine mean rank of motifs based on metrics .
909
def write_stats ( stats , fname , header = None ) : for bg in list ( stats . values ( ) ) [ 0 ] . keys ( ) : f = open ( fname . format ( bg ) , "w" ) if header : f . write ( header ) stat_keys = sorted ( list ( list ( stats . values ( ) ) [ 0 ] . values ( ) ) [ 0 ] . keys ( ) ) f . write ( "{}\t{}\n" . format ( "Motif" , "\t" . join ( stat_keys ) ) ) for motif in stats : m_stats = stats . get ( str ( motif ) , { } ) . get ( bg ) if m_stats : f . write ( "{}\t{}\n" . format ( "_" . join ( motif . split ( "_" ) [ : - 1 ] ) , "\t" . join ( [ str ( m_stats [ k ] ) for k in stat_keys ] ) ) ) else : logger . warn ( "No stats for motif {0}, skipping this motif!" . format ( motif . id ) ) f . close ( ) return
write motif statistics to text file .
910
def get_roc_values ( motif , fg_file , bg_file ) : try : stats = calc_stats ( motif , fg_file , bg_file , stats = [ "roc_values" ] , ncpus = 1 ) ( x , y ) = list ( stats . values ( ) ) [ 0 ] [ "roc_values" ] return None , x , y except Exception as e : print ( motif ) print ( motif . id ) raise error = e return error , [ ] , [ ]
Calculate ROC AUC values for ROC plots .
911
def create_roc_plots ( pwmfile , fgfa , background , outdir ) : motifs = read_motifs ( pwmfile , fmt = "pwm" , as_dict = True ) ncpus = int ( MotifConfig ( ) . get_default_params ( ) [ 'ncpus' ] ) pool = Pool ( processes = ncpus ) jobs = { } for bg , fname in background . items ( ) : for m_id , m in motifs . items ( ) : k = "{}_{}" . format ( str ( m ) , bg ) jobs [ k ] = pool . apply_async ( get_roc_values , ( motifs [ m_id ] , fgfa , fname , ) ) imgdir = os . path . join ( outdir , "images" ) if not os . path . exists ( imgdir ) : os . mkdir ( imgdir ) roc_img_file = os . path . join ( outdir , "images" , "{}_roc.{}.png" ) for motif in motifs . values ( ) : for bg in background : k = "{}_{}" . format ( str ( motif ) , bg ) error , x , y = jobs [ k ] . get ( ) if error : logger . error ( "Error in thread: %s" , error ) logger . error ( "Motif: %s" , motif ) sys . exit ( 1 ) roc_plot ( roc_img_file . format ( motif . id , bg ) , x , y )
Make ROC plots for all motifs .
912
def _create_text_report ( inputfile , motifs , closest_match , stats , outdir ) : my_stats = { } for motif in motifs : match = closest_match [ motif . id ] my_stats [ str ( motif ) ] = { } for bg in list ( stats . values ( ) ) [ 0 ] . keys ( ) : if str ( motif ) not in stats : logger . error ( "####" ) logger . error ( "{} not found" . format ( str ( motif ) ) ) for s in sorted ( stats . keys ( ) ) : logger . error ( s ) logger . error ( "####" ) else : my_stats [ str ( motif ) ] [ bg ] = stats [ str ( motif ) ] [ bg ] . copy ( ) my_stats [ str ( motif ) ] [ bg ] [ "best_match" ] = "_" . join ( match [ 0 ] . split ( "_" ) [ : - 1 ] ) my_stats [ str ( motif ) ] [ bg ] [ "best_match_pvalue" ] = match [ 1 ] [ - 1 ] header = ( "# GimmeMotifs version {}\n" "# Inputfile: {}\n" ) . format ( __version__ , inputfile ) write_stats ( my_stats , os . path . join ( outdir , "stats.{}.txt" ) , header = header )
Create text report of motifs with statistics and database match .
913
def axes_off ( ax ) : ax . set_frame_on ( False ) ax . axes . get_yaxis ( ) . set_visible ( False ) ax . axes . get_xaxis ( ) . set_visible ( False )
Get rid of all axis ticks lines etc .
914
def motif_tree_plot ( outfile , tree , data , circle = True , vmin = None , vmax = None , dpi = 300 ) : try : from ete3 import Tree , faces , AttrFace , TreeStyle , NodeStyle except ImportError : print ( "Please install ete3 to use this functionality" ) sys . exit ( 1 ) t , ts = _get_motif_tree ( tree , data , circle , vmin , vmax ) t . render ( outfile , tree_style = ts , w = 100 , dpi = dpi , units = "mm" ) if circle : img = Image . open ( outfile ) size = img . size [ 0 ] spacer = 50 img . crop ( ( 0 , 0 , size , size / 2 + spacer ) ) . save ( outfile )
Plot a phylogenetic tree
915
def check_bed_file ( fname ) : if not os . path . exists ( fname ) : logger . error ( "Inputfile %s does not exist!" , fname ) sys . exit ( 1 ) for i , line in enumerate ( open ( fname ) ) : if line . startswith ( "#" ) or line . startswith ( "track" ) or line . startswith ( "browser" ) : pass else : vals = line . strip ( ) . split ( "\t" ) if len ( vals ) < 3 : logger . error ( "Expecting tab-seperated values (chromosome<tab>start<tab>end) on line %s of file %s" , i + 1 , fname ) sys . exit ( 1 ) try : start , end = int ( vals [ 1 ] ) , int ( vals [ 2 ] ) except ValueError : logger . error ( "No valid integer coordinates on line %s of file %s" , i + 1 , fname ) sys . exit ( 1 ) if len ( vals ) > 3 : try : float ( vals [ 3 ] ) except ValueError : pass
Check if the inputfile is a valid bed - file
916
def check_denovo_input ( inputfile , params ) : background = params [ "background" ] input_type = determine_file_type ( inputfile ) if input_type == "fasta" : valid_bg = FA_VALID_BGS elif input_type in [ "bed" , "narrowpeak" ] : genome = params [ "genome" ] valid_bg = BED_VALID_BGS if "genomic" in background or "gc" in background : Genome ( genome ) check_bed_file ( inputfile ) else : sys . stderr . write ( "Format of inputfile {} not recognized.\n" . format ( inputfile ) ) sys . stderr . write ( "Input should be FASTA, BED or narrowPeak.\n" ) sys . stderr . write ( "See https://genome.ucsc.edu/FAQ/FAQformat.html for specifications.\n" ) sys . exit ( 1 ) for bg in background : if not bg in valid_bg : logger . info ( "Input type is %s, ignoring background type '%s'" , input_type , bg ) background = [ bg for bg in background if bg in valid_bg ] if len ( background ) == 0 : logger . error ( "No valid backgrounds specified!" ) sys . exit ( 1 ) return input_type , background
Check if an input file is valid which means BED narrowPeak or FASTA
917
def scan_to_best_match ( fname , motifs , ncpus = None , genome = None , score = False ) : s = Scanner ( ncpus = ncpus ) s . set_motifs ( motifs ) s . set_threshold ( threshold = 0.0 ) if genome : s . set_genome ( genome ) if isinstance ( motifs , six . string_types ) : motifs = read_motifs ( motifs ) logger . debug ( "scanning %s..." , fname ) result = dict ( [ ( m . id , [ ] ) for m in motifs ] ) if score : it = s . best_score ( fname ) else : it = s . best_match ( fname ) for scores in it : for motif , score in zip ( motifs , scores ) : result [ motif . id ] . append ( score ) del s return result
Scan a FASTA file with motifs .
918
def set_background ( self , fname = None , genome = None , length = 200 , nseq = 10000 ) : length = int ( length ) if genome and fname : raise ValueError ( "Need either genome or filename for background." ) if fname : if not os . path . exists ( fname ) : raise IOError ( "Background file {} does not exist!" . format ( fname ) ) self . background = Fasta ( fname ) self . background_hash = file_checksum ( fname ) return if not genome : if self . genome : genome = self . genome logger . info ( "Using default background: genome {} with length {}" . format ( genome , length ) ) else : raise ValueError ( "Need either genome or filename for background." ) logger . info ( "Using background: genome {} with length {}" . format ( genome , length ) ) with Cache ( CACHE_DIR ) as cache : self . background_hash = "{}\{}" . format ( genome , int ( length ) ) fa = cache . get ( self . background_hash ) if not fa : fa = RandomGenomicFasta ( genome , length , nseq ) cache . set ( self . background_hash , fa ) self . background = fa
Set the background to use for FPR and z - score calculations .
919
def set_threshold ( self , fpr = None , threshold = None ) : if threshold and fpr : raise ValueError ( "Need either fpr or threshold." ) if fpr : fpr = float ( fpr ) if not ( 0.0 < fpr < 1.0 ) : raise ValueError ( "Parameter fpr should be between 0 and 1" ) if not self . motifs : raise ValueError ( "please run set_motifs() first" ) thresholds = { } motifs = read_motifs ( self . motifs ) if threshold is not None : self . threshold = parse_threshold_values ( self . motifs , threshold ) return if not self . background : try : self . set_background ( ) except : raise ValueError ( "please run set_background() first" ) seqs = self . background . seqs with Cache ( CACHE_DIR ) as cache : scan_motifs = [ ] for motif in motifs : k = "{}|{}|{:.4f}" . format ( motif . hash ( ) , self . background_hash , fpr ) threshold = cache . get ( k ) if threshold is None : scan_motifs . append ( motif ) else : if np . isclose ( threshold , motif . pwm_max_score ( ) ) : thresholds [ motif . id ] = None elif np . isclose ( threshold , motif . pwm_min_score ( ) ) : thresholds [ motif . id ] = 0.0 else : thresholds [ motif . id ] = threshold if len ( scan_motifs ) > 0 : logger . info ( "Determining FPR-based threshold" ) for motif , threshold in self . _threshold_from_seqs ( scan_motifs , seqs , fpr ) : k = "{}|{}|{:.4f}" . format ( motif . hash ( ) , self . background_hash , fpr ) cache . set ( k , threshold ) if np . isclose ( threshold , motif . pwm_max_score ( ) ) : thresholds [ motif . id ] = None elif np . isclose ( threshold , motif . pwm_min_score ( ) ) : thresholds [ motif . id ] = 0.0 else : thresholds [ motif . id ] = threshold self . threshold_str = "{}_{}_{}" . format ( fpr , threshold , self . background_hash ) self . threshold = thresholds
Set motif scanning threshold based on background sequences .
920
def best_score ( self , seqs , scan_rc = True , normalize = False ) : self . set_threshold ( threshold = 0.0 ) if normalize and len ( self . meanstd ) == 0 : self . set_meanstd ( ) means = np . array ( [ self . meanstd [ m ] [ 0 ] for m in self . motif_ids ] ) stds = np . array ( [ self . meanstd [ m ] [ 1 ] for m in self . motif_ids ] ) for matches in self . scan ( seqs , 1 , scan_rc ) : scores = np . array ( [ sorted ( m , key = lambda x : x [ 0 ] ) [ 0 ] [ 0 ] for m in matches if len ( m ) > 0 ] ) if normalize : scores = ( scores - means ) / stds yield scores
give the score of the best match of each motif in each sequence returns an iterator of lists containing floats
921
def roc ( args ) : outputfile = args . outfile if outputfile and not outputfile . endswith ( ".png" ) : outputfile += ".png" motifs = read_motifs ( args . pwmfile , fmt = "pwm" ) ids = [ ] if args . ids : ids = args . ids . split ( "," ) else : ids = [ m . id for m in motifs ] motifs = [ m for m in motifs if ( m . id in ids ) ] stats = [ "phyper_at_fpr" , "roc_auc" , "pr_auc" , "enr_at_fpr" , "recall_at_fdr" , "roc_values" , "matches_at_fpr" , ] plot_x = [ ] plot_y = [ ] legend = [ ] f_out = sys . stdout if args . outdir : if not os . path . exists ( args . outdir ) : os . makedirs ( args . outdir ) f_out = open ( args . outdir + "/gimme.roc.report.txt" , "w" ) f_out . write ( "Motif\t# matches\t# matches background\tP-value\tlog10 P-value\tROC AUC\tPR AUC\tEnr. at 1% FPR\tRecall at 10% FDR\n" ) for motif_stats in calc_stats_iterator ( motifs , args . sample , args . background , genome = args . genome , stats = stats , ncpus = args . ncpus ) : for motif in motifs : if str ( motif ) in motif_stats : if outputfile : x , y = motif_stats [ str ( motif ) ] [ "roc_values" ] plot_x . append ( x ) plot_y . append ( y ) legend . append ( motif . id ) log_pvalue = np . inf if motif_stats [ str ( motif ) ] [ "phyper_at_fpr" ] > 0 : log_pvalue = - np . log10 ( motif_stats [ str ( motif ) ] [ "phyper_at_fpr" ] ) f_out . write ( "{}\t{:d}\t{:d}\t{:.2e}\t{:.3f}\t{:.3f}\t{:.3f}\t{:.2f}\t{:0.4f}\n" . format ( motif . id , motif_stats [ str ( motif ) ] [ "matches_at_fpr" ] [ 0 ] , motif_stats [ str ( motif ) ] [ "matches_at_fpr" ] [ 1 ] , motif_stats [ str ( motif ) ] [ "phyper_at_fpr" ] , log_pvalue , motif_stats [ str ( motif ) ] [ "roc_auc" ] , motif_stats [ str ( motif ) ] [ "pr_auc" ] , motif_stats [ str ( motif ) ] [ "enr_at_fpr" ] , motif_stats [ str ( motif ) ] [ "recall_at_fdr" ] , ) ) f_out . close ( ) if args . outdir : html_report ( args . outdir , args . outdir + "/gimme.roc.report.txt" , args . pwmfile , 0.01 , ) if outputfile : roc_plot ( outputfile , plot_x , plot_y , ids = legend )
Calculate ROC_AUC and other metrics and optionally plot ROC curve .
922
def seqcor ( m1 , m2 , seq = None ) : l1 = len ( m1 ) l2 = len ( m2 ) l = max ( l1 , l2 ) if seq is None : seq = RCDB L = len ( seq ) result1 = pfmscan ( seq , m1 . pwm , m1 . pwm_min_score ( ) , len ( seq ) , False , True ) result2 = pfmscan ( seq , m2 . pwm , m2 . pwm_min_score ( ) , len ( seq ) , False , True ) result3 = pfmscan ( seq , m2 . rc ( ) . pwm , m2 . rc ( ) . pwm_min_score ( ) , len ( seq ) , False , True ) result1 = np . array ( result1 ) result2 = np . array ( result2 ) result3 = np . array ( result3 ) c = [ ] for i in range ( l1 - l1 // 3 ) : c . append ( [ 1 - distance . correlation ( result1 [ : L - l - i ] , result2 [ i : L - l ] ) , i , 1 ] ) c . append ( [ 1 - distance . correlation ( result1 [ : L - l - i ] , result3 [ i : L - l ] ) , i , - 1 ] ) for i in range ( l2 - l2 // 3 ) : c . append ( [ 1 - distance . correlation ( result1 [ i : L - l ] , result2 [ : L - l - i ] ) , - i , 1 ] ) c . append ( [ 1 - distance . correlation ( result1 [ i : L - l ] , result3 [ : L - l - i ] ) , - i , - 1 ] ) return sorted ( c , key = lambda x : x [ 0 ] ) [ - 1 ]
Calculates motif similarity based on Pearson correlation of scores .
923
def compare_motifs ( self , m1 , m2 , match = "total" , metric = "wic" , combine = "mean" , pval = False ) : if metric == "seqcor" : return seqcor ( m1 , m2 ) elif match == "partial" : if pval : return self . pvalue ( m1 , m2 , "total" , metric , combine , self . max_partial ( m1 . pwm , m2 . pwm , metric , combine ) ) elif metric in [ "pcc" , "ed" , "distance" , "wic" , "chisq" , "ssd" ] : return self . max_partial ( m1 . pwm , m2 . pwm , metric , combine ) else : return self . max_partial ( m1 . pfm , m2 . pfm , metric , combine ) elif match == "total" : if pval : return self . pvalue ( m1 , m2 , match , metric , combine , self . max_total ( m1 . pwm , m2 . pwm , metric , combine ) ) elif metric in [ "pcc" , 'akl' ] : return self . max_total ( m1 . wiggle_pwm ( ) , m2 . wiggle_pwm ( ) , metric , combine ) elif metric in [ "ed" , "distance" , "wic" , "chisq" , "pcc" , "ssd" ] : return self . max_total ( m1 . pwm , m2 . pwm , metric , combine ) else : return self . max_total ( m1 . pfm , m2 . pfm , metric , combine ) elif match == "subtotal" : if metric in [ "pcc" , "ed" , "distance" , "wic" , "chisq" , "ssd" ] : return self . max_subtotal ( m1 . pwm , m2 . pwm , metric , combine ) else : return self . max_subtotal ( m1 . pfm , m2 . pfm , metric , combine )
Compare two motifs . The similarity metric can be any of seqcor pcc ed distance wic chisq akl or ssd . If match is total the similarity score is calculated for the whole match including positions that are not present in both motifs . If match is partial or subtotal only the matching psotiions are used to calculate the score . The score of individual position is combined using either the mean or the sum .
924
def get_all_scores ( self , motifs , dbmotifs , match , metric , combine , pval = False , parallel = True , trim = None , ncpus = None ) : if trim : for m in motifs : m . trim ( trim ) for m in dbmotifs : m . trim ( trim ) scores = { } if parallel : if ncpus is None : ncpus = int ( MotifConfig ( ) . get_default_params ( ) [ "ncpus" ] ) pool = Pool ( processes = ncpus , maxtasksperchild = 1000 ) batch_len = len ( dbmotifs ) // ncpus if batch_len <= 0 : batch_len = 1 jobs = [ ] for i in range ( 0 , len ( dbmotifs ) , batch_len ) : p = pool . apply_async ( _get_all_scores , args = ( self , motifs , dbmotifs [ i : i + batch_len ] , match , metric , combine , pval ) ) jobs . append ( p ) pool . close ( ) for job in jobs : result = job . get ( ) for m1 , v in result . items ( ) : for m2 , s in v . items ( ) : if m1 not in scores : scores [ m1 ] = { } scores [ m1 ] [ m2 ] = s pool . join ( ) else : scores = _get_all_scores ( self , motifs , dbmotifs , match , metric , combine , pval ) return scores
Pairwise comparison of a set of motifs compared to reference motifs .
925
def get_closest_match ( self , motifs , dbmotifs = None , match = "partial" , metric = "wic" , combine = "mean" , parallel = True , ncpus = None ) : if dbmotifs is None : pwm = self . config . get_default_params ( ) [ "motif_db" ] pwmdir = self . config . get_motif_dir ( ) dbmotifs = os . path . join ( pwmdir , pwm ) motifs = parse_motifs ( motifs ) dbmotifs = parse_motifs ( dbmotifs ) dbmotif_lookup = dict ( [ ( m . id , m ) for m in dbmotifs ] ) scores = self . get_all_scores ( motifs , dbmotifs , match , metric , combine , parallel = parallel , ncpus = ncpus ) for motif in scores : scores [ motif ] = sorted ( scores [ motif ] . items ( ) , key = lambda x : x [ 1 ] [ 0 ] ) [ - 1 ] for motif in motifs : dbmotif , score = scores [ motif . id ] pval , pos , orient = self . compare_motifs ( motif , dbmotif_lookup [ dbmotif ] , match , metric , combine , True ) scores [ motif . id ] = [ dbmotif , ( list ( score ) + [ pval ] ) ] return scores
Return best match in database for motifs .
926
def list_regions ( service ) : for region in service . regions ( ) : print '%(name)s: %(endpoint)s' % { 'name' : region . name , 'endpoint' : region . endpoint , }
List regions for the service
927
def elb_table ( balancers ) : t = prettytable . PrettyTable ( [ 'Name' , 'DNS' , 'Ports' , 'Zones' , 'Created' ] ) t . align = 'l' for b in balancers : ports = [ '%s: %s -> %s' % ( l [ 2 ] , l [ 0 ] , l [ 1 ] ) for l in b . listeners ] ports = '\n' . join ( ports ) zones = '\n' . join ( b . availability_zones ) t . add_row ( [ b . name , b . dns_name , ports , zones , b . created_time ] ) return t
Print nice looking table of information from list of load balancers
928
def ec2_table ( instances ) : t = prettytable . PrettyTable ( [ 'ID' , 'State' , 'Monitored' , 'Image' , 'Name' , 'Type' , 'SSH key' , 'DNS' ] ) t . align = 'l' for i in instances : name = i . tags . get ( 'Name' , '' ) t . add_row ( [ i . id , i . state , i . monitored , i . image_id , name , i . instance_type , i . key_name , i . dns_name ] ) return t
Print nice looking table of information from list of instances
929
def ec2_image_table ( images ) : t = prettytable . PrettyTable ( [ 'ID' , 'State' , 'Name' , 'Owner' , 'Root device' , 'Is public' , 'Description' ] ) t . align = 'l' for i in images : t . add_row ( [ i . id , i . state , i . name , i . ownerId , i . root_device_type , i . is_public , i . description ] ) return t
Print nice looking table of information from images
930
def ec2_fab ( service , args ) : instance_ids = args . instances instances = service . list ( elb = args . elb , instance_ids = instance_ids ) hosts = service . resolve_hosts ( instances ) fab . env . hosts = hosts fab . env . key_filename = settings . get ( 'SSH' , 'KEY_FILE' ) fab . env . user = settings . get ( 'SSH' , 'USER' , getpass . getuser ( ) ) fab . env . parallel = True fabfile = find_fabfile ( args . file ) if not fabfile : print 'Couldn\'t find any fabfiles!' return fab . env . real_fabile = fabfile docstring , callables , default = load_fabfile ( fabfile ) fab_state . commands . update ( callables ) commands_to_run = parse_arguments ( args . methods ) for name , args , kwargs , arg_hosts , arg_roles , arg_exclude_hosts in commands_to_run : fab . execute ( name , hosts = arg_hosts , roles = arg_roles , exclude_hosts = arg_exclude_hosts , * args , ** kwargs )
Run Fabric commands against EC2 instances
931
def buffer_stream ( stream , buffer_size , partial = False , axis = None ) : data = [ ] count = 0 for item in stream : data . append ( item ) count += 1 if count < buffer_size : continue try : yield __stack_data ( data , axis = axis ) except ( TypeError , AttributeError ) : raise DataError ( "Malformed data stream: {}" . format ( data ) ) finally : data = [ ] count = 0 if data and partial : yield __stack_data ( data , axis = axis )
Buffer data from an stream into one data object .
932
def tuples ( stream , * keys ) : if not keys : raise PescadorError ( 'Unable to generate tuples from ' 'an empty item set' ) for data in stream : try : yield tuple ( data [ key ] for key in keys ) except TypeError : raise DataError ( "Malformed data stream: {}" . format ( data ) )
Reformat data as tuples .
933
def keras_tuples ( stream , inputs = None , outputs = None ) : flatten_inputs , flatten_outputs = False , False if inputs and isinstance ( inputs , six . string_types ) : inputs = [ inputs ] flatten_inputs = True if outputs and isinstance ( outputs , six . string_types ) : outputs = [ outputs ] flatten_outputs = True inputs , outputs = ( inputs or [ ] ) , ( outputs or [ ] ) if not inputs + outputs : raise PescadorError ( 'At least one key must be given for ' '`inputs` or `outputs`' ) for data in stream : try : x = list ( data [ key ] for key in inputs ) or None if len ( inputs ) == 1 and flatten_inputs : x = x [ 0 ] y = list ( data [ key ] for key in outputs ) or None if len ( outputs ) == 1 and flatten_outputs : y = y [ 0 ] yield ( x , y ) except TypeError : raise DataError ( "Malformed data stream: {}" . format ( data ) )
Reformat data objects as keras - compatible tuples .
934
def location ( args ) : fastafile = args . fastafile pwmfile = args . pwmfile lwidth = args . width if not lwidth : f = Fasta ( fastafile ) lwidth = len ( f . items ( ) [ 0 ] [ 1 ] ) f = None jobs = [ ] motifs = pwmfile_to_motifs ( pwmfile ) ids = [ motif . id for motif in motifs ] if args . ids : ids = args . ids . split ( "," ) n_cpus = int ( MotifConfig ( ) . get_default_params ( ) [ "ncpus" ] ) pool = Pool ( processes = n_cpus , maxtasksperchild = 1000 ) for motif in motifs : if motif . id in ids : outfile = os . path . join ( "%s_histogram" % motif . id ) jobs . append ( pool . apply_async ( motif_localization , ( fastafile , motif , lwidth , outfile , args . cutoff ) ) ) for job in jobs : job . get ( )
Creates histrogram of motif location .
935
def which ( fname ) : if "PATH" not in os . environ or not os . environ [ "PATH" ] : path = os . defpath else : path = os . environ [ "PATH" ] for p in [ fname ] + [ os . path . join ( x , fname ) for x in path . split ( os . pathsep ) ] : p = os . path . abspath ( p ) if os . access ( p , os . X_OK ) and not os . path . isdir ( p ) : return p p = sp . Popen ( "locate %s" % fname , shell = True , stdout = sp . PIPE , stderr = sp . PIPE ) ( stdout , stderr ) = p . communicate ( ) if not stderr : for p in stdout . decode ( ) . split ( "\n" ) : if ( os . path . basename ( p ) == fname ) and ( os . access ( p , os . X_OK ) ) and ( not os . path . isdir ( p ) ) : return p
Find location of executable .
936
def find_by_ext ( dirname , ext ) : try : files = os . listdir ( dirname ) except OSError : if os . path . exists ( dirname ) : cmd = "find {0} -maxdepth 1 -name \"*\"" . format ( dirname ) p = sp . Popen ( cmd , shell = True , stdout = sp . PIPE , stderr = sp . PIPE ) stdout , _stderr = p . communicate ( ) files = [ os . path . basename ( fname ) for fname in stdout . decode ( ) . splitlines ( ) ] else : raise retfiles = [ os . path . join ( dirname , fname ) for fname in files if os . path . splitext ( fname ) [ - 1 ] in ext ] return retfiles
Find all files in a directory by extension .
937
def default_motifs ( ) : config = MotifConfig ( ) d = config . get_motif_dir ( ) m = config . get_default_params ( ) [ 'motif_db' ] if not d or not m : raise ValueError ( "default motif database not configured" ) fname = os . path . join ( d , m ) with open ( fname ) as f : motifs = read_motifs ( f ) return motifs
Return list of Motif instances from default motif database .
938
def motif_from_align ( align ) : width = len ( align [ 0 ] ) nucs = { "A" : 0 , "C" : 1 , "G" : 2 , "T" : 3 } pfm = [ [ 0 for _ in range ( 4 ) ] for _ in range ( width ) ] for row in align : for i in range ( len ( row ) ) : pfm [ i ] [ nucs [ row [ i ] ] ] += 1 m = Motif ( pfm ) m . align = align [ : ] return m
Convert alignment to motif .
939
def motif_from_consensus ( cons , n = 12 ) : width = len ( cons ) nucs = { "A" : 0 , "C" : 1 , "G" : 2 , "T" : 3 } pfm = [ [ 0 for _ in range ( 4 ) ] for _ in range ( width ) ] m = Motif ( ) for i , char in enumerate ( cons ) : for nuc in m . iupac [ char . upper ( ) ] : pfm [ i ] [ nucs [ nuc ] ] = n / len ( m . iupac [ char . upper ( ) ] ) m = Motif ( pfm ) m . id = cons return m
Convert consensus sequence to motif .
940
def parse_motifs ( motifs ) : if isinstance ( motifs , six . string_types ) : with open ( motifs ) as f : if motifs . endswith ( "pwm" ) or motifs . endswith ( "pfm" ) : motifs = read_motifs ( f , fmt = "pwm" ) elif motifs . endswith ( "transfac" ) : motifs = read_motifs ( f , fmt = "transfac" ) else : motifs = read_motifs ( f ) elif isinstance ( motifs , Motif ) : motifs = [ motifs ] else : if not isinstance ( list ( motifs ) [ 0 ] , Motif ) : raise ValueError ( "Not a list of motifs" ) return list ( motifs )
Parse motifs in a variety of formats to return a list of motifs .
941
def read_motifs ( infile = None , fmt = "pwm" , as_dict = False ) : if infile is None or isinstance ( infile , six . string_types ) : infile = pwmfile_location ( infile ) with open ( infile ) as f : motifs = _read_motifs_from_filehandle ( f , fmt ) else : motifs = _read_motifs_from_filehandle ( infile , fmt ) if as_dict : motifs = { m . id : m for m in motifs } return motifs
Read motifs from a file or stream or file - like object .
942
def information_content ( self ) : ic = 0 for row in self . pwm : ic += 2.0 + np . sum ( [ row [ x ] * log ( row [ x ] ) / log ( 2 ) for x in range ( 4 ) if row [ x ] > 0 ] ) return ic
Return the total information content of the motif .
943
def pwm_min_score ( self ) : if self . min_score is None : score = 0 for row in self . pwm : score += log ( min ( row ) / 0.25 + 0.01 ) self . min_score = score return self . min_score
Return the minimum PWM score .
944
def pwm_max_score ( self ) : if self . max_score is None : score = 0 for row in self . pwm : score += log ( max ( row ) / 0.25 + 0.01 ) self . max_score = score return self . max_score
Return the maximum PWM score .
945
def score_kmer ( self , kmer ) : if len ( kmer ) != len ( self . pwm ) : raise Exception ( "incorrect k-mer length" ) score = 0.0 d = { "A" : 0 , "C" : 1 , "G" : 2 , "T" : 3 } for nuc , row in zip ( kmer . upper ( ) , self . pwm ) : score += log ( row [ d [ nuc ] ] / 0.25 + 0.01 ) return score
Calculate the log - odds score for a specific k - mer .
946
def pfm_to_pwm ( self , pfm , pseudo = 0.001 ) : return [ [ ( x + pseudo ) / ( float ( np . sum ( row ) ) + pseudo * 4 ) for x in row ] for row in pfm ]
Convert PFM with counts to a PFM with fractions .
947
def ic_pos ( self , row1 , row2 = None ) : if row2 is None : row2 = [ 0.25 , 0.25 , 0.25 , 0.25 ] score = 0 for a , b in zip ( row1 , row2 ) : if a > 0 : score += a * log ( a / b ) / log ( 2 ) return score
Calculate the information content of one position .
948
def pcc_pos ( self , row1 , row2 ) : mean1 = np . mean ( row1 ) mean2 = np . mean ( row2 ) a = 0 x = 0 y = 0 for n1 , n2 in zip ( row1 , row2 ) : a += ( n1 - mean1 ) * ( n2 - mean2 ) x += ( n1 - mean1 ) ** 2 y += ( n2 - mean2 ) ** 2 if a == 0 : return 0 else : return a / sqrt ( x * y )
Calculate the Pearson correlation coefficient of one position compared to another position .
949
def rc ( self ) : m = Motif ( ) m . pfm = [ row [ : : - 1 ] for row in self . pfm [ : : - 1 ] ] m . pwm = [ row [ : : - 1 ] for row in self . pwm [ : : - 1 ] ] m . id = self . id + "_revcomp" return m
Return the reverse complemented motif .
950
def trim ( self , edge_ic_cutoff = 0.4 ) : pwm = self . pwm [ : ] while len ( pwm ) > 0 and self . ic_pos ( pwm [ 0 ] ) < edge_ic_cutoff : pwm = pwm [ 1 : ] self . pwm = self . pwm [ 1 : ] self . pfm = self . pfm [ 1 : ] while len ( pwm ) > 0 and self . ic_pos ( pwm [ - 1 ] ) < edge_ic_cutoff : pwm = pwm [ : - 1 ] self . pwm = self . pwm [ : - 1 ] self . pfm = self . pfm [ : - 1 ] self . consensus = None self . min_score = None self . max_score = None self . wiggled_pwm = None return self
Trim positions with an information content lower than the threshold .
951
def consensus_scan ( self , fa ) : regexp = "" . join ( [ "[" + "" . join ( self . iupac [ x . upper ( ) ] ) + "]" for x in self . to_consensusv2 ( ) ] ) p = re . compile ( regexp ) matches = { } for name , seq in fa . items ( ) : matches [ name ] = [ ] for match in p . finditer ( seq ) : middle = ( match . span ( ) [ 1 ] + match . span ( ) [ 0 ] ) / 2 matches [ name ] . append ( middle ) return matches
Scan FASTA with the motif as a consensus sequence .
952
def pwm_scan_to_gff ( self , fa , gfffile , cutoff = 0.9 , nreport = 50 , scan_rc = True , append = False ) : if append : out = open ( gfffile , "a" ) else : out = open ( gfffile , "w" ) c = self . pwm_min_score ( ) + ( self . pwm_max_score ( ) - self . pwm_min_score ( ) ) * cutoff pwm = self . pwm strandmap = { - 1 : "-" , "-1" : "-" , "-" : "-" , "1" : "+" , 1 : "+" , "+" : "+" } gff_line = ( "{}\tpfmscan\tmisc_feature\t{}\t{}\t{:.3f}\t{}\t.\t" "motif_name \"{}\" ; motif_instance \"{}\"\n" ) for name , seq in fa . items ( ) : result = pfmscan ( seq . upper ( ) , pwm , c , nreport , scan_rc ) for score , pos , strand in result : out . write ( gff_line . format ( name , pos , pos + len ( pwm ) , score , strandmap [ strand ] , self . id , seq [ pos : pos + len ( pwm ) ] ) ) out . close ( )
Scan sequences with this motif and save to a GFF file .
953
def average_motifs ( self , other , pos , orientation , include_bg = False ) : pfm1 = self . pfm [ : ] pfm2 = other . pfm [ : ] if orientation < 0 : pfm2 = [ row [ : : - 1 ] for row in pfm2 [ : : - 1 ] ] pfm1_count = float ( np . sum ( pfm1 [ 0 ] ) ) pfm2_count = float ( np . sum ( pfm2 [ 0 ] ) ) if include_bg : if len ( pfm1 ) > len ( pfm2 ) + pos : pfm2 += [ [ pfm2_count / 4.0 for x in range ( 4 ) ] for i in range ( - ( len ( pfm1 ) - len ( pfm2 ) - pos ) , 0 ) ] elif len ( pfm2 ) + pos > len ( pfm1 ) : pfm1 += [ [ pfm1_count / 4.0 for x in range ( 4 ) ] for i in range ( - ( len ( pfm2 ) - len ( pfm1 ) + pos ) , 0 ) ] if pos < 0 : pfm1 = [ [ pfm1_count / 4.0 for x in range ( 4 ) ] for i in range ( - pos ) ] + pfm1 elif pos > 0 : pfm2 = [ [ pfm2_count / 4.0 for x in range ( 4 ) ] for i in range ( pos ) ] + pfm2 else : if len ( pfm1 ) > len ( pfm2 ) + pos : pfm2 += [ [ pfm1 [ i ] [ x ] / pfm1_count * ( pfm2_count ) for x in range ( 4 ) ] for i in range ( - ( len ( pfm1 ) - len ( pfm2 ) - pos ) , 0 ) ] elif len ( pfm2 ) + pos > len ( pfm1 ) : pfm1 += [ [ pfm2 [ i ] [ x ] / pfm2_count * ( pfm1_count ) for x in range ( 4 ) ] for i in range ( - ( len ( pfm2 ) - len ( pfm1 ) + pos ) , 0 ) ] if pos < 0 : pfm1 = [ [ pfm2 [ i ] [ x ] / pfm2_count * ( pfm1_count ) for x in range ( 4 ) ] for i in range ( - pos ) ] + pfm1 elif pos > 0 : pfm2 = [ [ pfm1 [ i ] [ x ] / pfm1_count * ( pfm2_count ) for x in range ( 4 ) ] for i in range ( pos ) ] + pfm2 pfm = [ [ a + b for a , b in zip ( x , y ) ] for x , y in zip ( pfm1 , pfm2 ) ] m = Motif ( pfm ) m . id = m . to_consensus ( ) return m
Return the average of two motifs .
954
def _pwm_to_str ( self , precision = 4 ) : if not self . pwm : return "" fmt = "{{:.{:d}f}}" . format ( precision ) return "\n" . join ( [ "\t" . join ( [ fmt . format ( p ) for p in row ] ) for row in self . pwm ] )
Return string representation of pwm .
955
def to_pwm ( self , precision = 4 , extra_str = "" ) : motif_id = self . id if extra_str : motif_id += "_%s" % extra_str if not self . pwm : self . pwm = [ self . iupac_pwm [ char ] for char in self . consensus . upper ( ) ] return ">%s\n%s" % ( motif_id , self . _pwm_to_str ( precision ) )
Return pwm as string .
956
def to_img ( self , fname , fmt = "PNG" , add_left = 0 , seqlogo = None , height = 6 ) : if not seqlogo : seqlogo = self . seqlogo if not seqlogo : raise ValueError ( "seqlogo not specified or configured" ) VALID_FORMATS = [ "EPS" , "GIF" , "PDF" , "PNG" ] N = 1000 fmt = fmt . upper ( ) if not fmt in VALID_FORMATS : sys . stderr . write ( "Invalid motif format\n" ) return if fname [ - 4 : ] . upper ( ) == ( ".%s" % fmt ) : fname = fname [ : - 4 ] seqs = [ ] if add_left == 0 : seqs = [ "" for i in range ( N ) ] else : for nuc in [ "A" , "C" , "T" , "G" ] : seqs += [ nuc * add_left for i in range ( N // 4 ) ] for pos in range ( len ( self . pwm ) ) : vals = [ self . pwm [ pos ] [ 0 ] * N ] for i in range ( 1 , 4 ) : vals . append ( vals [ i - 1 ] + self . pwm [ pos ] [ i ] * N ) if vals [ 3 ] - N != 0 : vals [ 3 ] = N for i in range ( N ) : if i <= vals [ 0 ] : seqs [ i ] += "A" elif i <= vals [ 1 ] : seqs [ i ] += "C" elif i <= vals [ 2 ] : seqs [ i ] += "G" elif i <= vals [ 3 ] : seqs [ i ] += "T" f = NamedTemporaryFile ( mode = "w" , dir = mytmpdir ( ) ) for seq in seqs : f . write ( "%s\n" % seq ) f . flush ( ) makelogo = "{0} -f {1} -F {2} -c -a -h {3} -w {4} -o {5} -b -n -Y" cmd = makelogo . format ( seqlogo , f . name , fmt , height , len ( self ) + add_left , fname ) sp . call ( cmd , shell = True )
Create a sequence logo using seqlogo .
957
def randomize ( self ) : random_pfm = [ [ c for c in row ] for row in self . pfm ] random . shuffle ( random_pfm ) m = Motif ( pfm = random_pfm ) m . id = "random" return m
Create a new motif with shuffled positions .
958
def maelstrom ( args ) : infile = args . inputfile genome = args . genome outdir = args . outdir pwmfile = args . pwmfile methods = args . methods ncpus = args . ncpus if not os . path . exists ( infile ) : raise ValueError ( "file {} does not exist" . format ( infile ) ) if methods : methods = [ x . strip ( ) for x in methods . split ( "," ) ] run_maelstrom ( infile , genome , outdir , pwmfile , methods = methods , ncpus = ncpus )
Run the maelstrom method .
959
def zmq_recv_data ( socket , flags = 0 , copy = True , track = False ) : data = dict ( ) msg = socket . recv_multipart ( flags = flags , copy = copy , track = track ) headers = json . loads ( msg [ 0 ] . decode ( 'ascii' ) ) if len ( headers ) == 0 : raise StopIteration for header , payload in zip ( headers , msg [ 1 : ] ) : data [ header [ 'key' ] ] = np . frombuffer ( buffer ( payload ) , dtype = header [ 'dtype' ] ) data [ header [ 'key' ] ] . shape = header [ 'shape' ] if six . PY2 : continue data [ header [ 'key' ] ] . flags [ 'ALIGNED' ] = header [ 'aligned' ] return data
Receive data over a socket .
960
def hardmask ( self ) : p = re . compile ( "a|c|g|t|n" ) for seq_id in self . fasta_dict . keys ( ) : self . fasta_dict [ seq_id ] = p . sub ( "N" , self . fasta_dict [ seq_id ] ) return self
Mask all lowercase nucleotides with N s
961
def get_random ( self , n , l = None ) : random_f = Fasta ( ) if l : ids = self . ids [ : ] random . shuffle ( ids ) i = 0 while ( i < n ) and ( len ( ids ) > 0 ) : seq_id = ids . pop ( ) if ( len ( self [ seq_id ] ) >= l ) : start = random . randint ( 0 , len ( self [ seq_id ] ) - l ) random_f [ "random%s" % ( i + 1 ) ] = self [ seq_id ] [ start : start + l ] i += 1 if len ( random_f ) != n : sys . stderr . write ( "Not enough sequences of required length" ) return else : return random_f else : choice = random . sample ( self . ids , n ) for i in range ( n ) : random_f [ choice [ i ] ] = self [ choice [ i ] ] return random_f
Return n random sequences from this Fasta object
962
def writefasta ( self , fname ) : f = open ( fname , "w" ) fa_str = "\n" . join ( [ ">%s\n%s" % ( id , self . _format_seq ( seq ) ) for id , seq in self . items ( ) ] ) f . write ( fa_str ) f . close ( )
Write sequences to FASTA formatted file
963
def batch_length ( batch ) : n = None for value in six . itervalues ( batch ) : if n is None : n = len ( value ) elif len ( value ) != n : raise PescadorError ( 'Unequal field lengths' ) return n
Determine the number of samples in a batch .
964
def _activate ( self ) : self . distribution_ = 1. / self . n_streams * np . ones ( self . n_streams ) self . valid_streams_ = np . ones ( self . n_streams , dtype = bool ) self . streams_ = [ None ] * self . k self . stream_weights_ = np . zeros ( self . k ) self . stream_counts_ = np . zeros ( self . k , dtype = int ) self . stream_idxs_ = np . zeros ( self . k , dtype = int ) for idx in range ( self . k ) : if not ( self . distribution_ > 0 ) . any ( ) : break self . stream_idxs_ [ idx ] = self . rng . choice ( self . n_streams , p = self . distribution_ ) self . streams_ [ idx ] , self . stream_weights_ [ idx ] = ( self . _new_stream ( self . stream_idxs_ [ idx ] ) ) self . weight_norm_ = np . sum ( self . stream_weights_ )
Activates a number of streams
965
def iterate ( self , max_iter = None ) : if max_iter is None : max_iter = np . inf with self as active_mux : n = 0 while n < max_iter and active_mux . _streamers_available ( ) : idx = active_mux . _next_sample_index ( ) try : yield six . advance_iterator ( active_mux . streams_ [ idx ] ) n += 1 active_mux . stream_counts_ [ idx ] += 1 except StopIteration : active_mux . _on_stream_exhausted ( idx ) active_mux . _replace_stream ( idx )
Yields items from the mux and handles stream exhaustion and replacement .
966
def _next_sample_index ( self ) : return self . rng . choice ( self . n_active , p = ( self . stream_weights_ / self . weight_norm_ ) )
StochasticMux chooses its next sample stream randomly
967
def _activate ( self ) : self . streams_ = [ None ] * self . n_streams self . stream_weights_ = np . array ( self . weights , dtype = float ) self . stream_counts_ = np . zeros ( self . n_streams , dtype = int ) for idx in range ( self . n_streams ) : self . _new_stream ( idx ) self . weight_norm_ = np . sum ( self . stream_weights_ )
ShuffledMux s activate is similar to StochasticMux but there is no n_active since all the streams are always available .
968
def _next_sample_index ( self ) : return self . rng . choice ( self . n_streams , p = ( self . stream_weights_ / self . weight_norm_ ) )
ShuffledMux chooses its next sample stream randomly conditioned on the stream weights .
969
def _next_sample_index ( self ) : idx = self . active_index_ self . active_index_ += 1 if self . active_index_ >= len ( self . streams_ ) : self . active_index_ = 0 while self . streams_ [ idx ] is None : idx = self . active_index_ self . active_index_ += 1 if self . active_index_ >= len ( self . streams_ ) : self . active_index_ = 0 return idx
Rotates through each active sampler by incrementing the index
970
def _new_stream ( self , idx ) : stream_index = self . stream_idxs_ [ idx ] self . streams_ [ idx ] = self . streamers [ stream_index ] . iterate ( ) self . stream_counts_ [ idx ] = 0
Activate a new stream given the index into the stream pool .
971
def _new_stream ( self ) : try : next_stream = six . advance_iterator ( self . stream_generator_ ) except StopIteration : if self . mode == "cycle" : self . stream_generator_ = self . chain_streamer_ . iterate ( ) next_stream = six . advance_iterator ( self . stream_generator_ ) else : next_stream = None if next_stream is not None : streamer = next_stream . iterate ( ) self . streams_ [ 0 ] = streamer self . stream_counts_ [ 0 ] = 0
Grab the next stream from the input streamers and start it .
972
def npz_generator ( npz_path ) : npz_data = np . load ( npz_path ) X = npz_data [ 'X' ] y = npz_data [ 'Y' ] n = X . shape [ 0 ] while True : i = np . random . randint ( 0 , n ) yield { 'X' : X [ i ] , 'Y' : y [ i ] }
Generate data from an npz file .
973
def phyper ( k , good , bad , N ) : pvalues = [ phyper_single ( x , good , bad , N ) for x in range ( k + 1 , N + 1 ) ] return np . sum ( pvalues )
Current hypergeometric implementation in scipy is broken so here s the correct version
974
def calc_motif_enrichment ( sample , background , mtc = None , len_sample = None , len_back = None ) : INF = "Inf" if mtc not in [ None , "Bonferroni" , "Benjamini-Hochberg" , "None" ] : raise RuntimeError ( "Unknown correction: %s" % mtc ) sig = { } p_value = { } n_sample = { } n_back = { } if not ( len_sample ) : len_sample = sample . seqn ( ) if not ( len_back ) : len_back = background . seqn ( ) for motif in sample . motifs . keys ( ) : p = "NA" s = "NA" q = len ( sample . motifs [ motif ] ) m = 0 if ( background . motifs . get ( motif ) ) : m = len ( background . motifs [ motif ] ) n = len_back - m k = len_sample p = phyper ( q - 1 , m , n , k ) if p != 0 : s = - ( log ( p ) / log ( 10 ) ) else : s = INF else : s = INF p = 0.0 sig [ motif ] = s p_value [ motif ] = p n_sample [ motif ] = q n_back [ motif ] = m if mtc == "Bonferroni" : for motif in p_value . keys ( ) : if p_value [ motif ] != "NA" : p_value [ motif ] = p_value [ motif ] * len ( p_value . keys ( ) ) if p_value [ motif ] > 1 : p_value [ motif ] = 1 elif mtc == "Benjamini-Hochberg" : motifs = sorted ( p_value . keys ( ) , key = lambda x : - p_value [ x ] ) l = len ( p_value ) c = l for m in motifs : if p_value [ m ] != "NA" : p_value [ m ] = p_value [ m ] * l / c c -= 1 return ( sig , p_value , n_sample , n_back )
Calculate enrichment based on hypergeometric distribution
975
def parse_cutoff ( motifs , cutoff , default = 0.9 ) : cutoffs = { } if os . path . isfile ( str ( cutoff ) ) : for i , line in enumerate ( open ( cutoff ) ) : if line != "Motif\tScore\tCutoff\n" : try : motif , _ , c = line . strip ( ) . split ( "\t" ) c = float ( c ) cutoffs [ motif ] = c except Exception as e : sys . stderr . write ( "Error parsing cutoff file, line {0}: {1}\n" . format ( e , i + 1 ) ) sys . exit ( 1 ) else : for motif in motifs : cutoffs [ motif . id ] = float ( cutoff ) for motif in motifs : if not motif . id in cutoffs : sys . stderr . write ( "No cutoff found for {0}, using default {1}\n" . format ( motif . id , default ) ) cutoffs [ motif . id ] = default return cutoffs
Provide either a file with one cutoff per motif or a single cutoff returns a hash with motif id as key and cutoff as value
976
def determine_file_type ( fname ) : if not ( isinstance ( fname , str ) or isinstance ( fname , unicode ) ) : raise ValueError ( "{} is not a file name!" , fname ) if not os . path . isfile ( fname ) : raise ValueError ( "{} is not a file!" , fname ) ext = os . path . splitext ( fname ) [ 1 ] . lower ( ) if ext in [ "bed" ] : return "bed" elif ext in [ "fa" , "fasta" ] : return "fasta" elif ext in [ "narrowpeak" ] : return "narrowpeak" try : Fasta ( fname ) return "fasta" except : pass p = re . compile ( r'^(#|track|browser)' ) with open ( fname ) as f : for line in f . readlines ( ) : line = line . strip ( ) if not p . search ( line ) : break region_p = re . compile ( r'^(.+):(\d+)-(\d+)$' ) if region_p . search ( line ) : return "region" else : vals = line . split ( "\t" ) if len ( vals ) >= 3 : try : _ , _ = int ( vals [ 1 ] ) , int ( vals [ 2 ] ) except ValueError : return "unknown" if len ( vals ) == 10 : try : _ , _ = int ( vals [ 4 ] ) , int ( vals [ 9 ] ) return "narrowpeak" except ValueError : return "unknown" pass return "bed" return "unknown"
Detect file type .
977
def file_checksum ( fname ) : size = os . path . getsize ( fname ) with open ( fname , "r+" ) as f : checksum = hashlib . md5 ( mmap . mmap ( f . fileno ( ) , size ) ) . hexdigest ( ) return checksum
Return md5 checksum of file .
978
def download_annotation ( genomebuild , gene_file ) : pred_bin = "genePredToBed" pred = find_executable ( pred_bin ) if not pred : sys . stderr . write ( "{} not found in path!\n" . format ( pred_bin ) ) sys . exit ( 1 ) tmp = NamedTemporaryFile ( delete = False , suffix = ".gz" ) anno = [ ] f = urlopen ( UCSC_GENE_URL . format ( genomebuild ) ) p = re . compile ( r'\w+.Gene.txt.gz' ) for line in f . readlines ( ) : m = p . search ( line . decode ( ) ) if m : anno . append ( m . group ( 0 ) ) sys . stderr . write ( "Retrieving gene annotation for {}\n" . format ( genomebuild ) ) url = "" for a in ANNOS : if a in anno : url = UCSC_GENE_URL . format ( genomebuild ) + a break if url : sys . stderr . write ( "Using {}\n" . format ( url ) ) urlretrieve ( url , tmp . name ) with gzip . open ( tmp . name ) as f : cols = f . readline ( ) . decode ( errors = 'ignore' ) . split ( "\t" ) start_col = 1 for i , col in enumerate ( cols ) : if col == "+" or col == "-" : start_col = i - 1 break end_col = start_col + 10 cmd = "zcat {} | cut -f{}-{} | {} /dev/stdin {}" print ( cmd . format ( tmp . name , start_col , end_col , pred , gene_file ) ) sp . call ( cmd . format ( tmp . name , start_col , end_col , pred , gene_file ) , shell = True ) else : sys . stderr . write ( "No annotation found!" )
Download gene annotation from UCSC based on genomebuild .
979
def _make_index ( self , fasta , index ) : out = open ( index , "wb" ) f = open ( fasta ) line = f . readline ( ) offset = f . tell ( ) line = f . readline ( ) while line : out . write ( pack ( self . pack_char , offset ) ) offset = f . tell ( ) line = f . readline ( ) f . close ( ) out . close ( )
Index a single one - sequence fasta - file
980
def _read_index_file ( self ) : param_file = os . path . join ( self . index_dir , self . param_file ) with open ( param_file ) as f : for line in f . readlines ( ) : ( name , fasta_file , index_file , line_size , total_size ) = line . strip ( ) . split ( "\t" ) self . size [ name ] = int ( total_size ) self . fasta_file [ name ] = fasta_file self . index_file [ name ] = index_file self . line_size [ name ] = int ( line_size )
read the param_file index_dir should already be set
981
def _read_seq_from_fasta ( self , fasta , offset , nr_lines ) : fasta . seek ( offset ) lines = [ fasta . readline ( ) . strip ( ) for _ in range ( nr_lines ) ] return "" . join ( lines )
retrieve a number of lines from a fasta file - object starting at offset
982
def get_sequence ( self , chrom , start , end , strand = None ) : if not self . index_dir : print ( "Index dir is not defined!" ) sys . exit ( ) fasta_file = self . fasta_file [ chrom ] index_file = self . index_file [ chrom ] line_size = self . line_size [ chrom ] total_size = self . size [ chrom ] if start > total_size : raise ValueError ( "Invalid start {0}, greater than sequence length {1} of {2}!" . format ( start , total_size , chrom ) ) if start < 0 : raise ValueError ( "Invalid start, < 0!" ) if end > total_size : raise ValueError ( "Invalid end {0}, greater than sequence length {1} of {2}!" . format ( end , total_size , chrom ) ) index = open ( index_file , "rb" ) fasta = open ( fasta_file ) seq = self . _read ( index , fasta , start , end , line_size ) index . close ( ) fasta . close ( ) if strand and strand == "-" : seq = rc ( seq ) return seq
Retrieve a sequence
983
def get_size ( self , chrom = None ) : if len ( self . size ) == 0 : raise LookupError ( "no chromosomes in index, is the index correct?" ) if chrom : if chrom in self . size : return self . size [ chrom ] else : raise KeyError ( "chromosome {} not in index" . format ( chrom ) ) total = 0 for size in self . size . values ( ) : total += size return total
Return the sizes of all sequences in the index or the size of chrom if specified as an optional argument
984
def get_tool ( name ) : tool = name . lower ( ) if tool not in __tools__ : raise ValueError ( "Tool {0} not found!\n" . format ( name ) ) t = __tools__ [ tool ] ( ) if not t . is_installed ( ) : sys . stderr . write ( "Tool {0} not installed!\n" . format ( tool ) ) if not t . is_configured ( ) : sys . stderr . write ( "Tool {0} not configured!\n" . format ( tool ) ) return t
Returns an instance of a specific tool .
985
def locate_tool ( name , verbose = True ) : m = get_tool ( name ) tool_bin = which ( m . cmd ) if tool_bin : if verbose : print ( "Found {} in {}" . format ( m . name , tool_bin ) ) return tool_bin else : print ( "Couldn't find {}" . format ( m . name ) )
Returns the binary of a tool .
986
def bin ( self ) : if self . local_bin : return self . local_bin else : return self . config . bin ( self . name )
Get the command used to run the tool .
987
def run ( self , fastafile , params = None , tmp = None ) : if not self . is_configured ( ) : raise ValueError ( "%s is not configured" % self . name ) if not self . is_installed ( ) : raise ValueError ( "%s is not installed or not correctly configured" % self . name ) self . tmpdir = mkdtemp ( prefix = "{0}." . format ( self . name ) , dir = tmp ) fastafile = os . path . abspath ( fastafile ) try : return self . _run_program ( self . bin ( ) , fastafile , params ) except KeyboardInterrupt : return ( [ ] , "Killed" , "Killed" )
Run the tool and predict motifs from a FASTA file .
988
def _run_program ( self , bin , fastafile , params = None ) : params = self . _parse_params ( params ) outfile = os . path . join ( self . tmpdir , os . path . basename ( fastafile . replace ( ".fa" , ".pwm" ) ) ) stdout = "" stderr = "" cmd = "%s %s %s --localization --batch %s %s" % ( bin , self . tmpdir , fastafile , params [ "background" ] , params [ "strand" ] , ) p = Popen ( cmd , shell = True , stdout = PIPE , stderr = PIPE ) out , err = p . communicate ( ) stdout += out . decode ( ) stderr += err . decode ( ) motifs = [ ] if os . path . exists ( outfile ) : motifs = read_motifs ( outfile , fmt = "xxmotif" ) for m in motifs : m . id = "{0}_{1}" . format ( self . name , m . id ) else : stdout += "\nMotif file {0} not found!\n" . format ( outfile ) stderr += "\nMotif file {0} not found!\n" . format ( outfile ) return motifs , stdout , stderr
Run XXmotif and predict motifs from a FASTA file .
989
def _run_program ( self , bin , fastafile , params = None ) : params = self . _parse_params ( params ) outfile = NamedTemporaryFile ( mode = "w" , dir = self . tmpdir , prefix = "homer_w{}." . format ( params [ "width" ] ) ) . name cmd = "%s denovo -i %s -b %s -len %s -S %s %s -o %s -p 8" % ( bin , fastafile , params [ "background" ] , params [ "width" ] , params [ "number" ] , params [ "strand" ] , outfile ) stderr = "" stdout = "Running command:\n{}\n" . format ( cmd ) p = Popen ( cmd , shell = True , stdout = PIPE , stderr = PIPE , cwd = self . tmpdir ) out , err = p . communicate ( ) stdout += out . decode ( ) stderr += err . decode ( ) motifs = [ ] if os . path . exists ( outfile ) : motifs = read_motifs ( outfile , fmt = "pwm" ) for i , m in enumerate ( motifs ) : m . id = "{}_{}_{}" . format ( self . name , params [ "width" ] , i + 1 ) return motifs , stdout , stderr
Run Homer and predict motifs from a FASTA file .
990
def _run_program ( self , bin , fastafile , params = None ) : params = self . _parse_params ( params ) default_params = { "width" : 10 } if params is not None : default_params . update ( params ) fgfile , summitfile , outfile = self . _prepare_files ( fastafile ) current_path = os . getcwd ( ) os . chdir ( self . tmpdir ) cmd = "{} -i {} -w {} -dna 4 -iteration 50 -chain 20 -seqprop -0.1 -strand 2 -peaklocation {} -t_dof 3 -dep 2" . format ( bin , fgfile , params [ 'width' ] , summitfile ) p = Popen ( cmd , shell = True , stdout = PIPE , stderr = PIPE ) stdout , stderr = p . communicate ( ) os . chdir ( current_path ) motifs = [ ] if os . path . exists ( outfile ) : with open ( outfile ) as f : motifs = self . parse ( f ) for i , m in enumerate ( motifs ) : m . id = "HMS_w{}_{}" . format ( params [ 'width' ] , i + 1 ) return motifs , stdout , stderr
Run HMS and predict motifs from a FASTA file .
991
def _run_program ( self , bin , fastafile , params = None ) : params = self . _parse_params ( params ) fgfile = os . path . join ( self . tmpdir , "AMD.in.fa" ) outfile = fgfile + ".Matrix" shutil . copy ( fastafile , fgfile ) current_path = os . getcwd ( ) os . chdir ( self . tmpdir ) stdout = "" stderr = "" cmd = "%s -F %s -B %s" % ( bin , fgfile , params [ "background" ] , ) p = Popen ( cmd , shell = True , stdout = PIPE , stderr = PIPE ) out , err = p . communicate ( ) stdout += out . decode ( ) stderr += err . decode ( ) os . chdir ( current_path ) motifs = [ ] if os . path . exists ( outfile ) : f = open ( outfile ) motifs = self . parse ( f ) f . close ( ) return motifs , stdout , stderr
Run AMD and predict motifs from a FASTA file .
992
def _run_program ( self , bin , fastafile , params = None ) : params = self . _parse_params ( params ) tmp = NamedTemporaryFile ( mode = "w" , dir = self . tmpdir , delete = False ) shutil . copy ( fastafile , tmp . name ) fastafile = tmp . name current_path = os . getcwd ( ) os . chdir ( self . dir ( ) ) motifs = [ ] stdout = "" stderr = "" for wildcard in [ 0 , 1 , 2 ] : cmd = "%s -sample %s -background %s -directory %s -strand %s -wildcard %s" % ( bin , fastafile , params [ "background" ] , self . tmpdir , params [ "strand" ] , wildcard , ) p = Popen ( cmd , shell = True , stdout = PIPE , stderr = PIPE ) out , err = p . communicate ( ) stdout += out . decode ( ) stderr += err . decode ( ) os . chdir ( current_path ) pwmfiles = glob . glob ( "{}/tmp*/result/*pwm" . format ( self . tmpdir ) ) if len ( pwmfiles ) > 0 : out_file = pwmfiles [ 0 ] stdout += "\nOutfile: {}" . format ( out_file ) my_motifs = [ ] if os . path . exists ( out_file ) : my_motifs = read_motifs ( out_file , fmt = "pwm" ) for m in motifs : m . id = "{}_{}" . format ( self . name , m . id ) stdout += "\nTrawler: {} motifs" . format ( len ( motifs ) ) if os . path . exists ( tmp . name ) : os . unlink ( tmp . name ) for motif in my_motifs : motif . id = "{}_{}_{}" . format ( self . name , wildcard , motif . id ) motifs += my_motifs else : stderr += "\nNo outfile found" return motifs , stdout , stderr
Run Trawler and predict motifs from a FASTA file .
993
def _run_program ( self , bin , fastafile , params = None ) : params = self . _parse_params ( params ) organism = params [ "organism" ] weeder_organisms = { "hg18" : "HS" , "hg19" : "HS" , "hg38" : "HS" , "mm9" : "MM" , "mm10" : "MM" , "dm3" : "DM" , "dm5" : "DM" , "dm6" : "DM" , "yeast" : "SC" , "sacCer2" : "SC" , "sacCer3" : "SC" , "TAIR10" : "AT" , "TAIR11" : "AT" , } weeder_organism = weeder_organisms . get ( organism , "HS" ) tmp = NamedTemporaryFile ( dir = self . tmpdir ) name = tmp . name tmp . close ( ) shutil . copy ( fastafile , name ) fastafile = name cmd = "{} -f {} -O" . format ( self . cmd , fastafile , weeder_organism , ) if params [ "single" ] : cmd += " -ss" stdout , stderr = "" , "" p = Popen ( cmd , shell = True , stdout = PIPE , stderr = PIPE , cwd = self . tmpdir ) out , err = p . communicate ( ) stdout += out . decode ( ) stderr += err . decode ( ) motifs = [ ] if os . path . exists ( fastafile + ".matrix.w2" ) : f = open ( fastafile + ".matrix.w2" ) motifs = self . parse ( f ) f . close ( ) for m in motifs : m . id = "{}_{}" . format ( self . name , m . id . split ( "\t" ) [ 0 ] ) for ext in [ ".w2" , ".matrix.w2" ] : if os . path . exists ( fastafile + ext ) : os . unlink ( fastafile + ext ) return motifs , stdout , stderr
Run Weeder and predict motifs from a FASTA file .
994
def _run_program ( self , bin , fastafile , params = None ) : params = self . _parse_params ( params ) cmd = "%s -f %s -b %s -m %s -w %s -n %s -o %s -s %s" % ( bin , fastafile , params [ "background_model" ] , params [ "pwmfile" ] , params [ "width" ] , params [ "number" ] , params [ "outfile" ] , params [ "strand" ] , ) p = Popen ( cmd , shell = True , stdout = PIPE , stderr = PIPE ) stdout , stderr = p . communicate ( ) motifs = [ ] if os . path . exists ( params [ "outfile" ] ) : with open ( params [ "outfile" ] ) as f : motifs = self . parse_out ( f ) for motif in motifs : motif . id = "%s_%s" % ( self . name , motif . id ) return motifs , stdout , stderr
Run MotifSampler and predict motifs from a FASTA file .
995
def _run_program ( self , bin , fastafile , params = None ) : default_params = { "width" : 10 , "number" : 10 } if params is not None : default_params . update ( params ) new_file = os . path . join ( self . tmpdir , "mdmodule_in.fa" ) shutil . copy ( fastafile , new_file ) fastafile = new_file pwmfile = fastafile + ".out" width = default_params [ 'width' ] number = default_params [ 'number' ] current_path = os . getcwd ( ) os . chdir ( self . tmpdir ) cmd = "%s -i %s -a 1 -o %s -w %s -t 100 -r %s" % ( bin , fastafile , pwmfile , width , number ) p = Popen ( cmd , shell = True , stdout = PIPE , stderr = PIPE ) stdout , stderr = p . communicate ( ) stdout = "cmd: {}\n" . format ( cmd ) + stdout . decode ( ) motifs = [ ] if os . path . exists ( pwmfile ) : with open ( pwmfile ) as f : motifs = self . parse ( f ) os . chdir ( current_path ) for motif in motifs : motif . id = "%s_%s" % ( self . name , motif . id ) return motifs , stdout , stderr
Run MDmodule and predict motifs from a FASTA file .
996
def _run_program ( self , bin , fastafile , params = None ) : params = self . _parse_params ( params ) basename = "munk_in.fa" new_file = os . path . join ( self . tmpdir , basename ) out = open ( new_file , "w" ) f = Fasta ( fastafile ) for seq in f . seqs : header = len ( seq ) // 2 out . write ( ">%s\n" % header ) out . write ( "%s\n" % seq ) out . close ( ) fastafile = new_file outfile = fastafile + ".out" current_path = os . getcwd ( ) os . chdir ( self . dir ( ) ) motifs = [ ] ncpus = 4 stdout = "" stderr = "" for zoops_factor in [ "oops" , 0.0 , 0.5 , 1.0 ] : cmd = "{} {} {} y {} m:{} 100 10 1 {} 1>{}" . format ( bin , params . get ( "width" , 8 ) , params . get ( "width" , 20 ) , zoops_factor , fastafile , ncpus , outfile ) p = Popen ( cmd , shell = True , stdout = PIPE , stderr = PIPE ) std = p . communicate ( ) stdout = stdout + std [ 0 ] . decode ( ) stderr = stderr + std [ 1 ] . decode ( ) if "RuntimeException" in stderr : return [ ] , stdout , stderr if os . path . exists ( outfile ) : with open ( outfile ) as f : motifs += self . parse ( f ) os . chdir ( current_path ) return motifs , stdout , stderr
Run ChIPMunk and predict motifs from a FASTA file .
997
def _run_program ( self , bin , fastafile , params = None ) : default_params = { } if params is not None : default_params . update ( params ) width = params . get ( "width" , 8 ) basename = "posmo_in.fa" new_file = os . path . join ( self . tmpdir , basename ) shutil . copy ( fastafile , new_file ) fastafile = new_file motifs = [ ] current_path = os . getcwd ( ) os . chdir ( self . tmpdir ) for n_ones in range ( 4 , min ( width , 11 ) , 2 ) : x = "1" * n_ones outfile = "%s.%s.out" % ( fastafile , x ) cmd = "%s 5000 %s %s 1.6 2.5 %s 200" % ( bin , x , fastafile , width ) p = Popen ( cmd , shell = True , stdout = PIPE , stderr = PIPE ) stdout , stderr = p . communicate ( ) stdout = stdout . decode ( ) stderr = stderr . decode ( ) context_file = fastafile . replace ( basename , "context.%s.%s.txt" % ( basename , x ) ) cmd = "%s %s %s simi.txt 0.88 10 2 10" % ( bin . replace ( "posmo" , "clusterwd" ) , context_file , outfile ) p = Popen ( cmd , shell = True , stdout = PIPE , stderr = PIPE ) out , err = p . communicate ( ) stdout += out . decode ( ) stderr += err . decode ( ) if os . path . exists ( outfile ) : with open ( outfile ) as f : motifs += self . parse ( f , width , n_ones ) os . chdir ( current_path ) return motifs , stdout , stderr
Run Posmo and predict motifs from a FASTA file .
998
def _run_program ( self , bin , fastafile , params = None ) : fname = os . path . join ( self . config . get_motif_dir ( ) , "JASPAR2010_vertebrate.pwm" ) motifs = read_motifs ( fname , fmt = "pwm" ) for motif in motifs : motif . id = "JASPAR_%s" % motif . id return motifs , "" , ""
Get enriched JASPAR motifs in a FASTA file .
999
def _run_program ( self , bin , fastafile , params = None ) : default_params = { "width" : 10 , "single" : False , "number" : 10 } if params is not None : default_params . update ( params ) tmp = NamedTemporaryFile ( dir = self . tmpdir ) tmpname = tmp . name strand = "-revcomp" width = default_params [ "width" ] number = default_params [ "number" ] cmd = [ bin , fastafile , "-text" , "-dna" , "-nostatus" , "-mod" , "zoops" , "-nmotifs" , "%s" % number , "-w" , "%s" % width , "-maxsize" , "10000000" ] if not default_params [ "single" ] : cmd . append ( strand ) p = Popen ( cmd , bufsize = 1 , stderr = PIPE , stdout = PIPE ) stdout , stderr = p . communicate ( ) motifs = [ ] motifs = self . parse ( io . StringIO ( stdout . decode ( ) ) ) tmp . close ( ) return motifs , stdout , stderr
Run MEME and predict motifs from a FASTA file .