idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
100
def dump_stats ( myStats ) : print ( "\n----%s PYTHON PING Statistics----" % ( myStats . thisIP ) ) if myStats . pktsSent > 0 : myStats . fracLoss = ( myStats . pktsSent - myStats . pktsRcvd ) / myStats . pktsSent print ( ( "%d packets transmitted, %d packets received, " "%0.1f%% packet loss" ) % ( myStats . pktsSent ,...
Show stats when pings are done
101
def updatable ( self ) : if self . latest_version > self . current_version : updatable_version = self . latest_version else : updatable_version = False return updatable_version
bootstrap - py package updatable? .
102
def show_message ( self ) : print ( 'current version: {current_version}\n' 'latest version : {latest_version}' . format ( current_version = self . current_version , latest_version = self . latest_version ) )
Show message updatable .
103
def condense_otus ( otuF , nuniqueF ) : uniqueOTUs = set ( ) nuOTUs = { } for line in nuniqueF : line = line . split ( ) uOTU = line [ 0 ] for nuOTU in line [ 1 : ] : nuOTUs [ nuOTU ] = uOTU uniqueOTUs . add ( uOTU ) otuFilter = defaultdict ( list ) for line in otuF : line = line . split ( ) otuID , seqIDs = line [ 0 ]...
Traverse the input otu - sequence file collect the non - unique OTU IDs and file the sequences associated with then under the unique OTU ID as defined by the input matrix .
104
def rna_bases ( rna_cov , scaffold , bases , line ) : start = int ( line [ 3 ] ) stop = start + bases - 1 if scaffold not in rna_cov : return rna_cov for pos in rna_cov [ scaffold ] [ 2 ] : ol = get_overlap ( [ start , stop ] , pos ) rna_cov [ scaffold ] [ 0 ] += ol return rna_cov
determine if read overlaps with rna if so count bases
105
def parse_s2bins ( s2bins ) : s2b = { } b2s = { } for line in s2bins : line = line . strip ( ) . split ( ) s , b = line [ 0 ] , line [ 1 ] if 'UNK' in b : continue if len ( line ) > 2 : g = ' ' . join ( line [ 2 : ] ) else : g = 'n/a' b = '%s\t%s' % ( b , g ) s2b [ s ] = b if b not in b2s : b2s [ b ] = [ ] b2s [ b ] . ...
parse ggKbase scaffold - to - bin mapping - scaffolds - to - bins and bins - to - scaffolds
106
def filter_missing_rna ( s2bins , bins2s , rna_cov ) : for bin , scaffolds in list ( bins2s . items ( ) ) : c = 0 for s in scaffolds : if s in rna_cov : c += 1 if c == 0 : del bins2s [ bin ] for scaffold , bin in list ( s2bins . items ( ) ) : if bin not in bins2s : del s2bins [ scaffold ] return s2bins , bins2s
remove any bins that don t have 16S
107
def calc_bin_cov ( scaffolds , cov ) : bases = sum ( [ cov [ i ] [ 0 ] for i in scaffolds if i in cov ] ) length = sum ( [ cov [ i ] [ 1 ] for i in scaffolds if i in cov ] ) if length == 0 : return 0 return float ( float ( bases ) / float ( length ) )
calculate bin coverage
108
def clean ( self ) : super ( TranslationFormSet , self ) . clean ( ) if settings . HIDE_LANGUAGE : return if len ( self . forms ) > 0 : if settings . DEFAULT_LANGUAGE and not any ( self . errors ) : for form in self . forms : language_code = form . cleaned_data . get ( 'language_code' , None ) if language_code == setti...
Make sure there is at least a translation has been filled in . If a default language has been specified make sure that it exists amongst translations .
109
def _get_default_language ( self ) : assert hasattr ( self , 'available_languages' ) , 'No available languages have been generated.' assert len ( self . available_languages ) > 0 , 'No available languages to select from.' if ( settings . DEFAULT_LANGUAGE and settings . DEFAULT_LANGUAGE in self . available_languages ) o...
If a default language has been set and is still available in self . available_languages return it and remove it from the list .
110
def _construct_form ( self , i , ** kwargs ) : if not settings . HIDE_LANGUAGE : self . _construct_available_languages ( ) form = super ( TranslationFormSet , self ) . _construct_form ( i , ** kwargs ) if settings . HIDE_LANGUAGE : form . instance . language_code = settings . DEFAULT_LANGUAGE else : language_code = for...
Construct the form overriding the initial value for language_code .
111
def fq_merge ( R1 , R2 ) : c = itertools . cycle ( [ 1 , 2 , 3 , 4 ] ) for r1 , r2 in zip ( R1 , R2 ) : n = next ( c ) if n == 1 : pair = [ [ ] , [ ] ] pair [ 0 ] . append ( r1 . strip ( ) ) pair [ 1 ] . append ( r2 . strip ( ) ) if n == 4 : yield pair
merge separate fastq files
112
def _build_circle ( self ) : total_weight = 0 for node in self . _nodes : total_weight += self . _weights . get ( node , 1 ) for node in self . _nodes : weight = self . _weights . get ( node , 1 ) ks = math . floor ( ( 40 * len ( self . _nodes ) * weight ) / total_weight ) for i in xrange ( 0 , int ( ks ) ) : b_key = s...
Creates hash ring .
113
def _gen_key ( self , key ) : b_key = self . _md5_digest ( key ) return self . _hashi ( b_key , lambda x : x )
Return long integer for a given key that represent it place on the hash ring .
114
def has_custom_image ( user_context , app_id ) : possible_paths = _valid_custom_image_paths ( user_context , app_id ) return any ( map ( os . path . exists , possible_paths ) )
Returns True if there exists a custom image for app_id .
115
def get_custom_image ( user_context , app_id ) : possible_paths = _valid_custom_image_paths ( user_context , app_id ) existing_images = filter ( os . path . exists , possible_paths ) if len ( existing_images ) > 0 : return existing_images [ 0 ]
Returns the custom image associated with a given app . If there are multiple candidate images on disk one is chosen arbitrarily .
116
def set_custom_image ( user_context , app_id , image_path ) : if image_path is None : return False if not os . path . exists ( image_path ) : return False ( root , ext ) = os . path . splitext ( image_path ) if not is_valid_extension ( ext ) : return False if has_custom_image ( user_context , app_id ) : img = get_custo...
Sets the custom image for app_id to be the image located at image_path . If there already exists a custom image for app_id it will be deleted . Returns True is setting the image was successful .
117
def from_file ( cls , fname , form = None ) : try : tg = TableGroup . from_file ( fname ) opfname = None except JSONDecodeError : tg = TableGroup . fromvalue ( cls . MD ) opfname = fname if len ( tg . tables ) != 1 : raise ValueError ( 'profile description must contain exactly one table' ) metadata = tg . common_props ...
Read an orthography profile from a metadata file or a default tab - separated profile file .
118
def from_text ( cls , text , mapping = 'mapping' ) : graphemes = Counter ( grapheme_pattern . findall ( text ) ) specs = [ OrderedDict ( [ ( cls . GRAPHEME_COL , grapheme ) , ( 'frequency' , frequency ) , ( mapping , grapheme ) ] ) for grapheme , frequency in graphemes . most_common ( ) ] return cls ( * specs )
Create a Profile instance from the Unicode graphemes found in text .
119
def split_fasta ( f , id2f ) : opened = { } for seq in parse_fasta ( f ) : id = seq [ 0 ] . split ( '>' ) [ 1 ] . split ( ) [ 0 ] if id not in id2f : continue fasta = id2f [ id ] if fasta not in opened : opened [ fasta ] = '%s.fa' % fasta seq [ 1 ] += '\n' with open ( opened [ fasta ] , 'a+' ) as f_out : f_out . write ...
split fasta file into separate fasta files based on list of scaffolds that belong to each separate file
120
def _is_user_directory ( self , pathname ) : fullpath = os . path . join ( self . userdata_location ( ) , pathname ) return os . path . isdir ( fullpath ) and pathname . isdigit ( )
Check whether pathname is a valid user data directory
121
def local_users ( self ) : userdirs = filter ( self . _is_user_directory , os . listdir ( self . userdata_location ( ) ) ) return map ( lambda userdir : user . User ( self , int ( userdir ) ) , userdirs )
Returns an array of user ids for users on the filesystem
122
def _calculate_degree_days ( temperature_equivalent , base_temperature , cooling = False ) : if cooling : ret = temperature_equivalent - base_temperature else : ret = base_temperature - temperature_equivalent ret [ ret < 0 ] = 0 prefix = 'CDD' if cooling else 'HDD' ret . name = '{}_{}' . format ( prefix , base_temperat...
Calculates degree days starting with a series of temperature equivalent values
123
def status ( self ) : return { self . _acronym_status ( l ) : l for l in self . resp_text . split ( '\n' ) if l . startswith ( self . prefix_status ) }
Development status .
124
def licenses ( self ) : return { self . _acronym_lic ( l ) : l for l in self . resp_text . split ( '\n' ) if l . startswith ( self . prefix_lic ) }
OSI Approved license .
125
def licenses_desc ( self ) : return { self . _acronym_lic ( l ) : l . split ( self . prefix_lic ) [ 1 ] for l in self . resp_text . split ( '\n' ) if l . startswith ( self . prefix_lic ) }
Remove prefix .
126
def _acronym_lic ( self , license_statement ) : pat = re . compile ( r'\(([\w+\W?\s?]+)\)' ) if pat . search ( license_statement ) : lic = pat . search ( license_statement ) . group ( 1 ) if lic . startswith ( 'CNRI' ) : acronym_licence = lic [ : 4 ] else : acronym_licence = lic . replace ( ' ' , '' ) else : acronym_li...
Convert license acronym .
127
def calcMD5 ( path ) : if os . path . exists ( path ) is False : yield False else : command = [ 'md5sum' , path ] p = Popen ( command , stdout = PIPE ) for line in p . communicate ( ) [ 0 ] . splitlines ( ) : yield line . decode ( 'ascii' ) . strip ( ) . split ( ) [ 0 ] p . wait ( ) yield False
calc MD5 based on path
128
def wget ( ftp , f = False , exclude = False , name = False , md5 = False , tries = 10 ) : if f is False : f = ftp . rsplit ( '/' , 1 ) [ - 1 ] t = 0 while md5check ( f , ftp , md5 , exclude ) is not True : t += 1 if name is not False : print ( '# downloading:' , name , f ) if exclude is False : command = 'wget -q --ra...
download files with wget
129
def check ( line , queries ) : line = line . strip ( ) spLine = line . replace ( '.' , ' ' ) . split ( ) matches = set ( spLine ) . intersection ( queries ) if len ( matches ) > 0 : return matches , line . split ( '\t' ) return matches , False
check that at least one of queries is in list l
130
def entrez ( db , acc ) : c1 = [ 'esearch' , '-db' , db , '-query' , acc ] c2 = [ 'efetch' , '-db' , 'BioSample' , '-format' , 'docsum' ] p1 = Popen ( c1 , stdout = PIPE , stderr = PIPE ) p2 = Popen ( c2 , stdin = p1 . stdout , stdout = PIPE , stderr = PIPE ) return p2 . communicate ( )
search entrez using specified database and accession
131
def searchAccession ( acc ) : out , error = entrez ( 'genome' , acc ) for line in out . splitlines ( ) : line = line . decode ( 'ascii' ) . strip ( ) if 'Assembly_Accession' in line or 'BioSample' in line : newAcc = line . split ( '>' ) [ 1 ] . split ( '<' ) [ 0 ] . split ( '.' ) [ 0 ] . split ( ',' ) [ 0 ] if len ( ne...
attempt to use NCBI Entrez to get BioSample ID
132
def getFTPs ( accessions , ftp , search , exclude , convert = False , threads = 1 , attempt = 1 , max_attempts = 2 ) : info = wget ( ftp ) [ 0 ] allMatches = [ ] for genome in open ( info , encoding = 'utf8' ) : genome = str ( genome ) matches , genomeInfo = check ( genome , accessions ) if genomeInfo is not False : f ...
download genome info from NCBI
133
def download ( args ) : accessions , infoFTP = set ( args [ 'g' ] ) , args [ 'i' ] search , exclude = args [ 's' ] , args [ 'e' ] FTPs = getFTPs ( accessions , infoFTP , search , exclude , threads = args [ 't' ] , convert = args [ 'convert' ] ) if args [ 'test' ] is True : for genome in FTPs : print ( 'found:' , ';' . ...
download genomes from NCBI
134
def fix_fasta ( fasta ) : for seq in parse_fasta ( fasta ) : seq [ 0 ] = remove_char ( seq [ 0 ] ) if len ( seq [ 1 ] ) > 0 : yield seq
remove pesky characters from fasta file header
135
def _calc_frames ( stats ) : timings = [ ] callers = [ ] for key , values in iteritems ( stats . stats ) : timings . append ( pd . Series ( key + values [ : - 1 ] , index = timing_colnames , ) ) for caller_key , caller_values in iteritems ( values [ - 1 ] ) : callers . append ( pd . Series ( key + caller_key + caller_v...
Compute a DataFrame summary of a Stats object .
136
def unmapped ( sam , mates ) : for read in sam : if read . startswith ( '@' ) is True : continue read = read . strip ( ) . split ( ) if read [ 2 ] == '*' and read [ 6 ] == '*' : yield read elif mates is True : if read [ 2 ] == '*' or read [ 6 ] == '*' : yield read for i in read : if i == 'YT:Z:UP' : yield read
get unmapped reads
137
def parallel ( processes , threads ) : pool = multithread ( threads ) pool . map ( run_process , processes ) pool . close ( ) pool . join ( )
execute jobs in processes using N threads
138
def define_log_renderer ( fmt , fpath , quiet ) : if fmt : return structlog . processors . JSONRenderer ( ) if fpath is not None : return structlog . processors . JSONRenderer ( ) if sys . stderr . isatty ( ) and not quiet : return structlog . dev . ConsoleRenderer ( ) return structlog . processors . JSONRenderer ( )
the final log processor that structlog requires to render .
139
def _structlog_default_keys_processor ( logger_class , log_method , event ) : global HOSTNAME if 'id' not in event : event [ 'id' ] = '%s_%s' % ( datetime . utcnow ( ) . strftime ( '%Y%m%dT%H%M%S' ) , uuid . uuid1 ( ) . hex ) if 'type' not in event : event [ 'type' ] = 'log' event [ 'host' ] = HOSTNAME return event
Add unique id type and hostname
140
def define_log_processors ( ) : return [ structlog . processors . TimeStamper ( fmt = "iso" ) , _structlog_default_keys_processor , structlog . stdlib . PositionalArgumentsFormatter ( ) , structlog . processors . StackInfoRenderer ( ) , structlog . processors . format_exc_info , ]
log processors that structlog executes before final rendering
141
def _configure_logger ( fmt , quiet , level , fpath , pre_hooks , post_hooks , metric_grouping_interval ) : level = getattr ( logging , level . upper ( ) ) global _GLOBAL_LOG_CONFIGURED if _GLOBAL_LOG_CONFIGURED : return def wrap_hook ( fn ) : @ wraps ( fn ) def processor ( logger , method_name , event_dict ) : fn ( ev...
configures a logger when required write to stderr or a file
142
def _add_base_info ( self , event_dict ) : f = sys . _getframe ( ) level_method_frame = f . f_back caller_frame = level_method_frame . f_back return event_dict
Instead of using a processor adding basic information like caller filename etc here .
143
def _proxy_to_logger ( self , method_name , event , * event_args , ** event_kw ) : if isinstance ( event , bytes ) : event = event . decode ( 'utf-8' ) if event_args : event_kw [ 'positional_args' ] = event_args return super ( BoundLevelLogger , self ) . _proxy_to_logger ( method_name , event = event , ** event_kw )
Propagate a method call to the wrapped logger .
144
def translate ( rect , x , y , width = 1 ) : return ( ( rect [ 0 ] [ 0 ] + x , rect [ 0 ] [ 1 ] + y ) , ( rect [ 1 ] [ 0 ] + x , rect [ 1 ] [ 1 ] + y ) , ( rect [ 2 ] [ 0 ] + x + width , rect [ 2 ] [ 1 ] + y ) , ( rect [ 3 ] [ 0 ] + x + width , rect [ 3 ] [ 1 ] + y ) )
Given four points of a rectangle translate the rectangle to the specified x and y coordinates and optionally change the width .
145
def remove_bad ( string ) : remove = [ ':' , ',' , '(' , ')' , ' ' , '|' , ';' , '\'' ] for c in remove : string = string . replace ( c , '_' ) return string
remove problem characters from string
146
def get_ids ( a ) : a_id = '%s.id.fa' % ( a . rsplit ( '.' , 1 ) [ 0 ] ) a_id_lookup = '%s.id.lookup' % ( a . rsplit ( '.' , 1 ) [ 0 ] ) if check ( a_id ) is True : return a_id , a_id_lookup a_id_f = open ( a_id , 'w' ) a_id_lookup_f = open ( a_id_lookup , 'w' ) ids = [ ] for seq in parse_fasta ( open ( a ) ) : id = id...
make copy of sequences with short identifier
147
def convert2phylip ( convert ) : out = '%s.phy' % ( convert . rsplit ( '.' , 1 ) [ 0 ] ) if check ( out ) is False : convert = open ( convert , 'rU' ) out_f = open ( out , 'w' ) alignments = AlignIO . parse ( convert , "fasta" ) AlignIO . write ( alignments , out , "phylip" ) return out
convert fasta to phylip because RAxML is ridiculous
148
def run_iqtree ( phy , model , threads , cluster , node ) : if threads > 24 : ppn = 24 else : ppn = threads tree = '%s.treefile' % ( phy ) if check ( tree ) is False : if model is False : model = 'TEST' dir = os . getcwd ( ) command = 'iqtree-omp -s %s -m %s -nt %s -quiet' % ( phy , model , threads ) if cluster is Fals...
run IQ - Tree
149
def fix_tree ( tree , a_id_lookup , out ) : if check ( out ) is False and check ( tree ) is True : tree = open ( tree ) . read ( ) for line in open ( a_id_lookup ) : id , name , header = line . strip ( ) . split ( '\t' ) tree = tree . replace ( id + ':' , name + ':' ) out_f = open ( out , 'w' ) print ( tree . strip ( )...
get the names for sequences in the raxml tree
150
def create_cluster ( settings ) : settings = copy . deepcopy ( settings ) backend = settings . pop ( 'engine' , settings . pop ( 'backend' , None ) ) if isinstance ( backend , basestring ) : Conn = import_string ( backend ) elif backend : Conn = backend else : raise KeyError ( 'backend' ) cluster = settings . pop ( 'cl...
Creates a new Nydus cluster from the given settings .
151
def _get_translation ( self , field , code ) : if not code in self . _translation_cache : translations = self . translations . select_related ( ) logger . debug ( u'Matched with field %s for language %s. Attempting lookup.' , field , code ) try : translation_obj = translations . get ( language_code = code ) except Obje...
Gets the translation of a specific field for a specific language code .
152
def unicode_wrapper ( self , property , default = ugettext ( 'Untitled' ) ) : try : value = getattr ( self , property ) except ValueError : logger . warn ( u'ValueError rendering unicode for %s object.' , self . _meta . object_name ) value = None if not value : value = default return value
Wrapper to allow for easy unicode representation of an object by the specified property . If this wrapper is not able to find the right translation of the specified property it will return the default value instead .
153
def strip_inserts ( fasta ) : for seq in parse_fasta ( fasta ) : seq [ 1 ] = '' . join ( [ b for b in seq [ 1 ] if b == '-' or b . isupper ( ) ] ) yield seq
remove insertion columns from aligned fasta file
154
def transform ( self , word , column = Profile . GRAPHEME_COL , error = errors . replace ) : assert self . op , 'method can only be called with orthography profile.' if column != Profile . GRAPHEME_COL and column not in self . op . column_labels : raise ValueError ( "Column {0} not found in profile." . format ( column ...
Transform a string s graphemes into the mappings given in a different column in the orthography profile .
155
def rules ( self , word ) : return self . _rules . apply ( word ) if self . _rules else word
Function to tokenize input string and return output of str with ortho rules applied .
156
def combine_modifiers ( self , graphemes ) : result = [ ] temp = "" count = len ( graphemes ) for grapheme in reversed ( graphemes ) : count -= 1 if len ( grapheme ) == 1 and unicodedata . category ( grapheme ) == "Lm" and not ord ( grapheme ) in [ 712 , 716 ] : temp = grapheme + temp if count == 0 : result [ - 1 ] = t...
Given a string that is space - delimited on Unicode grapheme clusters group Unicode modifier letters with their preceding base characters deal with tie bars etc .
157
def parse_catalytic ( insertion , gff ) : offset = insertion [ 'offset' ] GeneStrand = insertion [ 'strand' ] if type ( insertion [ 'intron' ] ) is not str : return gff for intron in parse_fasta ( insertion [ 'intron' ] . split ( '|' ) ) : ID , annot , strand , pos = intron [ 0 ] . split ( '>' ) [ 1 ] . split ( ) Start...
parse catalytic RNAs to gff format
158
def parse_orf ( insertion , gff ) : offset = insertion [ 'offset' ] if type ( insertion [ 'orf' ] ) is not str : return gff for orf in parse_fasta ( insertion [ 'orf' ] . split ( '|' ) ) : ID = orf [ 0 ] . split ( '>' ) [ 1 ] . split ( ) [ 0 ] Start , End , strand = [ int ( i ) for i in orf [ 0 ] . split ( ' # ' ) [ 1 ...
parse ORF to gff format
159
def parse_insertion ( insertion , gff ) : offset = insertion [ 'offset' ] for ins in parse_fasta ( insertion [ 'insertion sequence' ] . split ( '|' ) ) : strand = insertion [ 'strand' ] ID = ins [ 0 ] . split ( '>' ) [ 1 ] . split ( ) [ 0 ] Start , End = [ int ( i ) for i in ins [ 0 ] . split ( 'gene-pos=' , 1 ) [ 1 ] ...
parse insertion to gff format
160
def parse_rRNA ( insertion , seq , gff ) : offset = insertion [ 'offset' ] strand = insertion [ 'strand' ] for rRNA in parse_masked ( seq , 0 ) [ 0 ] : rRNA = '' . join ( rRNA ) Start = seq [ 1 ] . find ( rRNA ) + 1 End = Start + len ( rRNA ) - 1 if strand == '-' : Start , End = End - 2 , Start - 2 pos = ( abs ( Start ...
parse rRNA to gff format
161
def iTable2GFF ( iTable , fa , contig = False ) : columns = [ '#seqname' , 'source' , 'feature' , 'start' , 'end' , 'score' , 'strand' , 'frame' , 'attribute' ] gff = { c : [ ] for c in columns } for insertion in iTable . iterrows ( ) : insertion = insertion [ 1 ] if insertion [ 'ID' ] not in fa : continue strand = ins...
convert iTable to gff file
162
def summarize_taxa ( biom ) : tamtcounts = defaultdict ( int ) tot_seqs = 0.0 for row , col , amt in biom [ 'data' ] : tot_seqs += amt rtax = biom [ 'rows' ] [ row ] [ 'metadata' ] [ 'taxonomy' ] for i , t in enumerate ( rtax ) : t = t . strip ( ) if i == len ( rtax ) - 1 and len ( t ) > 3 and len ( rtax [ - 1 ] ) > 3 ...
Given an abundance table group the counts by every taxonomic level .
163
def custom_image ( self , user ) : for ext in self . valid_custom_image_extensions ( ) : image_location = self . _custom_image_path ( user , ext ) if os . path . isfile ( image_location ) : return image_location return None
Returns the path to the custom image set for this game or None if no image is set
164
def set_image ( self , user , image_path ) : _ , ext = os . path . splitext ( image_path ) shutil . copy ( image_path , self . _custom_image_path ( user , ext ) )
Sets a custom image for the game . image_path should refer to an image file on disk
165
def sam_list ( sam ) : list = [ ] for file in sam : for line in file : if line . startswith ( '@' ) is False : line = line . strip ( ) . split ( ) id , map = line [ 0 ] , int ( line [ 1 ] ) if map != 4 and map != 8 : list . append ( id ) return set ( list )
get a list of mapped reads
166
def sam_list_paired ( sam ) : list = [ ] pair = [ '1' , '2' ] prev = '' for file in sam : for line in file : if line . startswith ( '@' ) is False : line = line . strip ( ) . split ( ) id , map = line [ 0 ] , int ( line [ 1 ] ) if map != 4 and map != 8 : read = id . rsplit ( '/' ) [ 0 ] if read == prev : list . append ...
get a list of mapped reads require that both pairs are mapped in the sam file in order to remove the reads
167
def filter_paired ( list ) : pairs = { } filtered = [ ] for id in list : read = id . rsplit ( '/' ) [ 0 ] if read not in pairs : pairs [ read ] = [ ] pairs [ read ] . append ( id ) for read in pairs : ids = pairs [ read ] if len ( ids ) == 2 : filtered . extend ( ids ) return set ( filtered )
require that both pairs are mapped in the sam file in order to remove the reads
168
def sam2fastq ( line ) : fastq = [ ] fastq . append ( '@%s' % line [ 0 ] ) fastq . append ( line [ 9 ] ) fastq . append ( '+%s' % line [ 0 ] ) fastq . append ( line [ 10 ] ) return fastq
print fastq from sam
169
def check_mismatches ( read , pair , mismatches , mm_option , req_map ) : if pair is False : mm = count_mismatches ( read ) if mm is False : return False if mismatches is False : return True if mm <= mismatches : return True r_mm = count_mismatches ( read ) p_mm = count_mismatches ( pair ) if r_mm is False and p_mm is ...
- check to see if the read maps with < = threshold number of mismatches - mm_option = one or both depending on whether or not one or both reads in a pair need to pass the mismatch threshold - pair can be False if read does not have a pair - make sure alignment score is not 0 which would indicate that the read was not a...
170
def check_region ( read , pair , region ) : if region is False : return True for mapping in read , pair : if mapping is False : continue start , length = int ( mapping [ 3 ] ) , len ( mapping [ 9 ] ) r = [ start , start + length - 1 ] if get_overlap ( r , region ) > 0 : return True return False
determine whether or not reads map to specific region of scaffold
171
def get_steam ( ) : helper = lambda udd : Steam ( udd ) if os . path . exists ( udd ) else None plat = platform . system ( ) if plat == 'Darwin' : return helper ( paths . default_osx_userdata_path ( ) ) if plat == 'Linux' : return helper ( paths . default_linux_userdata_path ( ) ) if plat == 'Windows' : possible_dir = ...
Returns a Steam object representing the current Steam installation on the users computer . If the user doesn t have Steam installed returns None .
172
def zero_to_one ( table , option ) : if option == 'table' : m = min ( min ( table ) ) ma = max ( max ( table ) ) t = [ ] for row in table : t_row = [ ] if option != 'table' : m , ma = min ( row ) , max ( row ) for i in row : if ma == m : t_row . append ( 0 ) else : t_row . append ( ( i - m ) / ( ma - m ) ) t . append (...
normalize from zero to one for row or table
173
def pertotal ( table , option ) : if option == 'table' : total = sum ( [ i for line in table for i in line ] ) t = [ ] for row in table : t_row = [ ] if option != 'table' : total = sum ( row ) for i in row : if total == 0 : t_row . append ( 0 ) else : t_row . append ( i / total * 100 ) t . append ( t_row ) return t
calculate percent of total
174
def scale ( table ) : t = [ ] columns = [ [ ] for i in table [ 0 ] ] for row in table : for i , v in enumerate ( row ) : columns [ i ] . append ( v ) sums = [ float ( sum ( i ) ) for i in columns ] scale_to = float ( max ( sums ) ) scale_factor = [ scale_to / i for i in sums if i != 0 ] for row in table : t . append ( ...
scale table based on the column with the largest sum
175
def norm ( table ) : print ( '# norm dist is broken' , file = sys . stderr ) exit ( ) from matplotlib . pyplot import hist as hist t = [ ] for i in table : t . append ( np . ndarray . tolist ( hist ( i , bins = len ( i ) , normed = True ) [ 0 ] ) ) return t
fit to normal distribution
176
def log_trans ( table ) : t = [ ] all = [ item for sublist in table for item in sublist ] if min ( all ) == 0 : scale = min ( [ i for i in all if i != 0 ] ) * 10e-10 else : scale = 0 for i in table : t . append ( np . ndarray . tolist ( np . log10 ( [ j + scale for j in i ] ) ) ) return t
log transform each value in table
177
def box_cox ( table ) : from scipy . stats import boxcox as bc t = [ ] for i in table : if min ( i ) == 0 : scale = min ( [ j for j in i if j != 0 ] ) * 10e-10 else : scale = 0 t . append ( np . ndarray . tolist ( bc ( np . array ( [ j + scale for j in i ] ) ) [ 0 ] ) ) return t
box - cox transform table
178
def inh ( table ) : t = [ ] for i in table : t . append ( np . ndarray . tolist ( np . arcsinh ( i ) ) ) return t
inverse hyperbolic sine transformation
179
def diri ( table ) : t = [ ] for i in table : a = [ j + 1 for j in i ] t . append ( np . ndarray . tolist ( np . random . mtrand . dirichlet ( a ) ) ) return t
from SparCC - randomly draw from the corresponding posterior Dirichlet distribution with a uniform prior
180
def generate_barcodes ( nIds , codeLen = 12 ) : def next_code ( b , c , i ) : return c [ : i ] + b + ( c [ i + 1 : ] if i < - 1 else '' ) def rand_base ( ) : return random . choice ( [ 'A' , 'T' , 'C' , 'G' ] ) def rand_seq ( n ) : return '' . join ( [ rand_base ( ) for _ in range ( n ) ] ) hpf = re . compile ( 'aaaa|c...
Given a list of sample IDs generate unique n - base barcodes for each . Note that only 4^n unique barcodes are possible .
181
def scrobble_data_dir ( dataDir , sampleMap , outF , qualF = None , idopt = None , utf16 = False ) : seqcount = 0 outfiles = [ osp . split ( outF . name ) [ 1 ] ] if qualF : outfiles . append ( osp . split ( qualF . name ) [ 1 ] ) for item in os . listdir ( dataDir ) : if item in outfiles or not osp . isfile ( os . pat...
Given a sample ID and a mapping modify a Sanger FASTA file to include the barcode and primer in the sequence data and change the description line as needed .
182
def handle_program_options ( ) : parser = argparse . ArgumentParser ( description = "Convert Sanger-sequencing \ derived data files for use with the \ metagenomics analysis program QIIME, by \ extracting Sample I...
Uses the built - in argparse module to handle command - line options for the program .
183
def arcsin_sqrt ( biom_tbl ) : arcsint = lambda data , id_ , md : np . arcsin ( np . sqrt ( data ) ) tbl_relabd = relative_abd ( biom_tbl ) tbl_asin = tbl_relabd . transform ( arcsint , inplace = False ) return tbl_asin
Applies the arcsine square root transform to the given BIOM - format table
184
def parse_sam ( sam , qual ) : for line in sam : if line . startswith ( '@' ) : continue line = line . strip ( ) . split ( ) if int ( line [ 4 ] ) == 0 or int ( line [ 4 ] ) < qual : continue yield line
parse sam file and check mapping quality
185
def rc_stats ( stats ) : rc_nucs = { 'A' : 'T' , 'T' : 'A' , 'G' : 'C' , 'C' : 'G' , 'N' : 'N' } rcs = [ ] for pos in reversed ( stats ) : rc = { } rc [ 'reference frequencey' ] = pos [ 'reference frequency' ] rc [ 'consensus frequencey' ] = pos [ 'consensus frequency' ] rc [ 'In' ] = pos [ 'In' ] rc [ 'Del' ] = pos [ ...
reverse completement stats
186
def parse_codons ( ref , start , end , strand ) : codon = [ ] c = cycle ( [ 1 , 2 , 3 ] ) ref = ref [ start - 1 : end ] if strand == - 1 : ref = rc_stats ( ref ) for pos in ref : n = next ( c ) codon . append ( pos ) if n == 3 : yield codon codon = [ ]
parse codon nucleotide positions in range start - > end wrt strand
187
def calc_coverage ( ref , start , end , length , nucs ) : ref = ref [ start - 1 : end ] bases = 0 for pos in ref : for base , count in list ( pos . items ( ) ) : if base in nucs : bases += count return float ( bases ) / float ( length )
calculate coverage for positions in range start - > end
188
def parse_gbk ( gbks ) : for gbk in gbks : for record in SeqIO . parse ( open ( gbk ) , 'genbank' ) : for feature in record . features : if feature . type == 'gene' : try : locus = feature . qualifiers [ 'locus_tag' ] [ 0 ] except : continue if feature . type == 'CDS' : try : locus = feature . qualifiers [ 'locus_tag' ...
parse gbk file
189
def parse_fasta_annotations ( fastas , annot_tables , trans_table ) : if annot_tables is not False : annots = { } for table in annot_tables : for cds in open ( table ) : ID , start , end , strand = cds . strip ( ) . split ( ) annots [ ID ] = [ start , end , int ( strand ) ] for fasta in fastas : for seq in parse_fasta ...
parse gene call information from Prodigal fasta output
190
def parse_annotations ( annots , fmt , annot_tables , trans_table ) : annotations = { } if fmt is False : for contig , feature in parse_gbk ( annots ) : if contig not in annotations : annotations [ contig ] = [ ] annotations [ contig ] . append ( feature ) else : for contig , feature in parse_fasta_annotations ( annots...
parse annotations in either gbk or Prodigal fasta format
191
def codon2aa ( codon , trans_table ) : return Seq ( '' . join ( codon ) , IUPAC . ambiguous_dna ) . translate ( table = trans_table ) [ 0 ]
convert codon to amino acid
192
def find_consensus ( bases ) : nucs = [ 'A' , 'T' , 'G' , 'C' , 'N' ] total = sum ( [ bases [ nuc ] for nuc in nucs if nuc in bases ] ) try : top = max ( [ bases [ nuc ] for nuc in nucs if nuc in bases ] ) except : bases [ 'consensus' ] = ( 'N' , 'n/a' ) bases [ 'consensus frequency' ] = 'n/a' bases [ 'reference freque...
find consensus base based on nucleotide frequencies
193
def print_consensus ( genomes ) : cons = { } for genome , contigs in list ( genomes . items ( ) ) : cons [ genome ] = { } for contig , samples in list ( contigs . items ( ) ) : for sample , stats in list ( samples . items ( ) ) : if sample not in cons [ genome ] : cons [ genome ] [ sample ] = { } seq = cons [ genome ] ...
print consensensus sequences for each genome and sample
194
def parse_cov ( cov_table , scaffold2genome ) : size = { } mapped = { } for line in open ( cov_table ) : line = line . strip ( ) . split ( '\t' ) if line [ 0 ] . startswith ( '#' ) : samples = line [ 1 : ] samples = [ i . rsplit ( '/' , 1 ) [ - 1 ] . split ( '.' , 1 ) [ 0 ] for i in samples ] continue scaffold , length...
calculate genome coverage from scaffold coverage table
195
def genome_coverage ( covs , s2b ) : COV = [ ] for cov in covs : COV . append ( parse_cov ( cov , s2b ) ) return pd . concat ( COV )
calculate genome coverage from scaffold coverage
196
def parse_s2bs ( s2bs ) : s2b = { } for s in s2bs : for line in open ( s ) : line = line . strip ( ) . split ( '\t' ) s , b = line [ 0 ] , line [ 1 ] s2b [ s ] = b return s2b
convert s2b files to dictionary
197
def fa2s2b ( fastas ) : s2b = { } for fa in fastas : for seq in parse_fasta ( fa ) : s = seq [ 0 ] . split ( '>' , 1 ) [ 1 ] . split ( ) [ 0 ] s2b [ s ] = fa . rsplit ( '/' , 1 ) [ - 1 ] . rsplit ( '.' , 1 ) [ 0 ] return s2b
convert fastas to s2b dictionary
198
def filter_ambiguity ( records , percent = 0.5 ) : seqs = [ ] count = 0 for record in records : if record . seq . count ( 'N' ) / float ( len ( record ) ) < percent : seqs . append ( record ) count += 1 return seqs , count
Filters out sequences with too much ambiguity as defined by the method parameters .
199
def package_existent ( name ) : try : response = requests . get ( PYPI_URL . format ( name ) ) if response . ok : msg = ( '[error] "{0}" is registered already in PyPI.\n' '\tSpecify another package name.' ) . format ( name ) raise Conflict ( msg ) except ( socket . gaierror , Timeout , ConnectionError , HTTPError ) as ...
Search package .