idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
38,900
def space_lock ( args ) : r = fapi . lock_workspace ( args . project , args . workspace ) fapi . _check_response_code ( r , 204 ) if fcconfig . verbosity : eprint ( 'Locked workspace {0}/{1}' . format ( args . project , args . workspace ) ) return 0
Lock a workspace
38,901
def space_unlock ( args ) : r = fapi . unlock_workspace ( args . project , args . workspace ) fapi . _check_response_code ( r , 204 ) if fcconfig . verbosity : eprint ( 'Unlocked workspace {0}/{1}' . format ( args . project , args . workspace ) ) return 0
Unlock a workspace
38,902
def space_new ( args ) : r = fapi . create_workspace ( args . project , args . workspace , args . authdomain , dict ( ) ) fapi . _check_response_code ( r , 201 ) if fcconfig . verbosity : eprint ( r . content ) return 0
Create a new workspace .
38,903
def space_info ( args ) : r = fapi . get_workspace ( args . project , args . workspace ) fapi . _check_response_code ( r , 200 ) return r . text
Get metadata for a workspace .
38,904
def space_delete ( args ) : message = "WARNING: this will delete workspace: \n\t{0}/{1}" . format ( args . project , args . workspace ) if not args . yes and not _confirm_prompt ( message ) : return 0 r = fapi . delete_workspace ( args . project , args . workspace ) fapi . _check_response_code ( r , [ 200 , 202 , 204 ,...
Delete a workspace .
38,905
def space_clone ( args ) : if not args . to_workspace : args . to_workspace = args . workspace if not args . to_project : args . to_project = args . project if ( args . project == args . to_project and args . workspace == args . to_workspace ) : eprint ( "Error: destination project and namespace must differ from" " clo...
Replicate a workspace
38,906
def space_acl ( args ) : r = fapi . get_workspace_acl ( args . project , args . workspace ) fapi . _check_response_code ( r , 200 ) result = dict ( ) for user , info in sorted ( r . json ( ) [ 'acl' ] . items ( ) ) : result [ user ] = info [ 'accessLevel' ] return result
Retrieve access control list for a workspace
38,907
def space_set_acl ( args ) : acl_updates = [ { "email" : user , "accessLevel" : args . role } for user in args . users ] r = fapi . update_workspace_acl ( args . project , args . workspace , acl_updates ) fapi . _check_response_code ( r , 200 ) errors = r . json ( ) [ 'usersNotFound' ] if len ( errors ) : eprint ( "Una...
Assign an ACL role to list of users for a workspace
38,908
def space_search ( args ) : r = fapi . list_workspaces ( ) fapi . _check_response_code ( r , 200 ) workspaces = r . json ( ) extra_terms = [ ] if args . bucket : workspaces = [ w for w in workspaces if re . search ( args . bucket , w [ 'workspace' ] [ 'bucketName' ] ) ] extra_terms . append ( 'bucket' ) pretty_spaces =...
Search for workspaces matching certain criteria
38,909
def entity_import ( args ) : project = args . project workspace = args . workspace chunk_size = args . chunk_size with open ( args . tsvfile ) as tsvf : headerline = tsvf . readline ( ) . strip ( ) entity_data = [ l . rstrip ( '\n' ) for l in tsvf ] return _batch_load ( project , workspace , headerline , entity_data , ...
Upload an entity loadfile .
38,910
def entity_types ( args ) : r = fapi . list_entity_types ( args . project , args . workspace ) fapi . _check_response_code ( r , 200 ) return r . json ( ) . keys ( )
List entity types in a workspace
38,911
def entity_list ( args ) : r = fapi . get_entities_with_type ( args . project , args . workspace ) fapi . _check_response_code ( r , 200 ) return [ '{0}\t{1}' . format ( e [ 'entityType' ] , e [ 'name' ] ) for e in r . json ( ) ]
List entities in a workspace .
38,912
def participant_list ( args ) : if args . entity_type and args . entity : if args . entity_type == 'participant' : return [ args . entity . strip ( ) ] r = fapi . get_entity ( args . project , args . workspace , args . entity_type , args . entity ) fapi . _check_response_code ( r , 200 ) participants = r . json ( ) [ '...
List participants within a container
38,913
def pair_list ( args ) : if args . entity_type and args . entity : if args . entity_type == 'pair' : return [ args . entity . strip ( ) ] elif args . entity_type == 'participant' : entities = _entity_paginator ( args . project , args . workspace , 'pair' , page_size = 2000 ) return [ e [ 'name' ] for e in entities if e...
List pairs within a container .
38,914
def sample_list ( args ) : if args . entity_type and args . entity : if args . entity_type == 'sample' : return [ args . entity . strip ( ) ] elif args . entity_type == 'participant' : samples = _entity_paginator ( args . project , args . workspace , 'sample' , page_size = 2000 ) return [ e [ 'name' ] for e in samples ...
List samples within a container .
38,915
def entity_delete ( args ) : msg = "WARNING: this will delete {0} {1} in {2}/{3}" . format ( args . entity_type , args . entity , args . project , args . workspace ) if not ( args . yes or _confirm_prompt ( msg ) ) : return json_body = [ { "entityType" : args . entity_type , "entityName" : args . entity } ] r = fapi . ...
Delete entity in a workspace .
38,916
def meth_wdl ( args ) : r = fapi . get_repository_method ( args . namespace , args . method , args . snapshot_id , True ) fapi . _check_response_code ( r , 200 ) return r . text
Retrieve WDL for given version of a repository method
38,917
def meth_acl ( args ) : r = fapi . get_repository_method_acl ( args . namespace , args . method , args . snapshot_id ) fapi . _check_response_code ( r , 200 ) acls = sorted ( r . json ( ) , key = lambda k : k [ 'user' ] ) return map ( lambda acl : '{0}\t{1}' . format ( acl [ 'user' ] , acl [ 'role' ] ) , acls )
Retrieve access control list for given version of a repository method
38,918
def meth_set_acl ( args ) : acl_updates = [ { "user" : user , "role" : args . role } for user in set ( expand_fc_groups ( args . users ) ) if user != fapi . whoami ( ) ] id = args . snapshot_id if not id : r = fapi . list_repository_methods ( namespace = args . namespace , name = args . method ) fapi . _check_response_...
Assign an ACL role to a list of users for a workflow .
38,919
def expand_fc_groups ( users ) : groups = None for user in users : fcgroup = None if '@' not in user : fcgroup = user elif user . lower ( ) . endswith ( '@firecloud.org' ) : if groups is None : r = fapi . get_groups ( ) fapi . _check_response_code ( r , 200 ) groups = { group [ 'groupEmail' ] . lower ( ) : group [ 'gro...
If user is a firecloud group return all members of the group . Caveat is that only group admins may do this .
38,920
def meth_list ( args ) : r = fapi . list_repository_methods ( namespace = args . namespace , name = args . method , snapshotId = args . snapshot_id ) fapi . _check_response_code ( r , 200 ) methods = r . json ( ) results = [ ] for m in methods : ns = m [ 'namespace' ] n = m [ 'name' ] sn_id = m [ 'snapshotId' ] results...
List workflows in the methods repository
38,921
def config_acl ( args ) : r = fapi . get_repository_config_acl ( args . namespace , args . config , args . snapshot_id ) fapi . _check_response_code ( r , 200 ) acls = sorted ( r . json ( ) , key = lambda k : k [ 'user' ] ) return map ( lambda acl : '{0}\t{1}' . format ( acl [ 'user' ] , acl [ 'role' ] ) , acls )
Retrieve access control list for a method configuration
38,922
def config_set_acl ( args ) : acl_updates = [ { "user" : user , "role" : args . role } for user in set ( expand_fc_groups ( args . users ) ) if user != fapi . whoami ( ) ] id = args . snapshot_id if not id : r = fapi . list_repository_configs ( namespace = args . namespace , name = args . config ) fapi . _check_respons...
Assign an ACL role to a list of users for a config .
38,923
def config_get ( args ) : r = fapi . get_workspace_config ( args . project , args . workspace , args . namespace , args . config ) fapi . _check_response_code ( r , 200 ) return json . dumps ( r . json ( ) , indent = 4 , separators = ( ',' , ': ' ) , sort_keys = True , ensure_ascii = False )
Retrieve a method config from a workspace send stdout
38,924
def config_wdl ( args ) : r = fapi . get_workspace_config ( args . project , args . workspace , args . namespace , args . config ) fapi . _check_response_code ( r , 200 ) method = r . json ( ) [ "methodRepoMethod" ] args . namespace = method [ "methodNamespace" ] args . method = method [ "methodName" ] args . snapshot_...
Retrieve the WDL for a method config in a workspace send stdout
38,925
def config_diff ( args ) : config_1 = config_get ( args ) . splitlines ( ) args . project = args . Project args . workspace = args . Workspace cfg_1_name = args . config if args . Config is not None : args . config = args . Config if args . Namespace is not None : args . namespace = args . Namespace config_2 = config_g...
Compare method configuration definitions across workspaces . Ignores methodConfigVersion if the verbose argument is not set
38,926
def config_delete ( args ) : r = fapi . delete_workspace_config ( args . project , args . workspace , args . namespace , args . config ) fapi . _check_response_code ( r , [ 200 , 204 ] ) return r . text if r . text else None
Remove a method config from a workspace
38,927
def attr_copy ( args ) : if not args . to_workspace : args . to_workspace = args . workspace if not args . to_project : args . to_project = args . project if ( args . project == args . to_project and args . workspace == args . to_workspace ) : eprint ( "destination project and namespace must differ from" " source works...
Copy workspace attributes between workspaces .
38,928
def health ( args ) : r = fapi . health ( ) fapi . _check_response_code ( r , 200 ) return r . content
Health FireCloud Server
38,929
def sset_loop ( args ) : fiss_func = __cmd_to_func ( args . action ) if not fiss_func : eprint ( "invalid FISS cmd '" + args . action + "'" ) return 1 r = fapi . get_entities ( args . project , args . workspace , "sample_set" ) fapi . _check_response_code ( r , 200 ) sample_sets = [ entity [ 'name' ] for entity in r . ...
Loop over all sample sets in a workspace performing a func
38,930
def monitor ( args ) : r = fapi . list_submissions ( args . project , args . workspace ) fapi . _check_response_code ( r , 200 ) statuses = sorted ( r . json ( ) , key = lambda k : k [ 'submissionDate' ] , reverse = True ) header = '\t' . join ( list ( statuses [ 0 ] . keys ( ) ) ) expander = lambda v : '{0}' . format ...
Retrieve status of jobs submitted from a given workspace as a list of TSV lines sorted by descending order of job submission date
38,931
def supervise ( args ) : project = args . project workspace = args . workspace namespace = args . namespace workflow = args . workflow sample_sets = args . sample_sets recovery_file = args . json_checkpoint if not sample_sets : r = fapi . get_entities ( args . project , args . workspace , "sample_set" ) fapi . _check_r...
Run legacy Firehose - style workflow of workflows
38,932
def entity_copy ( args ) : if not args . to_workspace : args . to_workspace = args . workspace if not args . to_project : args . to_project = args . project if ( args . project == args . to_project and args . workspace == args . to_workspace ) : eprint ( "destination project and namespace must differ from" " source wor...
Copy entities from one workspace to another .
38,933
def _validate_helper ( args , config_d , workspace_d , entity_d = None ) : invalid_inputs = sorted ( config_d [ "invalidInputs" ] ) invalid_outputs = sorted ( config_d [ "invalidOutputs" ] ) invalid_inputs = [ ( i , config_d [ 'methodConfiguration' ] [ 'inputs' ] [ i ] ) for i in invalid_inputs ] invalid_outputs = [ ( ...
Return FISSFC validation information on config for a certain entity
38,934
def _confirm_prompt ( message , prompt = "\nAre you sure? [y/yes (default: no)]: " , affirmations = ( "Y" , "Yes" , "yes" , "y" ) ) : answer = input ( message + prompt ) return answer in affirmations
Display a message then confirmation prompt and return true if the user responds with one of the affirmations .
38,935
def _nonempty_project ( string ) : value = str ( string ) if len ( value ) == 0 : msg = "No project provided and no default project configured" raise argparse . ArgumentTypeError ( msg ) return value
Argparse validator for ensuring a workspace is provided
38,936
def _entity_paginator ( namespace , workspace , etype , page_size = 500 , filter_terms = None , sort_direction = "asc" ) : page = 1 all_entities = [ ] r = fapi . get_entities_query ( namespace , workspace , etype , page = page , page_size = page_size , sort_direction = sort_direction , filter_terms = filter_terms ) fap...
Pages through the get_entities_query endpoint to get all entities in the workspace without crashing .
38,937
def __cmd_to_func ( cmd ) : fiss_module = sys . modules [ __name__ ] func = getattr ( fiss_module , cmd , None ) if func and not hasattr ( func , 'fiss_cmd' ) : func = None return func
Returns the function object in this module matching cmd .
38,938
def _valid_headerline ( l ) : if not l : return False headers = l . split ( '\t' ) first_col = headers [ 0 ] tsplit = first_col . split ( ':' ) if len ( tsplit ) != 2 : return False if tsplit [ 0 ] in ( 'entity' , 'update' ) : return tsplit [ 1 ] in ( 'participant_id' , 'participant_set_id' , 'sample_id' , 'sample_set_...
return true if the given string is a valid loadfile header
38,939
def _batch_load ( project , workspace , headerline , entity_data , chunk_size = 500 ) : if fcconfig . verbosity : print ( "Batching " + str ( len ( entity_data ) ) + " updates to Firecloud..." ) if not _valid_headerline ( headerline ) : eprint ( "Invalid loadfile header:\n" + headerline ) return 1 update_type = "member...
Submit a large number of entity updates in batches of chunk_size
38,940
def create_payload ( entities ) : types = { e . etype for e in entities } if len ( types ) != 1 : raise ValueError ( "Can't create payload with " + str ( len ( types ) ) + " types" ) all_attrs = set ( ) for e in entities : all_attrs . update ( set ( e . attrs . keys ( ) ) ) all_attrs = list ( all_attrs ) header = "enti...
Create a tsv payload describing entities .
38,941
def create_loadfile ( entities , f ) : with open ( f , 'w' ) as out : out . write ( Entity . create_payload ( entities ) )
Create payload and save to file .
38,942
def needs_gcloud ( self ) : gcloud_default_path = [ 'google-cloud-sdk' , 'bin' ] if platform . system ( ) != "Windows" : gcloud_default_path = os . path . join ( os . path . expanduser ( '~' ) , * gcloud_default_path ) else : gcloud_default_path = os . path . join ( os . environ [ 'LOCALAPPDATA' ] , 'Google' , 'Cloud S...
Returns true if gcloud is unavailable and needed for authentication .
38,943
def action ( arguments ) : for input_file in arguments . input_files : logging . info ( input_file ) with common . atomic_write ( input_file . name , file_factory = common . FileType ( 'wt' ) ) as tf : convert . transform_file ( input_file , tf , arguments ) if hasattr ( input_file , 'close' ) : input_file . close ( )
Run mogrify . Most of the action is in convert this just creates a temp file for the output .
38,944
def all_unambiguous ( sequence_str ) : result = [ [ ] ] for c in sequence_str : result = [ i + [ a ] for i in result for a in _AMBIGUOUS_MAP . get ( c , c ) ] return [ '' . join ( i ) for i in result ]
All unambiguous versions of sequence_str
38,945
def moving_average ( iterable , n ) : it = iter ( iterable ) d = collections . deque ( itertools . islice ( it , n - 1 ) ) d . appendleft ( 0 ) s = sum ( d ) for elem in it : s += elem - d . popleft ( ) d . append ( elem ) yield s / float ( n )
From Python collections module documentation
38,946
def parse_barcode_file ( fp , primer = None , header = False ) : tr = trie . trie ( ) reader = csv . reader ( fp ) if header : next ( reader ) records = ( record for record in reader if record ) for record in records : specimen , barcode = record [ : 2 ] if primer is not None : pr = primer else : pr = record [ 2 ] for ...
Load label barcode primer records from a CSV file .
38,947
def action ( arguments ) : if arguments . quality_window_mean_qual and not arguments . quality_window : raise ValueError ( "--quality-window-mean-qual specified without " "--quality-window" ) if trie is None or triefind is None : raise ValueError ( 'Missing Bio.trie and/or Bio.triefind modules. Cannot continue' ) filte...
Given parsed arguments filter input files .
38,948
def iterable_hook ( self , name , iterable ) : for record in iterable : self ( name , record ) yield record
Fire an event named name with each item in iterable
38,949
def _found_barcode ( self , record , sample , barcode = None ) : assert record . id == self . current_record [ 'sequence_name' ] self . current_record [ 'sample' ] = sample
Hook called when barcode is found
38,950
def filter_records ( self , records ) : for record in records : try : filtered = self . filter_record ( record ) assert ( filtered ) if filtered . seq == record . seq : self . passed_unchanged += 1 else : self . passed_changed += 1 yield filtered except FailedFilter as e : self . failed += 1 v = e . value if self . lis...
Apply the filter to records
38,951
def filter_record ( self , record ) : nloc = record . seq . find ( 'N' ) if nloc == - 1 : return record elif self . action == 'truncate' : return record [ : nloc ] elif self . action == 'drop' : raise FailedFilter ( ) else : assert False
Filter a record truncating or dropping at an N
38,952
def filter_record ( self , record ) : if len ( record ) >= self . min_length : return record else : raise FailedFilter ( len ( record ) )
Filter record dropping any that don t meet minimum length
38,953
def filter_record ( self , record ) : if len ( record ) >= self . max_length : return record [ : self . max_length ] else : return record
Filter record truncating any over some maximum length
38,954
def summarize_sequence_file ( source_file , file_type = None ) : is_alignment = True avg_length = None min_length = sys . maxsize max_length = 0 sequence_count = 0 with common . FileType ( 'rt' ) ( source_file ) as fp : if not file_type : file_type = fileformat . from_handle ( fp ) for record in SeqIO . parse ( fp , fi...
Summarizes a sequence file returning a tuple containing the name whether the file is an alignment minimum sequence length maximum sequence length average length number of sequences .
38,955
def _record_buffer ( records , buffer_size = DEFAULT_BUFFER_SIZE ) : with tempfile . SpooledTemporaryFile ( buffer_size , mode = 'wb+' ) as tf : pickler = pickle . Pickler ( tf ) for record in records : pickler . dump ( record ) def record_iter ( ) : tf . seek ( 0 ) unpickler = pickle . Unpickler ( tf ) while True : tr...
Buffer for transform functions which require multiple passes through data .
38,956
def dashes_cleanup ( records , prune_chars = '.:?~' ) : logging . info ( "Applying _dashes_cleanup: converting any of '{}' to '-'." . format ( prune_chars ) ) translation_table = { ord ( c ) : '-' for c in prune_chars } for record in records : record . seq = Seq ( str ( record . seq ) . translate ( translation_table ) ...
Take an alignment and convert any undesirable characters such as ? or ~ to - .
38,957
def deduplicate_sequences ( records , out_file ) : logging . info ( 'Applying _deduplicate_sequences generator: ' 'removing any duplicate records with identical sequences.' ) checksum_sequences = collections . defaultdict ( list ) for record in records : checksum = seguid ( record . seq ) sequences = checksum_sequences...
Remove any duplicate records with identical sequences keep the first instance seen and discard additional occurences .
38,958
def deduplicate_taxa ( records ) : logging . info ( 'Applying _deduplicate_taxa generator: ' + 'removing any duplicate records with identical IDs.' ) taxa = set ( ) for record in records : taxid = record . id if '|' in record . id : try : taxid = int ( record . id . split ( "|" ) [ 0 ] ) except : logging . warn ( "Unab...
Remove any duplicate records with identical IDs keep the first instance seen and discard additional occurences .
38,959
def first_name_capture ( records ) : logging . info ( 'Applying _first_name_capture generator: ' 'making sure ID only contains the first whitespace-delimited ' 'word.' ) whitespace = re . compile ( r'\s+' ) for record in records : if whitespace . search ( record . description ) : yield SeqRecord ( record . seq , id = r...
Take only the first whitespace - delimited word as the name of the sequence . Essentially removes any extra text from the sequence s description .
38,960
def include_from_file ( records , handle ) : ids = set ( i . strip ( ) for i in handle ) for record in records : if record . id . strip ( ) in ids : yield record
Filter the records keeping only sequences whose ID is contained in the handle .
38,961
def drop_columns ( records , slices ) : for record in records : drop = set ( i for slice in slices for i in range ( * slice . indices ( len ( record ) ) ) ) keep = [ i not in drop for i in range ( len ( record ) ) ] record . seq = Seq ( '' . join ( itertools . compress ( record . seq , keep ) ) , record . seq . alphabe...
Drop all columns present in slices from records
38,962
def cut_sequences_relative ( records , slices , record_id ) : with _record_buffer ( records ) as r : try : record = next ( i for i in r ( ) if i . id == record_id ) except StopIteration : raise ValueError ( "Record with id {0} not found." . format ( record_id ) ) new_slices = _update_slices ( record , slices ) for reco...
Cuts records to slices indexed by non - gap positions in record_id
38,963
def multi_mask_sequences ( records , slices ) : for record in records : record_indices = list ( range ( len ( record ) ) ) keep_indices = reduce ( lambda i , s : i - frozenset ( record_indices [ s ] ) , slices , frozenset ( record_indices ) ) seq = '' . join ( b if i in keep_indices else '-' for i , b in enumerate ( st...
Replace characters sliced by slices with gap characters .
38,964
def reverse_sequences ( records ) : logging . info ( 'Applying _reverse_sequences generator: ' 'reversing the order of sites in sequences.' ) for record in records : rev_record = SeqRecord ( record . seq [ : : - 1 ] , id = record . id , name = record . name , description = record . description ) _reverse_annotations ( ...
Reverse the order of sites in sequences .
38,965
def reverse_complement_sequences ( records ) : logging . info ( 'Applying _reverse_complement_sequences generator: ' 'transforming sequences into reverse complements.' ) for record in records : rev_record = SeqRecord ( record . seq . reverse_complement ( ) , id = record . id , name = record . name , description = recor...
Transform sequences into reverse complements .
38,966
def ungap_sequences ( records , gap_chars = GAP_TABLE ) : logging . info ( 'Applying _ungap_sequences generator: removing all gap characters' ) for record in records : yield ungap_all ( record , gap_chars )
Remove gaps from sequences given an alignment .
38,967
def _update_id ( record , new_id ) : old_id = record . id record . id = new_id record . description = re . sub ( '^' + re . escape ( old_id ) , new_id , record . description ) return record
Update a record id to new_id also modifying the ID in record . description
38,968
def name_append_suffix ( records , suffix ) : logging . info ( 'Applying _name_append_suffix generator: ' 'Appending suffix ' + suffix + ' to all ' 'sequence IDs.' ) for record in records : new_id = record . id + suffix _update_id ( record , new_id ) yield record
Given a set of sequences append a suffix for each sequence s name .
38,969
def name_insert_prefix ( records , prefix ) : logging . info ( 'Applying _name_insert_prefix generator: ' 'Inserting prefix ' + prefix + ' for all ' 'sequence IDs.' ) for record in records : new_id = prefix + record . id _update_id ( record , new_id ) yield record
Given a set of sequences insert a prefix for each sequence s name .
38,970
def name_include ( records , filter_regex ) : logging . info ( 'Applying _name_include generator: ' 'including only IDs matching ' + filter_regex + ' in results.' ) regex = re . compile ( filter_regex ) for record in records : if regex . search ( record . id ) or regex . search ( record . description ) : yield record
Given a set of sequences filter out any sequences with names that do not match the specified regular expression . Ignore case .
38,971
def name_replace ( records , search_regex , replace_pattern ) : regex = re . compile ( search_regex ) for record in records : maybe_id = record . description . split ( None , 1 ) [ 0 ] if maybe_id == record . id : record . description = regex . sub ( replace_pattern , record . description ) record . id = record . descr...
Given a set of sequences replace all occurrences of search_regex with replace_pattern . Ignore case .
38,972
def seq_include ( records , filter_regex ) : regex = re . compile ( filter_regex ) for record in records : if regex . search ( str ( record . seq ) ) : yield record
Filter any sequences who s seq does not match the filter . Ignore case .
38,973
def head ( records , head ) : logging . info ( 'Applying _head generator: ' 'limiting results to top ' + head + ' records.' ) if head == '-0' : for record in records : yield record elif '-' in head : with _record_buffer ( records ) as r : record_count = sum ( 1 for record in r ( ) ) end_index = max ( record_count + int...
Limit results to the top N records . With the leading - print all but the last N records .
38,974
def tail ( records , tail ) : logging . info ( 'Applying _tail generator: ' 'limiting results to top ' + tail + ' records.' ) if tail == '+0' : for record in records : yield record elif '+' in tail : tail = int ( tail ) - 1 for record in itertools . islice ( records , tail , None ) : yield record else : with _record_bu...
Limit results to the bottom N records . Use + N to output records starting with the Nth .
38,975
def gap_proportion ( sequences , gap_chars = '-' ) : aln_len = None gaps = [ ] for i , sequence in enumerate ( sequences ) : if aln_len is None : aln_len = len ( sequence ) gaps = [ 0 ] * aln_len else : if not len ( sequence ) == aln_len : raise ValueError ( ( "Unexpected sequence length {0}. Is this " "an alignment?" ...
Generates a list with the proportion of gaps by index in a set of sequences .
38,976
def squeeze ( records , gap_threshold = 1.0 ) : with _record_buffer ( records ) as r : gap_proportions = gap_proportion ( r ( ) ) keep_columns = [ g < gap_threshold for g in gap_proportions ] for record in r ( ) : sequence = str ( record . seq ) squeezed = itertools . compress ( sequence , keep_columns ) yield SeqRecor...
Remove any gaps that are present in the same position across all sequences in an alignment . Takes a second sequence iterator for determining gap positions .
38,977
def max_length_discard ( records , max_length ) : logging . info ( 'Applying _max_length_discard generator: ' 'discarding records longer than ' '.' ) for record in records : if len ( record ) > max_length : logging . debug ( 'Discarding long sequence: %s, length=%d' , record . id , len ( record ) ) else : yield record
Discard any records that are longer than max_length .
38,978
def min_length_discard ( records , min_length ) : logging . info ( 'Applying _min_length_discard generator: ' 'discarding records shorter than %d.' , min_length ) for record in records : if len ( record ) < min_length : logging . debug ( 'Discarding short sequence: %s, length=%d' , record . id , len ( record ) ) else :...
Discard any records that are shorter than min_length .
38,979
def min_ungap_length_discard ( records , min_length ) : for record in records : if len ( ungap_all ( record ) ) >= min_length : yield record
Discard any records that are shorter than min_length after removing gaps .
38,980
def batch ( iterable , chunk_size ) : i = iter ( iterable ) while True : r = list ( itertools . islice ( i , chunk_size ) ) if not r : break yield r
Return items from iterable in chunk_size bits .
38,981
def _validate_translation ( self , aligned_prot , aligned_nucl ) : codons = [ '' . join ( i ) for i in batch ( str ( aligned_nucl ) , 3 ) ] for codon , aa in zip ( codons , str ( aligned_prot ) ) : if codon == '---' and aa == '-' : continue try : trans = self . translation_table . forward_table [ codon ] if not trans =...
Given a seq for protein and nucleotide ensure that the translation holds
38,982
def map_all ( self , prot_alignment , nucl_sequences ) : zipped = itertools . zip_longest ( prot_alignment , nucl_sequences ) for p , n in zipped : if p is None : raise ValueError ( "Exhausted protein sequences" ) elif n is None : raise ValueError ( "Exhausted nucleotide sequences" ) yield self . map_alignment ( p , n ...
Convert protein sequences to nucleotide alignment
38,983
def from_extension ( extension ) : if not extension . startswith ( '.' ) : raise ValueError ( "Extensions must begin with a period." ) try : return EXTENSION_TO_TYPE [ extension . lower ( ) ] except KeyError : raise UnknownExtensionError ( "seqmagick does not know how to handle " + "files with extensions like this: " +...
Look up the BioPython file type corresponding with input extension .
38,984
def from_filename ( file_name ) : base , extension = os . path . splitext ( file_name ) if extension in COMPRESS_EXT : extension = os . path . splitext ( base ) [ 1 ] return from_extension ( extension )
Look up the BioPython file type corresponding to an input file name .
38,985
def from_handle ( fh , stream_default = 'fasta' ) : if fh in ( sys . stdin , sys . stdout , sys . stderr ) : return stream_default return from_filename ( fh . name )
Look up the BioPython file type corresponding to a file - like object .
38,986
def parse_arguments ( argv ) : parser = argparse . ArgumentParser ( description = 'seqmagick - Manipulate ' + ' sequence files.' , prog = 'seqmagick' ) parser . add_argument ( '-V' , '--version' , action = 'version' , version = 'seqmagick v' + version , help = "Print the version number and exit" ) parser . add_argument...
Extract command - line arguments for different actions .
38,987
def ungap_index_map ( sequence , gap_chars = '-' ) : counter = itertools . count ( 0 ) . __next__ ungap_indexes = [ counter ( ) if c not in gap_chars else None for c in iter ( sequence ) ] return dict ( ( ungapped , gapped ) for ungapped , gapped in zip ( ungap_indexes , range ( len ( sequence ) ) ) if ungapped is not ...
Returns a dict mapping from an index in the ungapped sequence to an index in the gapped sequence .
38,988
def _iupac_ambiguous_equal ( ambig_base , unambig_base ) : iupac_translation = { 'A' : 'A' , 'C' : 'C' , 'G' : 'G' , 'T' : 'T' , 'U' : 'U' , 'R' : 'AG' , 'Y' : 'CT' , 'S' : 'GC' , 'W' : 'AT' , 'K' : 'GT' , 'M' : 'AC' , 'B' : 'CGT' , 'D' : 'AGT' , 'H' : 'ACT' , 'V' : 'ACG' , 'N' : 'ACGT' , '-' : '-' } for i in ( ambig_b...
Tests two bases for equality accounting for IUPAC ambiguous DNA
38,989
def hamming_distance ( s1 , s2 , equality_function = operator . eq ) : if not len ( s1 ) == len ( s2 ) : raise ValueError ( "String lengths are not equal" ) return sum ( not equality_function ( c1 , c2 ) for c1 , c2 in zip ( s1 , s2 ) )
Returns the hamming distance between two strings .
38,990
def trim ( sequences , start , end ) : logging . info ( "Trimming from %d to %d" , start , end ) return ( sequence [ start : end ] for sequence in sequences )
Slice the input sequences from start to end
38,991
def action ( arguments ) : source_format = ( arguments . source_format or fileformat . from_handle ( arguments . source_file ) ) output_format = ( arguments . output_format or fileformat . from_handle ( arguments . output_file ) ) with arguments . source_file : sequences = SeqIO . parse ( arguments . source_file , sour...
Trim the alignment as specified
38,992
def hash_starts_numeric ( records ) : for record in records : seq_hash = hashlib . sha1 ( str ( record . seq ) ) . hexdigest ( ) if seq_hash [ 0 ] . isdigit ( ) : yield record
Very useful function that only accepts records with a numeric start to their sha - 1 hash .
38,993
def atomic_write ( path , mode = 'wt' , permissions = None , file_factory = None , ** kwargs ) : if permissions is None : permissions = apply_umask ( ) if path == '-' : yield sys . stdout else : base_dir = os . path . dirname ( path ) kwargs [ 'suffix' ] = os . path . basename ( path ) tf = tempfile . NamedTemporaryFil...
Open a file for atomic writing .
38,994
def typed_range ( type_func , minimum , maximum ) : @ functools . wraps ( type_func ) def inner ( string ) : result = type_func ( string ) if not result >= minimum and result <= maximum : raise argparse . ArgumentTypeError ( "Please provide a value between {0} and {1}" . format ( minimum , maximum ) ) return result ret...
Require variables to be of the specified type between minimum and maximum
38,995
def partial_append_action ( fn , argument_keys = None ) : if isinstance ( argument_keys , str ) : argument_keys = [ argument_keys ] argument_keys = argument_keys or [ ] class PartialAppendAction ( argparse . Action ) : def __init__ ( self , option_strings , dest , const = None , default = None , required = False , help...
Creates a new class extending argparse . Action which appends a partially - applied function to dest .
38,996
def positive_value ( target_type ) : def inner ( string ) : value = target_type ( string ) if not value >= 0 : raise argparse . ArgumentTypeError ( "Invalid positive number: " + string ) return value return inner
Wraps target_type in a function that requires the parsed argument be > = 0
38,997
def build_parser ( parser ) : add_options ( parser ) parser . add_argument ( 'source_file' , type = common . FileType ( 'rt' ) , help = "Input sequence file" ) parser . add_argument ( 'dest_file' , help = "Output file" ) return parser
Add shared arguments to the convert or mogrify parser .
38,998
def parse_fasta ( filepath ) : with open ( filepath , 'r' ) as f : seqs = [ ] header = '' for line in f : line = line . strip ( ) if line == '' : continue if line [ 0 ] == '>' : if header == '' : header = line . replace ( '>' , '' ) else : yield header , '' . join ( seqs ) seqs = [ ] header = line . replace ( '>' , '' ...
Parse a fasta file returning a generator yielding tuples of fasta headers to sequences .
38,999
def fasta_format_check ( fasta_path , logger ) : header_count = 0 line_count = 1 nt_count = 0 with open ( fasta_path ) as f : for l in f : l = l . strip ( ) if l == '' : continue if l [ 0 ] == '>' : header_count += 1 continue if header_count == 0 and l [ 0 ] != '>' : error_msg = 'First non-blank line (L:{line_count}) d...
Check that a file is valid FASTA format .