output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def participant_list(args): ''' List participants within a container''' # Case 1: retrieve participants within a named data entity if args.entity_type and args.entity: # Edge case: caller asked for participant within participant (itself) if args.entity_type == 'participant': ret...
Implement a function in Python 3 to list participants within a container
You are a Python code analyst, evaluating scripts for potential improvements.
def pair_list(args): ''' List pairs within a container. ''' # Case 1: retrieve pairs within a named data entity if args.entity_type and args.entity: # Edge case: caller asked for pair within a pair (itself) if args.entity_type == 'pair': return [ args.entity.strip() ] # ...
Write a Python 3 script to list the pairs within a container.
As a Python code translator, you convert algorithms and pseudocode into Python.
def sample_list(args): ''' List samples within a container. ''' # Case 1: retrieve samples within a named data entity if args.entity_type and args.entity: # Edge case: caller asked for samples within a sample (itself) if args.entity_type == 'sample': return [ args.entity.strip()...
Write a Python 3 script for listing samples within a container.
You are a Python code architect, reviewing and designing scalable and efficient code
Delete an entity in a workspace.
Can you generate a brief explanation for the following Python 3 code 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...
You are a Python code generator, capable of creating scripts from specifications.
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...
Can you implement a function in Python 3 that submits a new workflow to the methods repository.
You are a Python code analyst, evaluating scripts for potential improvements.
Remove a method from the method repository
Can you generate the documentation for the following Python 3 function def meth_delete(args): 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...
As a python code expert, you are capable of creating scripts from specifications.
Retrieve WDL for given version of a repository method
Explain what the following Python 3 code does 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
You are a Python code architect, reviewing and designing scalable and efficient code
Retrieve access control list for given version of a repository method
Can you generate a brief explanation for the following Python 3 code 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._ch...
As a Python code composer, you craft elegant and concise scripts.
Assign an ACL role to a list of users for a workflow.
Explain what the following Python 3 code does 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: # get the latest snapshot_id for ...
You are a Python code architect, reviewing and designing scalable and efficient code
Given a list of users return all members of the group.
Can you tell what is the following Python 3 function doing 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...
As a python code expert, you are capable of creating scripts from specifications.
List workflows in the methods repository
Can you generate a brief explanation for the following Python 3 code 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) # P...
You are a Python code architect, reviewing and designing scalable and efficient code
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...
Write a Python 3 script to invoke a task ( method configuration ) on given entity in given space
As a Python code translator, you convert algorithms and pseudocode into Python.
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, ...
Can you write a function in Python 3 where it aborts a task by submission ID in given space
You are a Python code architect, reviewing and designing scalable and efficient code
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 ...
Implement a function in Python 3 to list the method configs in the methods repository or a workspace.
You are a Python code architect, reviewing and designing scalable and efficient code
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']) ...
Implement a function in Python 3 to retrieve access control list for a method configuration
You are a Python code generator, capable of creating scripts from specifications.
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...
Can you create a Python 3 function that assigns an ACL role to a list of users for a config.
As a Python code translator, you convert algorithms and pseudocode into Python.
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...
Can you implement a function in Python 3 that retrieves a method config from a workspace send stdout
You are a Python code analyst, evaluating scripts for potential improvements.
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....
How would you code a function in Python 3 to retrieve the WDL for a method config in a workspace send stdout
You are a Python code analyst, evaluating scripts for potential improvements.
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...
Create a Python 3 function for comparing method configuration definitions across workspaces. Ignores methodConfigVersion if the verbose argument is not set
As a Python code translator, you convert algorithms and pseudocode into Python.
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...
Write a Python 3 script to install a valid method configuration into a workspace in one of several several ways.
You are a Python code architect, reviewing and designing scalable and efficient code
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...
Implement a function in Python 3 to install a new method config into a workspace.
As a python code expert, you are capable of creating scripts from specifications.
Remove a method config from a workspace
Explain what the following Python 3 code does 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
You are a Python code analyst, evaluating scripts for potential improvements.
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)...
Write a Python 3 function for copying a method config to a new name space or namespace
As a python code expert, you are capable of creating scripts from specifications.
Return a dict of attribute name - value pairs for a given entity type or workspace - level object.
Given the following Python 3 function, write the documentation 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 att...
As a Python code composer, you craft elegant and concise scripts.
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: ...
Create a Python 3 function to retrieve names of all attributes attached to a given object either an entity type + name or workspace
As a python code expert, you are capable of creating scripts from specifications.
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(...
Write a Python 3 script for setting key = value attributes for a single entity or a single workspace
As a Python code translator, you convert algorithms and pseudocode into Python.
Delete attributes from an entity in a workspace.
Make a summary of the following Python 3 code 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: # Sinc...
As a Python code translator, you convert algorithms and pseudocode into Python.
Copy workspace attributes between workspaces.
Given the following Python 3 function, write the documentation 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): ...
As a Python code composer, you craft elegant and concise scripts.
Assign the null sentinel value for all entities which do not have a value for all attributes.
Can you generate the documentation for the following Python 3 function def attr_fill_null(args): NULL_SENTINEL = "gs://broad-institute-gdac/GDAC_FC_NULL" attrs = args.attributes if not attrs: print("Error: provide at least one attribute to set") return 1 if 'participant' in attrs or 's...
As a Python code translator, you convert algorithms and pseudocode into Python.
Clean up unreferenced data in a workspace
Make a summary of the following Python 3 code 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._chec...
As a Python code translator, you convert algorithms and pseudocode into Python.
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...
How would you implement a function in Python 3 that loops over all sample sets in a workspace performing a func
You are a Python code analyst, evaluating scripts for potential improvements.
Retrieve status of jobs submitted from a given workspace as a list sorted by descending order of job submission date
Can you generate the documentation for the following Python 3 function 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_resp...
As a Python code composer, you craft elegant and concise scripts.
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...
Write a Python 3 function that can run legacy Firehose - style workflow of workflows
As a Python code translator, you convert algorithms and pseudocode into Python.
Copy entities from one workspace to another.
Explain what the following Python 3 code does 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("desti...
As a Python code composer, you craft elegant and concise scripts.
Retrieve the list of billing projects accessible to the caller and the caller s user and the level of access granted for each
Can you generate the documentation for the following Python 3 function 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_cod...
As a Python code analyst, you investigate and solve complex coding mysteries
Validate a workspace configuration
Explain what the following Python 3 code does 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.projec...
As a Python code analyst, you investigate and solve complex coding mysteries
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...
How would you implement a function in Python 3 that returns FISSFC validation information on config for a certain entity
As a python code expert, you are capable of creating scripts from specifications.
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 ...
How would you code a function in Python 3 to show me what can be run in a given workspace
As a Python code composer, you craft elegant and concise scripts.
Display a message and then return true if the user responds with one of the affirmations.
Can you generate the documentation for the following Python 3 function 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 ...
You are a Python code generator, capable of creating scripts from specifications.
Page through the get_entities_query endpoint to get all entities in a workspace without crashing.
Explain what the following Python 3 code does 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 ...
You are a Python code analyst, evaluating scripts for potential improvements.
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
Implement a function in Python 3 to return the function object in this module matching cmd.
You are a Python code analyst, evaluating scripts for potential improvements.
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...
Write a Python 3 script to return true if the given string is a valid loadfile header
As a Python code composer, you craft elegant and concise scripts.
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. "...
Write a Python 3 script for batching load a set of entity data into a single object
As a Python code analyst, you investigate and solve complex coding mysteries
Use this entry point to call HL fiss funcs as though from the UNIX CLI.
Make a summary of the following Python 3 code 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 = __prett...
As a Python code composer, you craft elegant and concise scripts.
Create a TSV payload describing the given list of entities.
Explain what the following Python 3 code does def create_payload(entities): #First check that all entities are of the same type types = {e.etype for e in entities} if len(types) != 1: raise ValueError("Can't create payload with " + str(len(types)) + " typ...
As a Python code composer, you craft elegant and concise scripts.
Create payload and save to file.
Make a summary of the following Python 3 code def create_loadfile(entities, f): with open(f, 'w') as out: out.write(Entity.create_payload(entities))
As a Python code translator, you convert algorithms and pseudocode into Python.
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('~'), ...
Implement a Python 3 function for returning true if gcloud is unavailable and needed for authentication.
As a Python code analyst, you investigate and solve complex coding mysteries
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...
Create a Python 3 function for running mogrify. Most of the action is in convert, this just creates a temp file for the output.
You are a Python code analyst, evaluating scripts for potential improvements.
Returns a list of all unambiguous versions of sequence_str.
Here you have a function in Python 3, explain what it does 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]
As a Python code analyst, you investigate and solve complex coding mysteries
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', ...
Create a Python 3 function to build a subparser for the command line
As a Python code composer, you craft elegant and concise scripts.
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) ...
Write a Python 3 function that can load label barcode primer records from a CSV file.
You are a Python code architect, reviewing and designing scalable and efficient code
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...
How would you code a function in Python 3 to give parsed arguments filter input files and return a new tree of BioXML objects.
As a Python code analyst, you investigate and solve complex coding mysteries
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
Implement a Python 3 function for firing an event named ``name`` with each item in iterable
As a Python code translator, you convert algorithms and pseudocode into Python.
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
Implement a function in Python 3 to hook called when barcode is found
As a Python code composer, you craft elegant and concise scripts.
Apply the filter to the records and yield the filtered records.
Explain what the following Python 3 code does def filter_records(self, records): for record in records: try: filtered = self.filter_record(record) assert (filtered) # Quick tracking whether the sequence was modified if filtered.seq == r...
You are a Python code architect, reviewing and designing scalable and efficient code
Filter a single record by the mean score.
Can you generate a brief explanation for the following Python 3 code def filter_record(self, record): quality_scores = record.letter_annotations['phred_quality'] mean_score = mean(quality_scores) if mean_score >= self.min_mean_score: return record else: raise Fai...
You are a Python code generator, capable of creating scripts from specifications.
Filter a single record by the minimum and acceptable mean score.
Given the following Python 3 function, write the documentation def filter_record(self, 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) ...
You are a Python code architect, reviewing and designing scalable and efficient code
Filter a record by truncating or dropping at an N
Explain what the following Python 3 code does 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: ...
You are a Python code architect, reviewing and designing scalable and efficient code
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))
How would you code a function in Python 3 to filter the record to only contain any that don t meet minimum length.
As a Python code composer, you craft elegant and concise scripts.
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
How would you code a function in Python 3 to filter the record to only contain the ones that are longer than self. max_length.
As a python code expert, you are capable of creating scripts from specifications.
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 ...
Implement a Python 3 function for summarizing 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.
As a python code expert, you are capable of creating scripts from specifications.
This function is called by the command line interface to determine if the file is an alignment or tab - delimited.
Here you have a function in Python 3, explain what it does def action(arguments): # Ignore SIGPIPE, for head support common.exit_on_sigpipe() common.exit_on_sigint() handle = arguments.destination_file output_format = arguments.output_format if not output_format: try: output...
You are a Python code architect, reviewing and designing scalable and efficient code
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+')...
Write a Python 3 function for buffering for transform functions which require multiple passes through data.
You are a Python code analyst, evaluating scripts for potential improvements.
Take an alignment and convert any undesirable characters such as? or ~ to -.
How would you explain what the following Python 3 function does 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....
As a python code expert, you are capable of creating scripts from specifications.
Remove any duplicate records with identical sequences keep the first Portal instance seen and discard additional occurences.
How would you explain what the following Python 3 function does 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...
As a Python code composer, you craft elegant and concise scripts.
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() ...
Implement a Python 3 function for removing any duplicate records with identical IDs keep the first duplicate record seen and discard additional occurences.
As a Python code composer, you craft elegant and concise scripts.
Yields SeqRecords that contain only the first whitespace - delimited word as the name of the sequence.
How would you explain what the following Python 3 function does 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 rec...
You are a Python code architect, reviewing and designing scalable and efficient code
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
Write a Python 3 script to filter the records keeping only sequences whose ID is contained in the handle.
You are a Python code generator, capable of creating scripts from specifications.
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: ...
How would you code a function in Python 3 to yield sequences from the given start and end indices.
You are a Python code analyst, evaluating scripts for potential improvements.
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...
How would you code a function in Python 3 to drop all columns present in slices from records
As a Python code composer, you craft elegant and concise scripts.
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...
Implement a Python 3 function for cutting records to slices indexed by non - gap positions in record_id
As a python code expert, you are capable of creating scripts from specifications.
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...
How would you implement a function in Python 3 that masks sequences in a list of records by the given slices.
As a Python code composer, you craft elegant and concise scripts.
Remove any empty sequences from the sequence list.
How would you explain what the following Python 3 function does def prune_empty(records): for record in records: if not all(c == '-' for c in str(record.seq)): yield record
You are a Python code architect, reviewing and designing scalable and efficient code
Reverse the annotations of the old_record to the new_record.
How would you explain what the following Python 3 function does def _reverse_annotations(old_record, new_record): # Copy the annotations over for k, v in list(old_record.annotations.items()): # Trim if appropriate if isinstance(v, (tuple, list)) and len(v) == len(old_record): assert ...
As a Python code analyst, you investigate and solve complex coding mysteries
Reverse the order of sites in sequences.
Explain what the following Python 3 code does 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, ...
You are a Python code generator, capable of creating scripts from specifications.
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...
Can you create a Python 3 function that transforms sequences into reverse complements.
You are a Python code architect, reviewing and designing scalable and efficient code
Remove gaps from sequences given an alignment.
Explain what the following Python 3 code does 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)
You are a Python code analyst, evaluating scripts for potential improvements.
Update a record ID to new_id
How would you explain what the following Python 3 function does def _update_id(record, new_id): 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) return record
As a python code expert, you are capable of creating scripts from specifications.
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...
How would you implement a function in Python 3 that gives a set of sequences append a suffix for each sequence s name.
As a Python code translator, you convert algorithms and pseudocode into Python.
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...
How would you code a function in Python 3 to give a set of sequences insert a prefix for each sequence s name.
As a Python code composer, you craft elegant and concise scripts.
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 + ...
Can you write a function in Python 3 where it gives a set of sequences and a regular expression filter out any sequences with names that do not match the regular expression.
You are a Python code architect, reviewing and designing scalable and efficient code
Given a set of sequences replace all occurrences of search_regex with replace_pattern. Ignore case.
Make a summary of the following Python 3 code 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, re...
As a Python code composer, you craft elegant and concise scripts.
Filter any sequences who s seq does not match the filter_regex. Ignore case.
Given the following Python 3 function, write the documentation def seq_include(records, filter_regex): regex = re.compile(filter_regex) for record in records: if regex.search(str(record.seq)): yield record
As a Python code translator, you convert algorithms and pseudocode into Python.
Choose a length - k subset of records retaining the input order.
Can you generate a brief explanation for the following Python 3 code def sample(records, k, random_seed=None): if random_seed is not None: random.seed(random_seed) result = [] for i, record in enumerate(records): if len(result) < k: result.append(record) else: ...
As a Python code translator, you convert algorithms and pseudocode into Python.
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...
Create a Python 3 function to yield the records from the specified head.
You are a Python code analyst, evaluating scripts for potential improvements.
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...
Implement a Python 3 function for yielding the records from the top N records.
You are a Python code architect, reviewing and designing scalable and efficient code
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...
How would you code a function in Python 3 to generate a list with the proportion of gaps by index in a set of sequences.
You are a Python code architect, reviewing and designing scalable and efficient code
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()) ...
Can you create a Python 3 function that takes a sequence iterator for determining gap between all sequences AttributeNames and trims any gaps that are present in the same position across all sequences AttributeNames.
As a Python code analyst, you investigate and solve complex coding mysteries
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...
Write a Python 3 function that can give a list of SeqRecords yield SeqRecords that are in the order they appear in the ID.
You are a Python code generator, capable of creating scripts from specifications.
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...
Create a Python 3 function for yielding the records in the sequence that are transcribed by the transcribe operation.
As a Python code composer, you craft elegant and concise scripts.
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...
Write a Python 3 script for translating a list of records into a sequence sequence.
As a Python code composer, you craft elegant and concise scripts.
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: ...
Implement a Python 3 function for discarding any records that are longer than max_length.
You are a Python code architect, reviewing and designing scalable and efficient code
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: ...
Create a Python 3 function to discard any records that are shorter than min_length.
As a Python code analyst, you investigate and solve complex coding mysteries
Discard any records that are shorter than min_length after removing gaps.
How would you explain what the following Python 3 function does def min_ungap_length_discard(records, min_length): for record in records: if len(ungap_all(record)) >= min_length: yield record
You are a Python code architect, reviewing and designing scalable and efficient code
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...
Implement a function in Python 3 to sort sequences by length.
You are a Python code generator, capable of creating scripts from specifications.
Yields items from iterable in chunk_size bits.
Here you have a function in Python 3, explain what it does def batch(iterable, chunk_size): i = iter(iterable) while True: r = list(itertools.islice(i, chunk_size)) if not r: break yield r
As a python code expert, you are capable of creating scripts from specifications.
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...
Create a Python 3 function to run the alignment of a single sequence.
As a python code expert, you are capable of creating scripts from specifications.
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 ...
Create a Python 3 function for validating that the translation table is valid for the given protein and nucleotide.
You are a Python code architect, reviewing and designing scalable and efficient code
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...
Can you write a function in Python 3 where it maps alignment to the original sequence.
You are a Python code architect, reviewing and designing scalable and efficient code
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"...
How would you implement a function in Python 3 that maps all sequences in the protein alignment to nucleotide sequences.
You are a Python code architect, reviewing and designing scalable and efficient code