idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
0
def split_phylogeny ( p , level = "s" ) : level = level + "__" result = p . split ( level ) return result [ 0 ] + level + result [ 1 ] . split ( ";" ) [ 0 ]
Return either the full or truncated version of a QIIME - formatted taxonomy string .
1
def ensure_dir ( d ) : if not os . path . exists ( d ) : try : os . makedirs ( d ) except OSError as oe : if os . errno == errno . ENOENT : msg = twdd ( ) return msg . format ( d ) else : msg = twdd ( ) return msg . format ( d , oe . strerror )
Check to make sure the supplied directory path does not exist if so create it . The method catches OSError exceptions and returns a descriptive message instead of re - raising the error .
2
def file_handle ( fnh , mode = "rU" ) : handle = None if isinstance ( fnh , file ) : if fnh . closed : raise ValueError ( "Input file is closed." ) handle = fnh elif isinstance ( fnh , str ) : handle = open ( fnh , mode ) return handle
Takes either a file path or an open file handle checks validity and returns an open file handle or raises an appropriate Exception .
3
def gather_categories ( imap , header , categories = None ) : if categories is None : return { "default" : DataCategory ( set ( imap . keys ( ) ) , { } ) } cat_ids = [ header . index ( cat ) for cat in categories if cat in header and "=" not in cat ] table = OrderedDict ( ) conditions = defaultdict ( set ) for i , cat ...
Find the user specified categories in the map and create a dictionary to contain the relevant data for each type within the categories . Multiple categories will have their types combined such that each possible combination will have its own entry in the dictionary .
4
def parse_unifrac ( unifracFN ) : with open ( unifracFN , "rU" ) as uF : first = uF . next ( ) . split ( "\t" ) lines = [ line . strip ( ) for line in uF ] unifrac = { "pcd" : OrderedDict ( ) , "eigvals" : [ ] , "varexp" : [ ] } if first [ 0 ] == "pc vector number" : return parse_unifrac_v1_8 ( unifrac , lines ) elif f...
Parses the unifrac results file into a dictionary
5
def parse_unifrac_v1_8 ( unifrac , file_data ) : for line in file_data : if line == "" : break line = line . split ( "\t" ) unifrac [ "pcd" ] [ line [ 0 ] ] = [ float ( e ) for e in line [ 1 : ] ] unifrac [ "eigvals" ] = [ float ( entry ) for entry in file_data [ - 2 ] . split ( "\t" ) [ 1 : ] ] unifrac [ "varexp" ] = ...
Function to parse data from older version of unifrac file obtained from Qiime version 1 . 8 and earlier .
6
def parse_unifrac_v1_9 ( unifrac , file_data ) : unifrac [ "eigvals" ] = [ float ( entry ) for entry in file_data [ 0 ] . split ( "\t" ) ] unifrac [ "varexp" ] = [ float ( entry ) * 100 for entry in file_data [ 3 ] . split ( "\t" ) ] for line in file_data [ 8 : ] : if line == "" : break line = line . split ( "\t" ) uni...
Function to parse data from newer version of unifrac file obtained from Qiime version 1 . 9 and later .
7
def color_mapping ( sample_map , header , group_column , color_column = None ) : group_colors = OrderedDict ( ) group_gather = gather_categories ( sample_map , header , [ group_column ] ) if color_column is not None : color_gather = gather_categories ( sample_map , header , [ color_column ] ) for group in group_gather ...
Determine color - category mapping . If color_column was specified then map the category names to color values . Otherwise use the palettable colors to automatically generate a set of colors for the group values .
8
def rev_c ( read ) : rc = [ ] rc_nucs = { 'A' : 'T' , 'T' : 'A' , 'G' : 'C' , 'C' : 'G' , 'N' : 'N' } for base in read : rc . extend ( rc_nucs [ base . upper ( ) ] ) return rc [ : : - 1 ]
return reverse completment of read
9
def shuffle_genome ( genome , cat , fraction = float ( 100 ) , plot = True , alpha = 0.1 , beta = 100000 , min_length = 1000 , max_length = 200000 ) : header = '>randomized_%s' % ( genome . name ) sequence = list ( '' . join ( [ i [ 1 ] for i in parse_fasta ( genome ) ] ) ) length = len ( sequence ) shuffled = [ ] whil...
randomly shuffle genome
10
def _prune ( self , fit , p_max ) : def remove_from_model_desc ( x , model_desc ) : rhs_termlist = [ ] for t in model_desc . rhs_termlist : if not t . factors : rhs_termlist . append ( t ) elif not x == t . factors [ 0 ] . _varname : rhs_termlist . append ( t ) md = ModelDesc ( model_desc . lhs_termlist , rhs_termlist ...
If the fit contains statistically insignificant parameters remove them . Returns a pruned fit where all parameters have p - values of the t - statistic below p_max
11
def find_best_rsquared ( list_of_fits ) : res = sorted ( list_of_fits , key = lambda x : x . rsquared ) return res [ - 1 ]
Return the best fit based on rsquared
12
def _predict ( self , fit , df ) : df_res = df . copy ( ) if 'Intercept' in fit . model . exog_names : df_res [ 'Intercept' ] = 1.0 df_res [ 'predicted' ] = fit . predict ( df_res ) if not self . allow_negative_predictions : df_res . loc [ df_res [ 'predicted' ] < 0 , 'predicted' ] = 0 prstd , interval_l , interval_u =...
Return a df with predictions and confidence interval
13
def relative_abundance ( biomf , sampleIDs = None ) : if sampleIDs is None : sampleIDs = biomf . ids ( ) else : try : for sid in sampleIDs : assert sid in biomf . ids ( ) except AssertionError : raise ValueError ( "\nError while calculating relative abundances: The sampleIDs provided do" " not match the sampleIDs in bi...
Calculate the relative abundance of each OTUID in a Sample .
14
def mean_otu_pct_abundance ( ra , otuIDs ) : sids = ra . keys ( ) otumeans = defaultdict ( int ) for oid in otuIDs : otumeans [ oid ] = sum ( [ ra [ sid ] [ oid ] for sid in sids if oid in ra [ sid ] ] ) / len ( sids ) * 100 return otumeans
Calculate the mean OTU abundance percentage .
15
def MRA ( biomf , sampleIDs = None , transform = None ) : ra = relative_abundance ( biomf , sampleIDs ) if transform is not None : ra = { sample : { otuID : transform ( abd ) for otuID , abd in ra [ sample ] . items ( ) } for sample in ra . keys ( ) } otuIDs = biomf . ids ( axis = "observation" ) return mean_otu_pct_ab...
Calculate the mean relative abundance percentage .
16
def raw_abundance ( biomf , sampleIDs = None , sample_abd = True ) : results = defaultdict ( int ) if sampleIDs is None : sampleIDs = biomf . ids ( ) else : try : for sid in sampleIDs : assert sid in biomf . ids ( ) except AssertionError : raise ValueError ( "\nError while calculating raw total abundances: The sampleID...
Calculate the total number of sequences in each OTU or SampleID .
17
def transform_raw_abundance ( biomf , fn = math . log10 , sampleIDs = None , sample_abd = True ) : totals = raw_abundance ( biomf , sampleIDs , sample_abd ) return { sid : fn ( abd ) for sid , abd in totals . items ( ) }
Function to transform the total abundance calculation for each sample ID to another format based on user given transformation function .
18
def print_MannWhitneyU ( div_calc ) : try : x = div_calc . values ( ) [ 0 ] . values ( ) y = div_calc . values ( ) [ 1 ] . values ( ) except : return "Error setting up input arrays for Mann-Whitney U Test. Skipping " "significance testing." T , p = stats . mannwhitneyu ( x , y ) print "\nMann-Whitney U test statistic:"...
Compute the Mann - Whitney U test for unequal group sample sizes .
19
def print_KruskalWallisH ( div_calc ) : calc = defaultdict ( list ) try : for k1 , v1 in div_calc . iteritems ( ) : for k2 , v2 in v1 . iteritems ( ) : calc [ k1 ] . append ( v2 ) except : return "Error setting up input arrays for Kruskal-Wallis H-Test. Skipping " "significance testing." h , p = stats . kruskal ( * cal...
Compute the Kruskal - Wallis H - test for independent samples . A typical rule is that each group must have at least 5 measurements .
20
def handle_program_options ( ) : parser = argparse . ArgumentParser ( description = "Calculate the alpha diversity\ of a set of samples using one or more \ metrics and output a kernal density \ estimator-smoothed...
Parses the given options passed in at the command line .
21
def blastdb ( fasta , maxfile = 10000000 ) : db = fasta . rsplit ( '.' , 1 ) [ 0 ] type = check_type ( fasta ) if type == 'nucl' : type = [ 'nhr' , type ] else : type = [ 'phr' , type ] if os . path . exists ( '%s.%s' % ( db , type [ 0 ] ) ) is False and os . path . exists ( '%s.00.%s' % ( db , type [ 0 ] ) ) is False ...
make blast db
22
def usearchdb ( fasta , alignment = 'local' , usearch_loc = 'usearch' ) : if '.udb' in fasta : print ( '# ... database found: %s' % ( fasta ) , file = sys . stderr ) return fasta type = check_type ( fasta ) db = '%s.%s.udb' % ( fasta . rsplit ( '.' , 1 ) [ 0 ] , type ) if os . path . exists ( db ) is False : print ( '#...
make usearch db
23
def _pp ( dict_data ) : for key , val in dict_data . items ( ) : print ( '{0:<11}: {1}' . format ( key , val ) )
Pretty print .
24
def print_licences ( params , metadata ) : if hasattr ( params , 'licenses' ) : if params . licenses : _pp ( metadata . licenses_desc ( ) ) sys . exit ( 0 )
Print licenses .
25
def check_repository_existence ( params ) : repodir = os . path . join ( params . outdir , params . name ) if os . path . isdir ( repodir ) : raise Conflict ( 'Package repository "{0}" has already exists.' . format ( repodir ) )
Check repository existence .
26
def generate_package ( params ) : pkg_data = package . PackageData ( params ) pkg_tree = package . PackageTree ( pkg_data ) pkg_tree . generate ( ) pkg_tree . move ( ) VCS ( os . path . join ( pkg_tree . outdir , pkg_tree . name ) , pkg_tree . pkg_data )
Generate package repository .
27
def print_single ( line , rev ) : if rev is True : seq = rc ( [ '' , line [ 9 ] ] ) [ 1 ] qual = line [ 10 ] [ : : - 1 ] else : seq = line [ 9 ] qual = line [ 10 ] fq = [ '@%s' % line [ 0 ] , seq , '+%s' % line [ 0 ] , qual ] print ( '\n' . join ( fq ) , file = sys . stderr )
print single reads to stderr
28
def sam2fastq ( sam , singles = False , force = False ) : L , R = None , None for line in sam : if line . startswith ( '@' ) is True : continue line = line . strip ( ) . split ( ) bit = [ True if i == '1' else False for i in bin ( int ( line [ 1 ] ) ) . split ( 'b' ) [ 1 ] [ : : - 1 ] ] while len ( bit ) < 8 : bit . ap...
convert sam to fastq
29
def sort_sam ( sam , sort ) : tempdir = '%s/' % ( os . path . abspath ( sam ) . rsplit ( '/' , 1 ) [ 0 ] ) if sort is True : mapping = '%s.sorted.sam' % ( sam . rsplit ( '.' , 1 ) [ 0 ] ) if sam != '-' : if os . path . exists ( mapping ) is False : os . system ( "\ sort -k1 --buffer-size=%sG -T %s -o...
sort sam file
30
def sub_sam ( sam , percent , sort = True , sbuffer = False ) : mapping = sort_sam ( sam , sort ) pool = [ 1 for i in range ( 0 , percent ) ] + [ 0 for i in range ( 0 , 100 - percent ) ] c = cycle ( [ 1 , 2 ] ) for line in mapping : line = line . strip ( ) . split ( ) if line [ 0 ] . startswith ( '@' ) : yield line con...
randomly subset sam file
31
def fq2fa ( fq ) : c = cycle ( [ 1 , 2 , 3 , 4 ] ) for line in fq : n = next ( c ) if n == 1 : seq = [ '>%s' % ( line . strip ( ) . split ( '@' , 1 ) [ 1 ] ) ] if n == 2 : seq . append ( line . strip ( ) ) yield seq
convert fq to fa
32
def change_return_type ( f ) : @ wraps ( f ) def wrapper ( * args , ** kwargs ) : if kwargs . has_key ( 'return_type' ) : return_type = kwargs [ 'return_type' ] kwargs . pop ( 'return_type' ) return return_type ( f ( * args , ** kwargs ) ) elif len ( args ) > 0 : return_type = type ( args [ 0 ] ) return return_type ( f...
Converts the returned value of wrapped function to the type of the first arg or to the type specified by a kwarg key return_type s value .
33
def convert_args_to_sets ( f ) : @ wraps ( f ) def wrapper ( * args , ** kwargs ) : args = ( setify ( x ) for x in args ) return f ( * args , ** kwargs ) return wrapper
Converts all args to set type via self . setify function .
34
def _init_entri ( self , laman ) : sup = BeautifulSoup ( laman . text , 'html.parser' ) estr = '' for label in sup . find ( 'hr' ) . next_siblings : if label . name == 'hr' : self . entri . append ( Entri ( estr ) ) break if label . name == 'h2' : if estr : self . entri . append ( Entri ( estr ) ) estr = '' estr += str...
Membuat objek - objek entri dari laman yang diambil .
35
def _init_kata_dasar ( self , dasar ) : for tiap in dasar : kata = tiap . find ( 'a' ) dasar_no = kata . find ( 'sup' ) kata = ambil_teks_dalam_label ( kata ) self . kata_dasar . append ( kata + ' [{}]' . format ( dasar_no . text . strip ( ) ) if dasar_no else kata )
Memproses kata dasar yang ada dalam nama entri .
36
def serialisasi ( self ) : return { "nama" : self . nama , "nomor" : self . nomor , "kata_dasar" : self . kata_dasar , "pelafalan" : self . pelafalan , "bentuk_tidak_baku" : self . bentuk_tidak_baku , "varian" : self . varian , "makna" : [ makna . serialisasi ( ) for makna in self . makna ] }
Mengembalikan hasil serialisasi objek Entri ini .
37
def _makna ( self ) : if len ( self . makna ) > 1 : return '\n' . join ( str ( i ) + ". " + str ( makna ) for i , makna in enumerate ( self . makna , 1 ) ) return str ( self . makna [ 0 ] )
Mengembalikan representasi string untuk semua makna entri ini .
38
def _nama ( self ) : hasil = self . nama if self . nomor : hasil += " [{}]" . format ( self . nomor ) if self . kata_dasar : hasil = " » ". j oin( s elf. k ata_dasar) » " + h sil return hasil
Mengembalikan representasi string untuk nama entri ini .
39
def _varian ( self , varian ) : if varian == self . bentuk_tidak_baku : nama = "Bentuk tidak baku" elif varian == self . varian : nama = "Varian" else : return '' return nama + ': ' + ', ' . join ( varian )
Mengembalikan representasi string untuk varian entri ini . Dapat digunakan untuk Varian maupun Bentuk tidak baku .
40
def _init_kelas ( self , makna_label ) : kelas = makna_label . find ( color = 'red' ) lain = makna_label . find ( color = 'darkgreen' ) info = makna_label . find ( color = 'green' ) if kelas : kelas = kelas . find_all ( 'span' ) if lain : self . kelas = { lain . text . strip ( ) : lain [ 'title' ] . strip ( ) } self . ...
Memproses kelas kata yang ada dalam makna .
41
def _init_contoh ( self , makna_label ) : indeks = makna_label . text . find ( ': ' ) if indeks != - 1 : contoh = makna_label . text [ indeks + 2 : ] . strip ( ) self . contoh = contoh . split ( '; ' ) else : self . contoh = [ ]
Memproses contoh yang ada dalam makna .
42
def serialisasi ( self ) : return { "kelas" : self . kelas , "submakna" : self . submakna , "info" : self . info , "contoh" : self . contoh }
Mengembalikan hasil serialisasi objek Makna ini .
43
def build_sphinx ( pkg_data , projectdir ) : try : version , _minor_version = pkg_data . version . rsplit ( '.' , 1 ) except ValueError : version = pkg_data . version args = ' ' . join ( ( 'sphinx-quickstart' , '--sep' , '-q' , '-p "{name}"' , '-a "{author}"' , '-v "{version}"' , '-r "{release}"' , '-l en' , '--suffix=...
Build sphinx documentation .
44
def bowtiedb ( fa , keepDB ) : btdir = '%s/bt2' % ( os . getcwd ( ) ) if not os . path . exists ( btdir ) : os . mkdir ( btdir ) btdb = '%s/%s' % ( btdir , fa . rsplit ( '/' , 1 ) [ - 1 ] ) if keepDB is True : if os . path . exists ( '%s.1.bt2' % ( btdb ) ) : return btdb p = subprocess . Popen ( 'bowtie2-build -q %s %s...
make bowtie db
45
def bowtie ( sam , btd , f , r , u , opt , no_shrink , threads ) : bt2 = 'bowtie2 -x %s -p %s ' % ( btd , threads ) if f is not False : bt2 += '-1 %s -2 %s ' % ( f , r ) if u is not False : bt2 += '-U %s ' % ( u ) bt2 += opt if no_shrink is False : if f is False : bt2 += ' | shrinksam -u -k %s-shrunk.sam ' % ( sam ) el...
generate bowtie2 command
46
def crossmap ( fas , reads , options , no_shrink , keepDB , threads , cluster , nodes ) : if cluster is True : threads = '48' btc = [ ] for fa in fas : btd = bowtiedb ( fa , keepDB ) F , R , U = reads if F is not False : if U is False : u = False for i , f in enumerate ( F ) : r = R [ i ] if U is not False : u = U [ i ...
map all read sets against all fasta files
47
def get_conn ( self , * args , ** kwargs ) : connections = self . __connections_for ( 'get_conn' , args = args , kwargs = kwargs ) if len ( connections ) is 1 : return connections [ 0 ] else : return connections
Returns a connection object from the router given args .
48
def __get_nondirect_init ( self , init ) : crc = init for i in range ( self . Width ) : bit = crc & 0x01 if bit : crc ^= self . Poly crc >>= 1 if bit : crc |= self . MSB_Mask return crc & self . Mask
return the non - direct init if the direct algorithm has been selected .
49
def reflect ( self , data , width ) : x = data & 0x01 for i in range ( width - 1 ) : data >>= 1 x = ( x << 1 ) | ( data & 0x01 ) return x
reflect a data word i . e . reverts the bit order .
50
def bit_by_bit ( self , in_data ) : if isinstance ( in_data , str ) : in_data = [ ord ( c ) for c in in_data ] register = self . NonDirectInit for octet in in_data : if self . ReflectIn : octet = self . reflect ( octet , 8 ) for i in range ( 8 ) : topbit = register & self . MSB_Mask register = ( ( register << 1 ) & sel...
Classic simple and slow CRC implementation . This function iterates bit by bit over the augmented input message and returns the calculated CRC value at the end .
51
def gen_table ( self ) : table_length = 1 << self . TableIdxWidth tbl = [ 0 ] * table_length for i in range ( table_length ) : register = i if self . ReflectIn : register = self . reflect ( register , self . TableIdxWidth ) register = register << ( self . Width - self . TableIdxWidth + self . CrcShift ) for j in range ...
This function generates the CRC table used for the table_driven CRC algorithm . The Python version cannot handle tables of an index width other than 8 . See the generated C code for tables with different sizes instead .
52
def table_driven ( self , in_data ) : if isinstance ( in_data , str ) : in_data = [ ord ( c ) for c in in_data ] tbl = self . gen_table ( ) register = self . DirectInit << self . CrcShift if not self . ReflectIn : for octet in in_data : tblidx = ( ( register >> ( self . Width - self . TableIdxWidth + self . CrcShift ) ...
The Standard table_driven CRC algorithm .
53
def parse_masked ( seq , min_len ) : nm , masked = [ ] , [ [ ] ] prev = None for base in seq [ 1 ] : if base . isupper ( ) : nm . append ( base ) if masked != [ [ ] ] and len ( masked [ - 1 ] ) < min_len : nm . extend ( masked [ - 1 ] ) del masked [ - 1 ] prev = False elif base . islower ( ) : if prev is False : masked...
parse masked sequence into non - masked and masked regions
54
def strip_masked ( fasta , min_len , print_masked ) : for seq in parse_fasta ( fasta ) : nm , masked = parse_masked ( seq , min_len ) nm = [ '%s removed_masked >=%s' % ( seq [ 0 ] , min_len ) , '' . join ( nm ) ] yield [ 0 , nm ] if print_masked is True : for i , m in enumerate ( [ i for i in masked if i != [ ] ] , 1 )...
remove masked regions from fasta file as long as they are longer than min_len
55
def get_relative_abundance ( biomfile ) : biomf = biom . load_table ( biomfile ) norm_biomf = biomf . norm ( inplace = False ) rel_abd = { } for sid in norm_biomf . ids ( ) : rel_abd [ sid ] = { } for otuid in norm_biomf . ids ( "observation" ) : otuname = oc . otu_name ( norm_biomf . metadata ( otuid , axis = "observa...
Return arcsine transformed relative abundance from a BIOM format file .
56
def find_otu ( otuid , tree ) : for m in re . finditer ( otuid , tree ) : before , after = tree [ m . start ( ) - 1 ] , tree [ m . start ( ) + len ( otuid ) ] if before in [ "(" , "," , ")" ] and after in [ ":" , ";" ] : return m . start ( ) return None
Find an OTU ID in a Newick - format tree . Return the starting position of the ID or None if not found .
57
def newick_replace_otuids ( tree , biomf ) : for val , id_ , md in biomf . iter ( axis = "observation" ) : otu_loc = find_otu ( id_ , tree ) if otu_loc is not None : tree = tree [ : otu_loc ] + oc . otu_name ( md [ "taxonomy" ] ) + tree [ otu_loc + len ( id_ ) : ] return tree
Replace the OTU ids in the Newick phylogenetic tree format with truncated OTU names
58
def genome_info ( genome , info ) : try : scg = info [ '#SCGs' ] dups = info [ '#SCG duplicates' ] length = info [ 'genome size (bp)' ] return [ scg - dups , length , genome ] except : return [ False , False , info [ 'genome size (bp)' ] , genome ]
return genome info for choosing representative
59
def print_clusters ( fastas , info , ANI ) : header = [ '#cluster' , 'num. genomes' , 'rep.' , 'genome' , '#SCGs' , '#SCG duplicates' , 'genome size (bp)' , 'fragments' , 'list' ] yield header in_cluster = [ ] for cluster_num , cluster in enumerate ( connected_components ( ANI ) ) : cluster = sorted ( [ genome_info ( g...
choose represenative genome and print cluster information
60
def parse_ggKbase_tables ( tables , id_type ) : g2info = { } for table in tables : for line in open ( table ) : line = line . strip ( ) . split ( '\t' ) if line [ 0 ] . startswith ( 'name' ) : header = line header [ 4 ] = 'genome size (bp)' header [ 12 ] = '#SCGs' header [ 13 ] = '#SCG duplicates' continue name , code ...
convert ggKbase genome info tables to dictionary
61
def parse_checkM_tables ( tables ) : g2info = { } for table in tables : for line in open ( table ) : line = line . strip ( ) . split ( '\t' ) if line [ 0 ] . startswith ( 'Bin Id' ) : header = line header [ 8 ] = 'genome size (bp)' header [ 5 ] = '#SCGs' header [ 6 ] = '#SCG duplicates' continue ID , info = line [ 0 ] ...
convert checkM genome info tables to dictionary
62
def genome_lengths ( fastas , info ) : if info is False : info = { } for genome in fastas : name = genome . rsplit ( '.' , 1 ) [ 0 ] . rsplit ( '/' , 1 ) [ - 1 ] . rsplit ( '.contigs' ) [ 0 ] if name in info : continue length = 0 fragments = 0 for seq in parse_fasta ( genome ) : length += len ( seq [ 1 ] ) fragments +=...
get genome lengths
63
def get_dbs ( self , attr , args , kwargs , ** fkwargs ) : if not self . _ready : if not self . setup_router ( args = args , kwargs = kwargs , ** fkwargs ) : raise self . UnableToSetupRouter ( ) retval = self . _pre_routing ( attr = attr , args = args , kwargs = kwargs , ** fkwargs ) if retval is not None : args , kwar...
Returns a list of db keys to route the given call to .
64
def setup_router ( self , args , kwargs , ** fkwargs ) : self . _ready = self . _setup_router ( args = args , kwargs = kwargs , ** fkwargs ) return self . _ready
Call method to perform any setup
65
def _route ( self , attr , args , kwargs , ** fkwargs ) : return self . cluster . hosts . keys ( )
Perform routing and return db_nums
66
def check_down_connections ( self ) : now = time . time ( ) for db_num , marked_down_at in self . _down_connections . items ( ) : if marked_down_at + self . retry_timeout <= now : self . mark_connection_up ( db_num )
Iterates through all connections which were previously listed as unavailable and marks any that have expired their retry_timeout as being up .
67
def flush_down_connections ( self ) : self . _get_db_attempts = 0 for db_num in self . _down_connections . keys ( ) : self . mark_connection_up ( db_num )
Marks all connections which were previously listed as unavailable as being up .
68
def standby ( df , resolution = '24h' , time_window = None ) : if df . empty : raise EmptyDataFrame ( ) df = pd . DataFrame ( df ) def parse_time ( t ) : if isinstance ( t , numbers . Number ) : return pd . Timestamp . utcfromtimestamp ( t ) . time ( ) else : return pd . Timestamp ( t ) . time ( ) if time_window is not...
Compute standby power
69
def share_of_standby ( df , resolution = '24h' , time_window = None ) : p_sb = standby ( df , resolution , time_window ) df = df . resample ( resolution ) . mean ( ) p_tot = df . sum ( ) p_standby = p_sb . sum ( ) share_standby = p_standby / p_tot res = share_standby . iloc [ 0 ] return res
Compute the share of the standby power in the total consumption .
70
def count_peaks ( ts ) : on_toggles = ts . diff ( ) > 3000 shifted = np . logical_not ( on_toggles . shift ( 1 ) ) result = on_toggles & shifted count = result . sum ( ) return count
Toggle counter for gas boilers
71
def load_factor ( ts , resolution = None , norm = None ) : if norm is None : norm = ts . max ( ) if resolution is not None : ts = ts . resample ( rule = resolution ) . mean ( ) lf = ts / norm return lf
Calculate the ratio of input vs . norm over a given interval .
72
def top_hits ( hits , num , column , reverse ) : hits . sort ( key = itemgetter ( column ) , reverse = reverse ) for hit in hits [ 0 : num ] : yield hit
get top hits after sorting by column number
73
def numBlast_sort ( blast , numHits , evalueT , bitT ) : header = [ '#query' , 'target' , 'pident' , 'alen' , 'mismatch' , 'gapopen' , 'qstart' , 'qend' , 'tstart' , 'tend' , 'evalue' , 'bitscore' ] yield header hmm = { h : [ ] for h in header } for line in blast : if line . startswith ( '#' ) : continue line = line . ...
parse b6 output with sorting
74
def numBlast ( blast , numHits , evalueT = False , bitT = False , sort = False ) : if sort is True : for hit in numBlast_sort ( blast , numHits , evalueT , bitT ) : yield hit return header = [ '#query' , 'target' , 'pident' , 'alen' , 'mismatch' , 'gapopen' , 'qstart' , 'qend' , 'tstart' , 'tend' , 'evalue' , 'bitscore...
parse b6 output
75
def numDomtblout ( domtblout , numHits , evalueT , bitT , sort ) : if sort is True : for hit in numDomtblout_sort ( domtblout , numHits , evalueT , bitT ) : yield hit return header = [ '#target name' , 'target accession' , 'tlen' , 'query name' , 'query accession' , 'qlen' , 'full E-value' , 'full score' , 'full bias' ...
parse hmm domain table output this version is faster but does not work unless the table is sorted
76
def stock2fa ( stock ) : seqs = { } for line in stock : if line . startswith ( '#' ) is False and line . startswith ( ' ' ) is False and len ( line ) > 3 : id , seq = line . strip ( ) . split ( ) id = id . rsplit ( '/' , 1 ) [ 0 ] id = re . split ( '[0-9]\|' , id , 1 ) [ - 1 ] if id not in seqs : seqs [ id ] = [ ] seqs...
convert stockholm to fasta
77
def week_schedule ( index , on_time = None , off_time = None , off_days = None ) : if on_time is None : on_time = '9:00' if off_time is None : off_time = '17:00' if off_days is None : off_days = [ 'Sunday' , 'Monday' ] if not isinstance ( on_time , datetime . time ) : on_time = pd . to_datetime ( on_time , format = '%H...
Return boolean time series following given week schedule .
78
def carpet ( timeseries , ** kwargs ) : cmap = kwargs . pop ( 'cmap' , cm . coolwarm ) norm = kwargs . pop ( 'norm' , LogNorm ( ) ) interpolation = kwargs . pop ( 'interpolation' , 'nearest' ) cblabel = kwargs . pop ( 'zlabel' , timeseries . name if timeseries . name else '' ) title = kwargs . pop ( 'title' , 'carpet p...
Draw a carpet plot of a pandas timeseries .
79
def calc_pident_ignore_gaps ( a , b ) : m = 0 mm = 0 for A , B in zip ( list ( a ) , list ( b ) ) : if A == '-' or A == '.' or B == '-' or B == '.' : continue if A == B : m += 1 else : mm += 1 try : return float ( float ( m ) / float ( ( m + mm ) ) ) * 100 except : return 0
calculate percent identity
80
def remove_gaps ( A , B ) : a_seq , b_seq = [ ] , [ ] for a , b in zip ( list ( A ) , list ( B ) ) : if a == '-' or a == '.' or b == '-' or b == '.' : continue a_seq . append ( a ) b_seq . append ( b ) return '' . join ( a_seq ) , '' . join ( b_seq )
skip column if either is a gap
81
def compare_seqs ( seqs ) : A , B , ignore_gaps = seqs a , b = A [ 1 ] , B [ 1 ] if len ( a ) != len ( b ) : print ( '# reads are not the same length' , file = sys . stderr ) exit ( ) if ignore_gaps is True : pident = calc_pident_ignore_gaps ( a , b ) else : pident = calc_pident ( a , b ) return A [ 0 ] , B [ 0 ] , pid...
compare pairs of sequences
82
def compare_seqs_leven ( seqs ) : A , B , ignore_gaps = seqs a , b = remove_gaps ( A [ 1 ] , B [ 1 ] ) if len ( a ) != len ( b ) : print ( '# reads are not the same length' , file = sys . stderr ) exit ( ) pident = lr ( a , b ) * 100 return A [ 0 ] , B [ 0 ] , pident
calculate Levenshtein ratio of sequences
83
def pairwise_compare ( afa , leven , threads , print_list , ignore_gaps ) : seqs = { seq [ 0 ] : seq for seq in nr_fasta ( [ afa ] , append_index = True ) } num_seqs = len ( seqs ) pairs = ( ( i [ 0 ] , i [ 1 ] , ignore_gaps ) for i in itertools . combinations ( list ( seqs . values ( ) ) , 2 ) ) pool = multithread ( t...
make pairwise sequence comparisons between aligned sequences
84
def print_pairwise ( pw , median = False ) : names = sorted ( set ( [ i for i in pw ] ) ) if len ( names ) != 0 : if '>' in names [ 0 ] : yield [ '#' ] + [ i . split ( '>' ) [ 1 ] for i in names if '>' in i ] else : yield [ '#' ] + names for a in names : if '>' in a : yield [ a . split ( '>' ) [ 1 ] ] + [ pw [ a ] [ b ...
print matrix of pidents to stdout
85
def print_comps ( comps ) : if comps == [ ] : print ( 'n/a' ) else : print ( '# min: %s, max: %s, mean: %s' % ( min ( comps ) , max ( comps ) , np . mean ( comps ) ) )
print stats for comparisons
86
def compare_clades ( pw ) : names = sorted ( set ( [ i for i in pw ] ) ) for i in range ( 0 , 4 ) : wi , bt = { } , { } for a in names : for b in pw [ a ] : if ';' not in a or ';' not in b : continue pident = pw [ a ] [ b ] cA , cB = a . split ( ';' ) [ i ] , b . split ( ';' ) [ i ] if i == 0 and '_' in cA and '_' in c...
print min . pident within each clade and then matrix of between - clade max .
87
def matrix2dictionary ( matrix ) : pw = { } for line in matrix : line = line . strip ( ) . split ( '\t' ) if line [ 0 ] . startswith ( '#' ) : names = line [ 1 : ] continue a = line [ 0 ] for i , pident in enumerate ( line [ 1 : ] ) : b = names [ i ] if a not in pw : pw [ a ] = { } if b not in pw : pw [ b ] = { } if pi...
convert matrix to dictionary of comparisons
88
def setoption ( parser , metadata = None ) : parser . add_argument ( '-v' , action = 'version' , version = __version__ ) subparsers = parser . add_subparsers ( help = 'sub commands help' ) create_cmd = subparsers . add_parser ( 'create' ) create_cmd . add_argument ( 'name' , help = 'Specify Python package name.' ) crea...
Set argument parser option .
89
def parse_options ( metadata ) : parser = argparse . ArgumentParser ( description = '%(prog)s usage:' , prog = __prog__ ) setoption ( parser , metadata = metadata ) return parser
Parse argument options .
90
def main ( ) : try : pkg_version = Update ( ) if pkg_version . updatable ( ) : pkg_version . show_message ( ) metadata = control . retreive_metadata ( ) parser = parse_options ( metadata ) argvs = sys . argv if len ( argvs ) <= 1 : parser . print_help ( ) sys . exit ( 1 ) args = parser . parse_args ( ) control . print_...
Execute main processes .
91
def _check_or_set_default_params ( self ) : if not hasattr ( self , 'date' ) : self . _set_param ( 'date' , datetime . utcnow ( ) . strftime ( '%Y-%m-%d' ) ) if not hasattr ( self , 'version' ) : self . _set_param ( 'version' , self . default_version ) if not hasattr ( self , 'description' ) or self . description is No...
Check key and set default vaule when it does not exists .
92
def move ( self ) : if not os . path . isdir ( self . outdir ) : os . makedirs ( self . outdir ) shutil . move ( self . tmpdir , os . path . join ( self . outdir , self . name ) )
Move directory from working directory to output directory .
93
def vcs_init ( self ) : VCS ( os . path . join ( self . outdir , self . name ) , self . pkg_data )
Initialize VCS repository .
94
def find_steam_location ( ) : if registry is None : return None key = registry . CreateKey ( registry . HKEY_CURRENT_USER , "Software\Valve\Steam" ) return registry . QueryValueEx ( key , "SteamPath" ) [ 0 ]
Finds the location of the current Steam installation on Windows machines . Returns None for any non - Windows machines or for Windows machines where Steam is not installed .
95
def plot_PCoA ( cat_data , otu_name , unifrac , names , colors , xr , yr , outDir , save_as , plot_style ) : fig = plt . figure ( figsize = ( 14 , 8 ) ) ax = fig . add_subplot ( 111 ) for i , cat in enumerate ( cat_data ) : plt . scatter ( cat_data [ cat ] [ "pc1" ] , cat_data [ cat ] [ "pc2" ] , cat_data [ cat ] [ "si...
Plot PCoA principal coordinates scaled by the relative abundances of otu_name .
96
def split_by_category ( biom_cols , mapping , category_id ) : columns = defaultdict ( list ) for i , col in enumerate ( biom_cols ) : columns [ mapping [ col [ 'id' ] ] [ category_id ] ] . append ( ( i , col ) ) return columns
Split up the column data in a biom table by mapping category value .
97
def print_line ( l ) : print_lines = [ '# STOCKHOLM' , '#=GF' , '#=GS' , ' ' ] if len ( l . split ( ) ) == 0 : return True for start in print_lines : if l . startswith ( start ) : return True return False
print line if starts with ...
98
def stock2one ( stock ) : lines = { } for line in stock : line = line . strip ( ) if print_line ( line ) is True : yield line continue if line . startswith ( '//' ) : continue ID , seq = line . rsplit ( ' ' , 1 ) if ID not in lines : lines [ ID ] = '' else : seq = seq . strip ( ) lines [ ID ] += seq for ID , line in li...
convert stockholm to single line format
99
def math_func ( f ) : @ wraps ( f ) def wrapper ( * args , ** kwargs ) : if len ( args ) > 0 : return_type = type ( args [ 0 ] ) if kwargs . has_key ( 'return_type' ) : return_type = kwargs [ 'return_type' ] kwargs . pop ( 'return_type' ) return return_type ( f ( * args , ** kwargs ) ) args = list ( ( setify ( x ) for ...
Statics the methods . wut .