sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def entity_delete(args): """ Delete entity in a workspace. """ 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, ...
Delete entity in a workspace.
entailment
def meth_new(args): """ Submit a new workflow (or update) to the methods repository. """ r = fapi.update_repository_method(args.namespace, args.method, args.synopsis, args.wdl, args.doc, args.comment) fapi._check_response_code(r, 20...
Submit a new workflow (or update) to the methods repository.
entailment
def meth_delete(args): """ Remove (redact) a method from the method repository """ message = "WARNING: this will delete workflow \n\t{0}/{1}:{2}".format( args.namespace, args.method, args.snapshot_id) if not args.yes and not _confirm_prompt(message): return r...
Remove (redact) a method from the method repository
entailment
def meth_wdl(args): ''' Retrieve WDL for given version of a repository method''' 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
entailment
def meth_acl(args): ''' Retrieve access control list for given version of a repository method''' 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...
Retrieve access control list for given version of a repository method
entailment
def meth_set_acl(args): """ Assign an ACL role to a list of users for a workflow. """ 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: # get the lat...
Assign an ACL role to a list of users for a workflow.
entailment
def expand_fc_groups(users): """ If user is a firecloud group, return all members of the group. Caveat is that only group admins may do this. """ groups = None for user in users: fcgroup = None if '@' not in user: fcgroup = user elif user.lower().endswith('@firecl...
If user is a firecloud group, return all members of the group. Caveat is that only group admins may do this.
entailment
def meth_list(args): """ List workflows in the methods repository """ r = fapi.list_repository_methods(namespace=args.namespace, name=args.method, snapshotId=args.snapshot_id) fapi._check_response_code(r, 200) # Parse the JSON fo...
List workflows in the methods repository
entailment
def config_start(args): '''Invoke a task (method configuration), on given entity in given space''' # Try to use call caching (job avoidance)? Flexibly accept range of answers cache = getattr(args, "cache", True) cache = cache is True or (cache.lower() in ["y", "true", "yes", "t", "1"]) if not arg...
Invoke a task (method configuration), on given entity in given space
entailment
def config_stop(args): '''Abort a task (method configuration) by submission ID in given space''' r = fapi.abort_submission(args.project, args.workspace, args.submission_id) fapi._check_response_code(r, 204) return ("Aborted {0} in {1}/{2}".format(args.submission_id, ...
Abort a task (method configuration) by submission ID in given space
entailment
def config_list(args): """ List configuration(s) in the methods repository or a workspace. """ verbose = fcconfig.verbosity if args.workspace: if verbose: print("Retrieving method configs from space {0}".format(args.workspace)) if not args.project: eprint("No project ...
List configuration(s) in the methods repository or a workspace.
entailment
def config_acl(args): ''' Retrieve access control list for a method configuration''' 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']) ...
Retrieve access control list for a method configuration
entailment
def config_set_acl(args): """ Assign an ACL role to a list of users for a config. """ 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: # get the lat...
Assign an ACL role to a list of users for a config.
entailment
def config_get(args): """ Retrieve a method config from a workspace, send stdout """ r = fapi.get_workspace_config(args.project, args.workspace, args.namespace, args.config) fapi._check_response_code(r, 200) # Setting ensure_ascii to False ensures unicode string r...
Retrieve a method config from a workspace, send stdout
entailment
def config_wdl(args): """ Retrieve the WDL for a method config in a workspace, send stdout """ r = fapi.get_workspace_config(args.project, args.workspace, args.namespace, args.config) fapi._check_response_code(r, 200) method = r.json()["methodRepoMethod"] args....
Retrieve the WDL for a method config in a workspace, send stdout
entailment
def config_diff(args): """Compare method configuration definitions across workspaces. Ignores methodConfigVersion if the verbose argument is not set""" config_1 = config_get(args).splitlines() args.project = args.Project args.workspace = args.Workspace cfg_1_name = args.config if args.Con...
Compare method configuration definitions across workspaces. Ignores methodConfigVersion if the verbose argument is not set
entailment
def config_put(args): '''Install a valid method configuration into a workspace, in one of several ways: from a JSON file containing a config definition (both file names and objects are supported); as a string representing the content of such a JSON file; or as a dict generated from such JSON co...
Install a valid method configuration into a workspace, in one of several ways: from a JSON file containing a config definition (both file names and objects are supported); as a string representing the content of such a JSON file; or as a dict generated from such JSON content, e.g via json.lo...
entailment
def config_new(args): '''Attempt to install a new method config into a workspace, by: generating a template from a versioned method in the methods repo, then launching a local editor (respecting the $EDITOR environment variable) to fill in the incomplete input/output fields. Returns True if th...
Attempt to install a new method config into a workspace, by: generating a template from a versioned method in the methods repo, then launching a local editor (respecting the $EDITOR environment variable) to fill in the incomplete input/output fields. Returns True if the config was successfu...
entailment
def config_delete(args): """ Remove a method config from a workspace """ 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
entailment
def config_copy(args): """ Copy a method config to new name/space/namespace/project (or all 4) """ if not (args.tospace or args.toname or args.toproject or args.tonamespace): raise RuntimeError('A new config name OR workspace OR project OR ' + 'namespace must be given (or all)...
Copy a method config to new name/space/namespace/project (or all 4)
entailment
def attr_get(args): '''Return a dict of attribute name/value pairs: if entity name & type are specified then attributes will be retrieved from that entity, otherwise workspace-level attributes will be returned. By default all attributes attached to the given object will be returned, but a subset ca...
Return a dict of attribute name/value pairs: if entity name & type are specified then attributes will be retrieved from that entity, otherwise workspace-level attributes will be returned. By default all attributes attached to the given object will be returned, but a subset can be selected by specifying...
entailment
def attr_list(args): '''Retrieve names of all attributes attached to a given object, either an entity (if entity type+name is provided) or workspace (if not)''' args.attributes = None result = attr_get(args) names = result.get("__header__",[]) if names: names = names[1:] else: ...
Retrieve names of all attributes attached to a given object, either an entity (if entity type+name is provided) or workspace (if not)
entailment
def attr_set(args): ''' Set key=value attributes: if entity name & type are specified then attributes will be set upon that entity, otherwise the attribute will be set at the workspace level''' if args.entity_type and args.entity: prompt = "Set {0}={1} for {2}:{3} in {4}/{5}?\n[Y\\n]: ".format(...
Set key=value attributes: if entity name & type are specified then attributes will be set upon that entity, otherwise the attribute will be set at the workspace level
entailment
def attr_delete(args): ''' Delete key=value attributes: if entity name & type are specified then attributes will be deleted from that entity, otherwise the attribute will be removed from the workspace''' if args.entity_type and args.entities: # Since there is no attribute deletion endpoint, we ...
Delete key=value attributes: if entity name & type are specified then attributes will be deleted from that entity, otherwise the attribute will be removed from the workspace
entailment
def attr_copy(args): """ Copy workspace attributes between workspaces. """ 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): epr...
Copy workspace attributes between workspaces.
entailment
def attr_fill_null(args): """ Assign the null sentinel value for all entities which do not have a value for the given attributes. see gs://broad-institute-gdac/GDAC_FC_NULL for more details """ NULL_SENTINEL = "gs://broad-institute-gdac/GDAC_FC_NULL" attrs = args.attributes if not attr...
Assign the null sentinel value for all entities which do not have a value for the given attributes. see gs://broad-institute-gdac/GDAC_FC_NULL for more details
entailment
def health(args): """ Health FireCloud Server """ r = fapi.health() fapi._check_response_code(r, 200) return r.content
Health FireCloud Server
entailment
def mop(args): ''' Clean up unreferenced data in a workspace''' # First retrieve the workspace to get bucket information if args.verbose: print("Retrieving workspace information...") r = fapi.get_workspace(args.project, args.workspace) fapi._check_response_code(r, 200) workspace = r.json...
Clean up unreferenced data in a workspace
entailment
def sset_loop(args): ''' Loop over all sample sets in a workspace, performing a func ''' # Ensure that the requested action is a valid fiss_cmd fiss_func = __cmd_to_func(args.action) if not fiss_func: eprint("invalid FISS cmd '" + args.action + "'") return 1 # First get the sample s...
Loop over all sample sets in a workspace, performing a func
entailment
def monitor(args): ''' Retrieve status of jobs submitted from a given workspace, as a list of TSV lines sorted by descending order of job submission date''' r = fapi.list_submissions(args.project, args.workspace) fapi._check_response_code(r, 200) statuses = sorted(r.json(), key=lambda k: k['subm...
Retrieve status of jobs submitted from a given workspace, as a list of TSV lines sorted by descending order of job submission date
entailment
def supervise(args): ''' Run legacy, Firehose-style workflow of workflows''' project = args.project workspace = args.workspace namespace = args.namespace workflow = args.workflow sample_sets = args.sample_sets recovery_file = args.json_checkpoint # If no sample sets are provided, run on...
Run legacy, Firehose-style workflow of workflows
entailment
def entity_copy(args): """ Copy entities from one workspace to another. """ 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): ep...
Copy entities from one workspace to another.
entailment
def proj_list(args): '''Retrieve the list of billing projects accessible to the caller/user, and show the level of access granted for each (e.g. Owner, User, ...)''' projects = fapi.list_billing_projects() fapi._check_response_code(projects, 200) projects = sorted(projects.json(), key=lambda d: d...
Retrieve the list of billing projects accessible to the caller/user, and show the level of access granted for each (e.g. Owner, User, ...)
entailment
def config_validate(args): ''' Validate a workspace configuration: if an entity was specified (i.e. upon which the configuration should operate), then also validate that the entity has the necessary attributes''' r = fapi.validate_config(args.project, args.workspace, args.namespace, ...
Validate a workspace configuration: if an entity was specified (i.e. upon which the configuration should operate), then also validate that the entity has the necessary attributes
entailment
def _validate_helper(args, config_d, workspace_d, entity_d=None): """ Return FISSFC validation information on config for a certain entity """ # 4 ways to have invalid config: invalid_inputs = sorted(config_d["invalidInputs"]) invalid_outputs = sorted(config_d["invalidOutputs"]) # Also insert va...
Return FISSFC validation information on config for a certain entity
entailment
def runnable(args): """ Show me what can be run in a given workspace """ w = fapi.get_workspace(args.project, args.workspace) fapi._check_response_code(w, 200) workspace_d = w.json() if args.config and args.namespace and not args.entity: # See what entities I can run on with this config ...
Show me what can be run in a given workspace
entailment
def _confirm_prompt(message, prompt="\nAre you sure? [y/yes (default: no)]: ", affirmations=("Y", "Yes", "yes", "y")): """ Display a message, then confirmation prompt, and return true if the user responds with one of the affirmations. """ answer = input(message + prompt) retu...
Display a message, then confirmation prompt, and return true if the user responds with one of the affirmations.
entailment
def _nonempty_project(string): """ Argparse validator for ensuring a workspace is provided """ 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
entailment
def _entity_paginator(namespace, workspace, etype, page_size=500, filter_terms=None, sort_direction="asc"): """Pages through the get_entities_query endpoint to get all entities in the workspace without crashing. """ page = 1 all_entities = [] # Make initial reques...
Pages through the get_entities_query endpoint to get all entities in the workspace without crashing.
entailment
def __cmd_to_func(cmd): """ Returns the function object in this module matching cmd. """ fiss_module = sys.modules[__name__] # Returns None if string is not a recognized FISS command 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.
entailment
def _valid_headerline(l): """return true if the given string is a valid loadfile header""" 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'): re...
return true if the given string is a valid loadfile header
entailment
def _batch_load(project, workspace, headerline, entity_data, chunk_size=500): """ Submit a large number of entity updates in batches of chunk_size """ if fcconfig.verbosity: print("Batching " + str(len(entity_data)) + " updates to Firecloud...") # Parse the entity type from the first cell, e.g. "...
Submit a large number of entity updates in batches of chunk_size
entailment
def main_as_cli(argv=None): '''Use this entry point to call HL fiss funcs as though from the UNIX CLI. (see firecloud/tests/highlevel_tests.py:call_cli for usage examples)''' try: result = main(argv) except Exception as e: result = __pretty_print_fc_exception(e) # FIXME: we should...
Use this entry point to call HL fiss funcs as though from the UNIX CLI. (see firecloud/tests/highlevel_tests.py:call_cli for usage examples)
entailment
def create_payload(entities): """Create a tsv payload describing entities. A TSV payload consists of 1 header row describing entity type and attribute names. Each subsequent line is an entity_id followed by attribute values separated by the tab "\\t" character. This payload can ...
Create a tsv payload describing entities. A TSV payload consists of 1 header row describing entity type and attribute names. Each subsequent line is an entity_id followed by attribute values separated by the tab "\\t" character. This payload can be uploaded to the workspace via ...
entailment
def create_loadfile(entities, f): """Create payload and save to file.""" with open(f, 'w') as out: out.write(Entity.create_payload(entities))
Create payload and save to file.
entailment
def needs_gcloud(self): """Returns true if gcloud is unavailable and needed for authentication.""" gcloud_default_path = ['google-cloud-sdk', 'bin'] if platform.system() != "Windows": gcloud_default_path = os.path.join(os.path.expanduser('~'), ...
Returns true if gcloud is unavailable and needed for authentication.
entailment
def action(arguments): """ Run mogrify. Most of the action is in convert, this just creates a temp file for the output. """ for input_file in arguments.input_files: logging.info(input_file) # Generate a temporary file with common.atomic_write( input_file.name...
Run mogrify. Most of the action is in convert, this just creates a temp file for the output.
entailment
def all_unambiguous(sequence_str): """ All unambiguous versions of 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
entailment
def build_parser(parser): """ Generate a subparser """ parser.add_argument( 'sequence_file', type=FileType('r'), help="""Input fastq file. A fasta-format file may also be provided if --input-qual is also specified.""") parser.add_argument( '--input-qual', ...
Generate a subparser
entailment
def moving_average(iterable, n): """ From Python collections module documentation moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0 """ it = iter(iterable) d = collections.deque(itertools.islice(it, n - 1)) d.appendleft(0) s = sum(d) for elem in it: s += elem ...
From Python collections module documentation moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0
entailment
def parse_barcode_file(fp, primer=None, header=False): """ Load label, barcode, primer records from a CSV file. Returns a map from barcode -> label Any additional columns are ignored """ tr = trie.trie() reader = csv.reader(fp) if header: # Skip header next(reader) ...
Load label, barcode, primer records from a CSV file. Returns a map from barcode -> label Any additional columns are ignored
entailment
def action(arguments): """ Given parsed arguments, filter input files. """ 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 Non...
Given parsed arguments, filter input files.
entailment
def iterable_hook(self, name, iterable): """ Fire an event named ``name`` with each item in iterable """ for record in iterable: self(name, record) yield record
Fire an event named ``name`` with each item in iterable
entailment
def _found_barcode(self, record, sample, barcode=None): """Hook called when barcode is found""" assert record.id == self.current_record['sequence_name'] self.current_record['sample'] = sample
Hook called when barcode is found
entailment
def filter_records(self, records): """ Apply the filter to records """ for record in records: try: filtered = self.filter_record(record) assert (filtered) # Quick tracking whether the sequence was modified if fil...
Apply the filter to records
entailment
def filter_record(self, record): """ Filter a single record """ quality_scores = record.letter_annotations['phred_quality'] mean_score = mean(quality_scores) if mean_score >= self.min_mean_score: return record else: raise FailedFilter(mean...
Filter a single record
entailment
def filter_record(self, record): """ Filter a single record """ quality_scores = record.letter_annotations['phred_quality'] # Simple case - window covers whole sequence if len(record) <= self.window_size: mean_score = mean(quality_scores) if mean_...
Filter a single record
entailment
def filter_record(self, record): """ Filter a record, truncating or dropping at an 'N' """ nloc = record.seq.find('N') if nloc == -1: return record elif self.action == 'truncate': return record[:nloc] elif self.action == 'drop': ...
Filter a record, truncating or dropping at an 'N'
entailment
def filter_record(self, record): """ Filter record, dropping any that don't meet minimum length """ if len(record) >= self.min_length: return record else: raise FailedFilter(len(record))
Filter record, dropping any that don't meet minimum length
entailment
def filter_record(self, record): """ Filter record, truncating any over some maximum length """ if len(record) >= self.max_length: return record[:self.max_length] else: return record
Filter record, truncating any over some maximum length
entailment
def summarize_sequence_file(source_file, file_type=None): """ 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. """ is_alignment = True avg_length = None ...
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.
entailment
def action(arguments): """ Given one more more sequence files, determine if the file is an alignment, the maximum sequence length and the total number of sequences. Provides different output formats including tab (tab-delimited), csv and align (aligned as if part of a borderless table). """ ...
Given one more more sequence files, determine if the file is an alignment, the maximum sequence length and the total number of sequences. Provides different output formats including tab (tab-delimited), csv and align (aligned as if part of a borderless table).
entailment
def _record_buffer(records, buffer_size=DEFAULT_BUFFER_SIZE): """ Buffer for transform functions which require multiple passes through data. Value returned by context manager is a function which returns an iterator through records. """ with tempfile.SpooledTemporaryFile(buffer_size, mode='wb+')...
Buffer for transform functions which require multiple passes through data. Value returned by context manager is a function which returns an iterator through records.
entailment
def dashes_cleanup(records, prune_chars='.:?~'): """ Take an alignment and convert any undesirable characters such as ? or ~ to -. """ logging.info( "Applying _dashes_cleanup: converting any of '{}' to '-'.".format(prune_chars)) translation_table = {ord(c): '-' for c in prune_chars} ...
Take an alignment and convert any undesirable characters such as ? or ~ to -.
entailment
def deduplicate_sequences(records, out_file): """ Remove any duplicate records with identical sequences, keep the first instance seen and discard additional occurences. """ logging.info('Applying _deduplicate_sequences generator: ' 'removing any duplicate records with identical seq...
Remove any duplicate records with identical sequences, keep the first instance seen and discard additional occurences.
entailment
def deduplicate_taxa(records): """ Remove any duplicate records with identical IDs, keep the first instance seen and discard additional occurences. """ logging.info('Applying _deduplicate_taxa generator: ' + \ 'removing any duplicate records with identical IDs.') taxa = set() ...
Remove any duplicate records with identical IDs, keep the first instance seen and discard additional occurences.
entailment
def first_name_capture(records): """ Take only the first whitespace-delimited word as the name of the sequence. Essentially removes any extra text from the sequence's description. """ logging.info('Applying _first_name_capture generator: ' 'making sure ID only contains the first whi...
Take only the first whitespace-delimited word as the name of the sequence. Essentially removes any extra text from the sequence's description.
entailment
def include_from_file(records, handle): """ Filter the records, keeping only sequences whose ID is contained in the 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.
entailment
def isolate_region(sequences, start, end, gap_char='-'): """ Replace regions before and after start:end with gap chars """ # Check arguments if end <= start: raise ValueError("start of slice must precede end ({0} !> {1})".format( end, start)) for sequence in sequences: ...
Replace regions before and after start:end with gap chars
entailment
def drop_columns(records, slices): """ Drop all columns present in ``slices`` from records """ for record in records: # Generate a set of indices to remove drop = set(i for slice in slices for i in range(*slice.indices(len(record)))) keep = [i not in drop for i...
Drop all columns present in ``slices`` from records
entailment
def cut_sequences_relative(records, slices, record_id): """ Cuts records to slices, indexed by non-gap positions in 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("Rec...
Cuts records to slices, indexed by non-gap positions in record_id
entailment
def multi_mask_sequences(records, slices): """ Replace characters sliced by slices with gap characters. """ for record in records: record_indices = list(range(len(record))) keep_indices = reduce(lambda i, s: i - frozenset(record_indices[s]), slices, frozense...
Replace characters sliced by slices with gap characters.
entailment
def prune_empty(records): """ Remove any sequences which are entirely gaps ('-') """ for record in records: if not all(c == '-' for c in str(record.seq)): yield record
Remove any sequences which are entirely gaps ('-')
entailment
def _reverse_annotations(old_record, new_record): """ Copy annotations form old_record to new_record, reversing any lists / tuples / strings. """ # Copy the annotations over for k, v in list(old_record.annotations.items()): # Trim if appropriate if isinstance(v, (tuple, list)) an...
Copy annotations form old_record to new_record, reversing any lists / tuples / strings.
entailment
def reverse_sequences(records): """ Reverse the order of sites in sequences. """ 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, ...
Reverse the order of sites in sequences.
entailment
def reverse_complement_sequences(records): """ Transform sequences into reverse complements. """ logging.info('Applying _reverse_complement_sequences generator: ' 'transforming sequences into reverse complements.') for record in records: rev_record = SeqRecord(record.seq.rev...
Transform sequences into reverse complements.
entailment
def ungap_sequences(records, gap_chars=GAP_TABLE): """ Remove gaps from sequences, given an alignment. """ 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.
entailment
def _update_id(record, new_id): """ Update a record id to new_id, also modifying the ID in record.description """ old_id = record.id record.id = new_id # At least for FASTA, record ID starts the description record.description = re.sub('^' + re.escape(old_id), new_id, record.description) ...
Update a record id to new_id, also modifying the ID in record.description
entailment
def name_append_suffix(records, suffix): """ Given a set of sequences, append a suffix for each sequence's name. """ logging.info('Applying _name_append_suffix generator: ' 'Appending suffix ' + suffix + ' to all ' 'sequence IDs.') for record in records: new...
Given a set of sequences, append a suffix for each sequence's name.
entailment
def name_insert_prefix(records, prefix): """ Given a set of sequences, insert a prefix for each sequence's name. """ logging.info('Applying _name_insert_prefix generator: ' 'Inserting prefix ' + prefix + ' for all ' 'sequence IDs.') for record in records: ne...
Given a set of sequences, insert a prefix for each sequence's name.
entailment
def name_include(records, filter_regex): """ Given a set of sequences, filter out any sequences with names that do not match the specified regular expression. Ignore case. """ logging.info('Applying _name_include generator: ' 'including only IDs matching ' + filter_regex + ...
Given a set of sequences, filter out any sequences with names that do not match the specified regular expression. Ignore case.
entailment
def name_replace(records, search_regex, replace_pattern): """ Given a set of sequences, replace all occurrences of search_regex with replace_pattern. Ignore case. If the ID and the first word of the description match, assume the description is FASTA-like and apply the transform to the entire de...
Given a set of sequences, replace all occurrences of search_regex with replace_pattern. Ignore case. If the ID and the first word of the description match, assume the description is FASTA-like and apply the transform to the entire description, then set the ID from the first word. If the ID and the ...
entailment
def seq_include(records, filter_regex): """ Filter any sequences who's seq does not match the filter. Ignore case. """ 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.
entailment
def sample(records, k, random_seed=None): """Choose a length-``k`` subset of ``records``, retaining the input order. If k > len(records), all are returned. If an integer ``random_seed`` is provided, sets ``random.seed()`` """ if random_seed is not None: random.seed(random_seed) resul...
Choose a length-``k`` subset of ``records``, retaining the input order. If k > len(records), all are returned. If an integer ``random_seed`` is provided, sets ``random.seed()``
entailment
def head(records, head): """ Limit results to the top N records. With the leading `-', print all but the last N records. """ logging.info('Applying _head generator: ' 'limiting results to top ' + head + ' records.') if head == '-0': for record in records: yi...
Limit results to the top N records. With the leading `-', print all but the last N records.
entailment
def tail(records, tail): """ Limit results to the bottom N records. Use +N to output records starting with the Nth. """ logging.info('Applying _tail generator: ' 'limiting results to top ' + tail + ' records.') if tail == '+0': for record in records: yield r...
Limit results to the bottom N records. Use +N to output records starting with the Nth.
entailment
def gap_proportion(sequences, gap_chars='-'): """ Generates a list with the proportion of gaps by index in a set of sequences. """ aln_len = None gaps = [] for i, sequence in enumerate(sequences): if aln_len is None: aln_len = len(sequence) gaps = [0] * aln_le...
Generates a list with the proportion of gaps by index in a set of sequences.
entailment
def squeeze(records, gap_threshold=1.0): """ 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. """ with _record_buffer(records) as r: gap_proportions = gap_proportion(r()) ...
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.
entailment
def strip_range(records): """ Cut off trailing /<start>-<stop> ranges from IDs. Ranges must be 1-indexed and the stop integer must not be less than the start integer. """ logging.info('Applying _strip_range generator: ' 'removing /<start>-<stop> ranges from IDs') # Split up and...
Cut off trailing /<start>-<stop> ranges from IDs. Ranges must be 1-indexed and the stop integer must not be less than the start integer.
entailment
def transcribe(records, transcribe): """ Perform transcription or back-transcription. transcribe must be one of the following: dna2rna rna2dna """ logging.info('Applying _transcribe generator: ' 'operation to perform is ' + transcribe + '.') for record in records...
Perform transcription or back-transcription. transcribe must be one of the following: dna2rna rna2dna
entailment
def translate(records, translate): """ Perform translation from generic DNA/RNA to proteins. Bio.Seq does not perform back-translation because the codons would more-or-less be arbitrary. Option to translate only up until reaching a stop codon. translate must be one of the following: dna2p...
Perform translation from generic DNA/RNA to proteins. Bio.Seq does not perform back-translation because the codons would more-or-less be arbitrary. Option to translate only up until reaching a stop codon. translate must be one of the following: dna2protein dna2proteinstop rna2prot...
entailment
def max_length_discard(records, max_length): """ Discard any records that are longer than max_length. """ logging.info('Applying _max_length_discard generator: ' 'discarding records longer than ' '.') for record in records: if len(record) > max_length: ...
Discard any records that are longer than max_length.
entailment
def min_length_discard(records, min_length): """ Discard any records that are shorter than 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: ...
Discard any records that are shorter than min_length.
entailment
def min_ungap_length_discard(records, min_length): """ Discard any records that are shorter than min_length after removing gaps. """ 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.
entailment
def sort_length(source_file, source_file_type, direction=1): """ Sort sequences by length. 1 is ascending (default) and 0 is descending. """ direction_text = 'ascending' if direction == 1 else 'descending' logging.info('Indexing sequences by length: %s', direction_text) # Adapted from the Biop...
Sort sequences by length. 1 is ascending (default) and 0 is descending.
entailment
def batch(iterable, chunk_size): """ Return items from iterable in chunk_size bits. If len(iterable) % chunk_size > 0, the last item returned will be shorter. """ 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. If len(iterable) % chunk_size > 0, the last item returned will be shorter.
entailment
def action(arguments): """ Run """ # Ignore SIGPIPE, for head support common.exit_on_sigpipe() logging.basicConfig() prot_sequences = SeqIO.parse(arguments.protein_align, fileformat.from_handle(arguments.protein_align)) nucl_sequences = SeqIO.parse(argum...
Run
entailment
def _validate_translation(self, aligned_prot, aligned_nucl): """ Given a seq for protein and nucleotide, ensure that the translation holds """ codons = [''.join(i) for i in batch(str(aligned_nucl), 3)] for codon, aa in zip(codons, str(aligned_prot)): # Check gaps ...
Given a seq for protein and nucleotide, ensure that the translation holds
entailment
def map_alignment(self, prot_seq, nucl_seq): """ Use aligned prot_seq to align nucl_seq """ if prot_seq.id != nucl_seq.id: logging.warning( 'ID mismatch: %s != %s. Are the sequences in the same order?', prot_seq.id, nucl_seq.id) # Unga...
Use aligned prot_seq to align nucl_seq
entailment
def map_all(self, prot_alignment, nucl_sequences): """ Convert protein sequences to nucleotide alignment """ zipped = itertools.zip_longest(prot_alignment, nucl_sequences) for p, n in zipped: if p is None: raise ValueError("Exhausted protein sequences"...
Convert protein sequences to nucleotide alignment
entailment