text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_byte_data(self, i2c_addr, register, force=None): """ Read a single byte from a designated register. :param i2c_addr: i2c address :type i2c_addr: int :param register: Register to read :type register: int :param force: :type force: Boolean :return: Read byte value :rtype: int """
self._set_address(i2c_addr, force=force) msg = i2c_smbus_ioctl_data.create( read_write=I2C_SMBUS_READ, command=register, size=I2C_SMBUS_BYTE_DATA ) ioctl(self.fd, I2C_SMBUS, msg) return msg.data.contents.byte
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_byte_data(self, i2c_addr, register, value, force=None): """ Write a byte to a given register. :param i2c_addr: i2c address :type i2c_addr: int :param register: Register to write to :type register: int :param value: Byte value to transmit :type value: int :param force: :type force: Boolean :rtype: None """
self._set_address(i2c_addr, force=force) msg = i2c_smbus_ioctl_data.create( read_write=I2C_SMBUS_WRITE, command=register, size=I2C_SMBUS_BYTE_DATA ) msg.data.contents.byte = value ioctl(self.fd, I2C_SMBUS, msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_call(self, i2c_addr, register, value, force=None): """ Executes a SMBus Process Call, sending a 16-bit value and receiving a 16-bit response :param i2c_addr: i2c address :type i2c_addr: int :param register: Register to read/write to :type register: int :param value: Word value to transmit :type value: int :param force: :type force: Boolean :rtype: int """
self._set_address(i2c_addr, force=force) msg = i2c_smbus_ioctl_data.create( read_write=I2C_SMBUS_WRITE, command=register, size=I2C_SMBUS_PROC_CALL ) msg.data.contents.word = value ioctl(self.fd, I2C_SMBUS, msg) return msg.data.contents.word
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_block_data(self, i2c_addr, register, force=None): """ Read a block of up to 32-bytes from a given register. :param i2c_addr: i2c address :type i2c_addr: int :param register: Start register :type register: int :param force: :type force: Boolean :return: List of bytes :rtype: list """
self._set_address(i2c_addr, force=force) msg = i2c_smbus_ioctl_data.create( read_write=I2C_SMBUS_READ, command=register, size=I2C_SMBUS_BLOCK_DATA ) ioctl(self.fd, I2C_SMBUS, msg) length = msg.data.contents.block[0] return msg.data.contents.block[1:length + 1]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_block_data(self, i2c_addr, register, data, force=None): """ Write a block of byte data to a given register. :param i2c_addr: i2c address :type i2c_addr: int :param register: Start register :type register: int :param data: List of bytes :type data: list :param force: :type force: Boolean :rtype: None """
length = len(data) if length > I2C_SMBUS_BLOCK_MAX: raise ValueError("Data length cannot exceed %d bytes" % I2C_SMBUS_BLOCK_MAX) self._set_address(i2c_addr, force=force) msg = i2c_smbus_ioctl_data.create( read_write=I2C_SMBUS_WRITE, command=register, size=I2C_SMBUS_BLOCK_DATA ) msg.data.contents.block[0] = length msg.data.contents.block[1:length + 1] = data ioctl(self.fd, I2C_SMBUS, msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_i2c_block_data(self, i2c_addr, register, length, force=None): """ Read a block of byte data from a given register. :param i2c_addr: i2c address :type i2c_addr: int :param register: Start register :type register: int :param length: Desired block length :type length: int :param force: :type force: Boolean :return: List of bytes :rtype: list """
if length > I2C_SMBUS_BLOCK_MAX: raise ValueError("Desired block length over %d bytes" % I2C_SMBUS_BLOCK_MAX) self._set_address(i2c_addr, force=force) msg = i2c_smbus_ioctl_data.create( read_write=I2C_SMBUS_READ, command=register, size=I2C_SMBUS_I2C_BLOCK_DATA ) msg.data.contents.byte = length ioctl(self.fd, I2C_SMBUS, msg) return msg.data.contents.block[1:length + 1]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def max_dimension(cellmap, sheet = None): """ This function calculates the maximum dimension of the workbook or optionally the worksheet. It returns a tupple of two integers, the first being the rows and the second being the columns. :param cellmap: all the cells that should be used to calculate the maximum. :param sheet: (optionally) a string with the sheet name. :return: a tupple of two integers, the first being the rows and the second being the columns. """
cells = list(cellmap.values()) rows = 0 cols = 0 for cell in cells: if sheet is None or cell.sheet == sheet: rows = max(rows, int(cell.row)) cols = max(cols, int(col2num(cell.col))) return (rows, cols)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _cast_number(value): # source: https://bitbucket.org/openpyxl/openpyxl/src/93604327bce7aac5e8270674579af76d390e09c0/openpyxl/cell/read_only.py?at=default&fileviewer=file-view-default "Convert numbers as string to an int or float" m = FLOAT_REGEX.search(value) if m is not None: return float(value) return int(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_rels(archive): """Read relationships for a workbook"""
xml_source = archive.read(ARC_WORKBOOK_RELS) tree = fromstring(xml_source) for element in safe_iterator(tree, '{%s}Relationship' % PKG_REL_NS): rId = element.get('Id') pth = element.get("Target") typ = element.get('Type') # normalise path if pth.startswith("/xl"): pth = pth.replace("/xl", "xl") elif not pth.startswith("xl") and not pth.startswith(".."): pth = "xl/" + pth yield rId, {'path':pth, 'type':typ}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_content_types(archive): """Read content types."""
xml_source = archive.read(ARC_CONTENT_TYPES) root = fromstring(xml_source) contents_root = root.findall('{%s}Override' % CONTYPES_NS) for type in contents_root: yield type.get('ContentType'), type.get('PartName')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_sheets(archive): """Read worksheet titles and ids for a workbook"""
xml_source = archive.read(ARC_WORKBOOK) tree = fromstring(xml_source) for element in safe_iterator(tree, '{%s}sheet' % SHEET_MAIN_NS): attrib = element.attrib attrib['id'] = attrib["{%s}id" % REL_NS] del attrib["{%s}id" % REL_NS] if attrib['id']: yield attrib
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def detect_worksheets(archive): """Return a list of worksheets"""
# content types has a list of paths but no titles # workbook has a list of titles and relIds but no paths # workbook_rels has a list of relIds and paths but no titles # rels = {'id':{'title':'', 'path':''} } content_types = read_content_types(archive) valid_sheets = dict((path, ct) for ct, path in content_types if ct == WORKSHEET_TYPE) rels = dict(read_rels(archive)) for sheet in read_sheets(archive): rel = rels[sheet['id']] rel['title'] = sheet['name'] rel['sheet_id'] = sheet['sheetId'] rel['state'] = sheet.get('state', 'visible') if ("/" + rel['path'] in valid_sheets or "worksheets" in rel['path']): # fallback in case content type is missing yield rel
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_string_table(xml_source): """Read in all shared strings in the table"""
strings = [] src = _get_xml_iter(xml_source) for _, node in iterparse(src): if node.tag == '{%s}si' % SHEET_MAIN_NS: text = Text.from_tree(node).content text = text.replace('x005F_', '') strings.append(text) node.clear() return IndexedList(strings)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_node(t, ref = None, debug = False): """Simple factory function"""
if t.ttype == "operand": if t.tsubtype in ["range", "named_range", "pointer"] : # print 'Creating Node', t.tvalue, t.tsubtype return RangeNode(t, ref, debug = debug) else: return OperandNode(t) elif t.ttype == "function": return FunctionNode(t, ref, debug = debug) elif t.ttype.startswith("operator"): return OperatorNode(t, ref, debug = debug) else: return ASTNode(t, debug = debug)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_ast(expression, debug = False): """build an AST from an Excel formula expression in reverse polish notation"""
#use a directed graph to store the tree G = DiGraph() stack = [] for n in expression: # Since the graph does not maintain the order of adding nodes/edges # add an extra attribute 'pos' so we can always sort to the correct order if isinstance(n,OperatorNode): if n.ttype == "operator-infix": arg2 = stack.pop() arg1 = stack.pop() # Hack to write the name of sheet in 2argument address if(n.tvalue == ':'): if '!' in arg1.tvalue and arg2.ttype == 'operand' and '!' not in arg2.tvalue: arg2.tvalue = arg1.tvalue.split('!')[0] + '!' + arg2.tvalue G.add_node(arg1,pos = 1) G.add_node(arg2,pos = 2) G.add_edge(arg1, n) G.add_edge(arg2, n) else: arg1 = stack.pop() G.add_node(arg1,pos = 1) G.add_edge(arg1, n) elif isinstance(n,FunctionNode): args = [] for _ in range(n.num_args): try: args.append(stack.pop()) except: raise Exception() #try: # args = [stack.pop() for _ in range(n.num_args)] #except: # print 'STACK', stack, type(n) # raise Exception('prut') args.reverse() for i,a in enumerate(args): G.add_node(a,pos = i) G.add_edge(a,n) else: G.add_node(n,pos=0) stack.append(n) return G,stack.pop()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cell2code(cell, named_ranges): """Generate python code for the given cell"""
if cell.formula: debug = False # if 'OFFSET' in cell.formula or 'INDEX' in cell.formula: # debug = True # if debug: # print 'FORMULA', cell.formula ref = parse_cell_address(cell.address()) if not cell.is_named_range else None sheet = cell.sheet e = shunting_yard(cell.formula, named_ranges, ref=ref, tokenize_range = False) ast,root = build_ast(e, debug = debug) code = root.emit(ast, context=sheet) # print 'CODE', code, ref else: ast = None if isinstance(cell.value, unicode): code = u'u"' + cell.value.replace(u'"', u'\\"') + u'"' elif isinstance(cell.value, str): raise RuntimeError("Got unexpected non-unicode str") else: code = str(cell.value) return code,ast
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def examine(self): """ Called by LiveReloadHandler's poll_tasks method. If a boolean true value is returned, then the waiters (browsers) are reloaded. """
if self._changes: return self._changes.pop() action_file = None if self._changed: self._changed = False action_file = self._action_file or True # TODO: Hack (see above) return action_file, None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def watch(self, path, action, *args, **kwargs): """ Called by the Server instance when a new watch task is requested. """
if action is None: action = _set_changed event_handler = _WatchdogHandler(self, action) self._observer.schedule(event_handler, path=path, recursive=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authors(): """ Updates the AUTHORS file with a list of committers from GIT. """
fmt_re = re.compile(r'([^<]+) <([^>]+)>') authors = local('git shortlog -s -e -n | cut -f 2-', capture=True) with open('AUTHORS', 'w') as fh: fh.write('Project contributors\n') fh.write('====================\n\n') for line in authors.splitlines(): match = fmt_re.match(line) name, email = match.groups() if email in env.ignored_authors: continue fh.write(' * ') fh.write(line) fh.write('\n')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def release(): """ Create a new release and upload it to PyPI. """
if not is_working_tree_clean(): print('Your working tree is not clean. Refusing to create a release.') return print('Rebuilding the AUTHORS file to check for modifications...') authors() if not is_working_tree_clean(): print('Your working tree is not clean after the AUTHORS file was ' 'rebuilt.') print('Please commit the changes before continuing.') return if not is_manifest_up_to_date(): print('Manifest is not up to date.') print('Please update MANIFEST.in or remove spurious files.') return # Get version version = 'v{}'.format(local('python setup.py --version', capture=True)) name = local('python setup.py --name', capture=True) # Tag tag_message = '{} release version {}.'.format(name, version) print('----------------------') print('Proceeding will tag the release, push the repository upstream,') print('and release a new version on PyPI.') print() print('Version: {}'.format(version)) print('Tag message: {}'.format(tag_message)) print() if not confirm('Continue?', default=True): print('Aborting.') return local('git tag -a {} -m {}'.format(pipes.quote(version), pipes.quote(tag_message))) # Push local('git push --tags origin develop') # Package and upload to pypi local('python setup.py sdist bdist_wheel upload')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insert(self, iterable, index=0, data=None, weight=1.0): """Insert new node into tree Args: iterable(hashable): key used to find in the future. data(object): data associated with the key index(int): an index used for insertion. weight(float): the wait given for the item added. """
if index == len(iterable): self.is_terminal = True self.key = iterable self.weight = weight if data: self.data.add(data) else: if iterable[index] not in self.children: self.children[iterable[index]] = TrieNode() self.children[iterable[index]].insert(iterable, index + 1, data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove(self, iterable, data=None, index=0): """Remove an element from the trie Args iterable(hashable): key used to find what is to be removed data(object): data associated with the key index(int): index of what is to me removed Returns: bool: True: if it was removed False: if it was not removed """
if index == len(iterable): if self.is_terminal: if data: self.data.remove(data) if len(self.data) == 0: self.is_terminal = False else: self.data.clear() self.is_terminal = False return True else: return False elif iterable[index] in self.children: return self.children[iterable[index]].remove(iterable, index=index+1, data=data) else: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gather(self, iterable): """Calls the lookup with gather True Passing iterable and yields the result. """
for result in self.lookup(iterable, gather=True): yield result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lookup(self, iterable, gather=False): """Call the lookup on the root node with the given parameters. Args iterable(index or key): Used to retrive nodes from tree gather(bool): this is passed down to the root node lookup Notes: max_edit_distance and match_threshold come from the init """
for result in self.root.lookup(iterable, gather=gather, edit_distance=0, max_edit_distance=self.max_edit_distance, match_threshold=self.match_threshold): yield result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insert(self, iterable, data=None, weight=1.0): """Used to insert into he root node Args iterable(hashable): index or key used to identify data(object): data to be paired with the key """
self.root.insert(iterable, index=0, data=data, weight=1.0)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove(self, iterable, data=None): """Used to remove from the root node Args: iterable(hashable): index or key used to identify item to remove data: data to be paired with the key """
return self.root.remove(iterable, data=data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bronk(r, p, x, graph): """This is used to fine cliques and remove them from graph Args: graph (graph): this is the graph of verticies to search for cliques p (list): this is a list of the verticies to search r (list): used by bronk for the search x (list): used by bronk for the search Yields: list : found clique of the given graph and verticies """
if len(p) == 0 and len(x) == 0: yield r return for vertex in p[:]: r_new = r[::] r_new.append(vertex) p_new = [val for val in p if val in graph.get_neighbors_of(vertex)] # p intersects N(vertex) x_new = [val for val in x if val in graph.get_neighbors_of(vertex)] # x intersects N(vertex) for result in bronk(r_new, p_new, x_new, graph): yield result p.remove(vertex) x.append(vertex)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def graph_key_from_tag(tag, entity_index): """Returns a key from a tag entity Args: tag (tag) : this is the tag selected to get the key from entity_index (int) : this is the index of the tagged entity Returns: str : String representing the key for the given tagged entity. """
start_token = tag.get('start_token') entity = tag.get('entities', [])[entity_index] return str(start_token) + '-' + entity.get('key') + '-' + str(entity.get('confidence'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_edge(self, a, b): """Used to add edges to the graph. 'a' and 'b' are vertexes and if 'a' or 'b' doesn't exisit then the vertex is created Args: a (hash): is one vertex of the edge b (hash): is another vertext of the edge """
neighbors_of_a = self.adjacency_lists.get(a) if not neighbors_of_a: neighbors_of_a = set() self.adjacency_lists[a] = neighbors_of_a neighbors_of_a.add(b) neighbors_of_b = self.adjacency_lists.get(b) if not neighbors_of_b: neighbors_of_b = set() self.adjacency_lists[b] = neighbors_of_b neighbors_of_b.add(a)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append(self, data): """Appends items or lists to the Lattice Args: data (item,list) : The Item or List to be added to the Lattice """
if isinstance(data, list) and len(data) > 0: self.nodes.append(data) else: self.nodes.append([data])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def traverse(self, index=0): """ This is used to produce a list of lists where each each item in that list is a diffrent combination of items from the lists within with every combination of such values. Args: index (int) : the index at witch to start the list. Note this is used only in the function as a processing Returns: list : is every combination. """
if index < len(self.nodes): for entity in self.nodes[index]: for next_result in self.traverse(index=index+1): if isinstance(entity, list): yield entity + next_result else: yield [entity] + next_result else: yield []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _build_graph(self, tags): """Builds a graph from the entities included in the tags. Note this is used internally. Args: tags (list): A list of the tags to include in graph Returns: graph : this is the resulting graph of the tagged entities. """
graph = SimpleGraph() for tag_index in xrange(len(tags)): for entity_index in xrange(len(tags[tag_index].get('entities'))): a_entity_name = graph_key_from_tag(tags[tag_index], entity_index) tokens = self.tokenizer.tokenize(tags[tag_index].get('entities', [])[entity_index].get('match')) for tag in tags[tag_index + 1:]: start_token = tag.get('start_token') if start_token >= tags[tag_index].get('start_token') + len(tokens): for b_entity_index in xrange(len(tag.get('entities'))): b_entity_name = graph_key_from_tag(tag, b_entity_index) graph.add_edge(a_entity_name, b_entity_name) return graph
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _sub_expand(self, tags): """This called by expand to find cliques Args: tags (list): a list of the tags used to get cliques Yields: list : list of sorted tags by start_token this is a clique """
entities = {} graph = self._build_graph(tags) # name entities for tag in tags: for entity_index in xrange(len(tag.get('entities'))): node_name = graph_key_from_tag(tag, entity_index) if not node_name in entities: entities[node_name] = [] entities[node_name] += [ tag.get('entities', [])[entity_index], tag.get('entities', [])[entity_index].get('confidence'), tag ] for clique in get_cliques(list(entities), graph): result = [] for entity_name in clique: start_token = int(entity_name.split("-")[0]) old_tag = entities[entity_name][2] tag = { 'start_token': start_token, 'entities': [entities.get(entity_name)[0]], 'confidence': entities.get(entity_name)[1] * old_tag.get('confidence', 1.0), 'end_token': old_tag.get('end_token'), 'match': old_tag.get('entities')[0].get('match'), 'key': old_tag.get('entities')[0].get('key'), 'from_context': old_tag.get('from_context', False) } result.append(tag) result = sorted(result, key=lambda e: e.get('start_token')) yield result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expand(self, tags, clique_scoring_func=None): """This is the main function to expand tags into cliques Args: tags (list): a list of tags to find the cliques. clique_scoring_func (func): a function that returns a float value for the clique Returns: list : a list of cliques """
lattice = Lattice() overlapping_spans = [] def end_token_index(): return max([t.get('end_token') for t in overlapping_spans]) for i in xrange(len(tags)): tag = tags[i] if len(overlapping_spans) > 0 and end_token_index() >= tag.get('start_token'): overlapping_spans.append(tag) elif len(overlapping_spans) > 1: cliques = list(self._sub_expand(overlapping_spans)) if clique_scoring_func: cliques = sorted(cliques, key=lambda e: -1 * clique_scoring_func(e)) lattice.append(cliques) overlapping_spans = [tag] else: lattice.append(overlapping_spans) overlapping_spans = [tag] if len(overlapping_spans) > 1: cliques = list(self._sub_expand(overlapping_spans)) if clique_scoring_func: cliques = sorted(cliques, key=lambda e: -1 * clique_scoring_func(e)) lattice.append(cliques) else: lattice.append(overlapping_spans) return lattice.traverse()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _iterate_subsequences(self, tokens): """ Using regex invokes this function, which significantly impacts performance of adapt. it is an N! operation. Args: tokens(list): list of tokens for Yield results. Yields: str: ? """
for start_idx in xrange(len(tokens)): for end_idx in xrange(start_idx + 1, len(tokens) + 1): yield ' '.join(tokens[start_idx:end_idx]), start_idx
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __best_intent(self, parse_result, context=[]): """ Decide the best intent Args: parse_result(list): results used to match the best intent. context(list): ? Returns: best_intent, best_tags: best_intent : The best intent for given results best_tags : The Tags for result """
best_intent = None best_tags = None context_as_entities = [{'entities': [c]} for c in context] for intent in self.intent_parsers: i, tags = intent.validate_with_tags(parse_result.get('tags') + context_as_entities, parse_result.get('confidence')) if not best_intent or (i and i.get('confidence') > best_intent.get('confidence')): best_intent = i best_tags = tags return best_intent, best_tags
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __get_unused_context(self, parse_result, context): """ Used to get unused context from context. Any keys not in parse_result Args: parse_results(list): parsed results used to identify what keys in the context are used. context(list): this is the context used to match with parsed results keys missing in the parsed results are the unused context Returns: list: A list of the unused context results. """
tags_keys = set([t['key'] for t in parse_result['tags'] if t['from_context']]) result_context = [c for c in context if c['key'] not in tags_keys] return result_context
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_entity(self, entity_value, entity_type, alias_of=None): """ Register an entity to be tagged in potential parse results Args: entity_value(str): the value/proper name of an entity instance (Ex: "The Big Bang Theory") entity_type(str): the type/tag of an entity instance (Ex: "Television Show") """
if alias_of: self.trie.insert(entity_value.lower(), data=(alias_of, entity_type)) else: self.trie.insert(entity_value.lower(), data=(entity_value, entity_type)) self.trie.insert(entity_type.lower(), data=(entity_type, 'Concept'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_intent_parser(self, intent_parser): """ "Enforce" the intent parser interface at registration time. Args: intent_parser(intent): Intent to be registered. Raises: ValueError: on invalid intent """
if hasattr(intent_parser, 'validate') and callable(intent_parser.validate): self.intent_parsers.append(intent_parser) else: raise ValueError("%s is not an intent parser" % str(intent_parser))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tokenizer(self): """ A property to link into IntentEngine's tokenizer. Warning: this is only for backwards compatiblility and should not be used if you intend on using domains. Return: the domains tokenizer from its IntentEngine """
domain = 0 if domain not in self.domains: self.register_domain(domain=domain) return self.domains[domain].tokenizer
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def trie(self): """ A property to link into IntentEngine's trie. warning:: this is only for backwards compatiblility and should not be used if you intend on using domains. Return: the domains trie from its IntentEngine """
domain = 0 if domain not in self.domains: self.register_domain(domain=domain) return self.domains[domain].trie
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _regex_strings(self): """ A property to link into IntentEngine's _regex_strings. Warning: this is only for backwards compatiblility and should not be used if you intend on using domains. Returns: the domains _regex_strings from its IntentEngine """
domain = 0 if domain not in self.domains: self.register_domain(domain=domain) return self.domains[domain]._regex_strings
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def regular_expressions_entities(self): """ A property to link into IntentEngine's regular_expressions_entities. Warning: this is only for backwards compatiblility and should not be used if you intend on using domains. Returns: the domains regular_expression_entities from its IntentEngine """
domain = 0 if domain not in self.domains: self.register_domain(domain=domain) return self.domains[domain].regular_expressions_entities
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_domain(self, domain=0, tokenizer=None, trie=None): """ Register a domain with the intent engine. Args: tokenizer(tokenizer): The tokenizer you wish to use. trie(Trie): the Trie() you wish to use. domain(str): a string representing the domain you wish to add """
self.domains[domain] = IntentDeterminationEngine( tokenizer=tokenizer, trie=trie)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_entity(self, entity_value, entity_type, alias_of=None, domain=0): """ Register an entity to be tagged in potential parse results. Args: entity_value(str): the value/proper name of an entity instance (Ex: "The Big Bang Theory") entity_type(str): the type/tag of an entity instance (Ex: "Television Show") domain(str): a string representing the domain you wish to add the entity to """
if domain not in self.domains: self.register_domain(domain=domain) self.domains[domain].register_entity(entity_value=entity_value, entity_type=entity_type, alias_of=alias_of)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_intent_parser(self, intent_parser, domain=0): """ Register a intent parser with a domain. Args: intent_parser(intent): The intent parser you wish to register. domain(str): a string representing the domain you wish register the intent parser to. """
if domain not in self.domains: self.register_domain(domain=domain) self.domains[domain].register_intent_parser( intent_parser=intent_parser)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tokenize(self, string): """Used to parce a string into tokens This function is to take in a string and return a list of tokens Args: string(str): This is a string of words or a sentance to be parsed into tokens Returns: list: a list of tokens from the string passed in. Notes: Doesn't seem to parse contractions correctly for example don't would parse as two tokens 'do' and "n't" and this seems to be not what we would want. Maybe should be "don't" or maybe contractions should be expanded into "do not" or "do","not". This could be done with a contraction dictionary and some preprocessing. """
s = string s = re.sub('\t', " ", s) s = re.sub("(" + regex_separator + ")", " \g<1> ", s) s = re.sub("([^0-9]),", "\g<1> , ", s) s = re.sub(",([^0-9])", " , \g<1>", s) s = re.sub("^(')", "\g<1> ", s) s = re.sub("(" + regex_not_letter_number + ")'", "\g<1> '", s) s = re.sub("(" + regex_clitics + ")$", " \g<1>", s) s = re.sub("(" + regex_clitics + ")(" + regex_not_letter_number + ")", " \g<1> \g<2>", s) words = s.strip().split() p1 = re.compile(".*" + regex_letter_number + "\\.") p2 = re.compile("^([A-Za-z]\\.([A-Za-z]\\.)+|[A-Z][bcdfghj-nptvxz]+\\.)$") token_list = [] for word in words: m1 = p1.match(word) m2 = p2.match(word) if m1 and word not in abbreviations_list and not m2: token_list.append(word[0: word.find('.')]) token_list.append(word[word.find('.')]) else: token_list.append(word) return token_list
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(self, utterance, context=None, N=1): """Used to find tags within utterance with a given confidence Args: utterance(str): conversational piece given by the user context(list): a list of entities N(int): number of results Returns: yield an object with the following fields utterance(str): the value passed in tags(list) : a list of tags found in utterance time(time) : duration since call of function confidence(float) : float indicating how confident of a match to the utterance. This might be used to determan the most likely intent. """
start = time.time() context_trie = None if context and isinstance(context, list): # sort by confidence in ascending order, so # highest confidence for an entity is last. # see comment on TrieNode ctor context.sort(key=lambda x: x.get('confidence')) context_trie = Trie() for entity in context: entity_value, entity_type = entity.get('data')[0] context_trie.insert(entity_value.lower(), data=(entity_value, entity_type), weight=entity.get('confidence')) tagged = self._tagger.tag(utterance.lower(), context_trie=context_trie) self.emit("tagged_entities", { 'utterance': utterance, 'tags': list(tagged), 'time': time.time() - start }) start = time.time() bke = BronKerboschExpander(self._tokenizer) def score_clique(clique): score = 0.0 for tagged_entity in clique: ec = tagged_entity.get('entities', [{'confidence': 0.0}])[0].get('confidence') score += ec * len(tagged_entity.get('entities', [{'match': ''}])[0].get('match')) / ( len(utterance) + 1) return score parse_results = bke.expand(tagged, clique_scoring_func=score_clique) count = 0 for result in parse_results: count += 1 parse_confidence = 0.0 for tag in result: sample_entity = tag['entities'][0] entity_confidence = sample_entity.get('confidence', 0.0) * float( len(sample_entity.get('match'))) / len(utterance) parse_confidence += entity_confidence yield { 'utterance': utterance, 'tags': result, 'time': time.time() - start, 'confidence': parse_confidence } if count >= N: break
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def metadata_matches(self, query={}): """ Returns key matches to metadata This will check every key in query for a matching key in metadata returning true if every key is in metadata. query without keys return false. Args: query(object): metadata for matching Returns: bool: True: when key count in query is > 0 and all keys in query in self.metadata False: if key count in query is <= 0 or any key in query not found in self.metadata """
result = len(query.keys()) > 0 for key in query.keys(): result = result and query[key] == self.metadata.get(key) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge_context(self, tag, metadata): """ merge into contextManagerFrame new entity and metadata. Appends tag as new entity and adds keys in metadata to keys in self.metadata. Args: tag(str): entity to be added to self.entities metadata(object): metadata containes keys to be added to self.metadata """
self.entities.append(tag) for k in metadata.keys(): if k not in self.metadata: self.metadata[k] = k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_context(self, max_frames=None, missing_entities=[]): """ Constructs a list of entities from the context. Args: max_frames(int): maximum number of frames to look back missing_entities(list of str): a list or set of tag names, as strings Returns: list: a list of entities """
if not max_frames or max_frames > len(self.frame_stack): max_frames = len(self.frame_stack) missing_entities = list(missing_entities) context = [] for i in xrange(max_frames): frame_entities = [entity.copy() for entity in self.frame_stack[i].entities] for entity in frame_entities: entity['confidence'] = entity.get('confidence', 1.0) / (2.0 + i) context += frame_entities result = [] if len(missing_entities) > 0: for entity in context: if entity.get('data') in missing_entities: result.append(entity) # NOTE: this implies that we will only ever get one # of an entity kind from context, unless specified # multiple times in missing_entities. Cannot get # an arbitrary number of an entity kind. missing_entities.remove(entity.get('data')) else: result = context return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_first_tag(tags, entity_type, after_index=-1): """Searches tags for entity type after given index Args: tags(list): a list of tags with entity types to be compaired too entity_type entity_type(str): This is he entity type to be looking for in tags after_index(int): the start token must be greaterthan this. Returns: ( tag, v, confidence ): tag(str): is the tag that matched v(str): ? the word that matched? confidence(float): is a mesure of accuacy. 1 is full confidence and 0 is none. """
for tag in tags: for entity in tag.get('entities'): for v, t in entity.get('data'): if t.lower() == entity_type.lower() and tag.get('start_token', 0) > after_index: return tag, v, entity.get('confidence') return None, None, None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def choose_1_from_each(lists): """Takes a list of lists and returns a list of lists with one item from each list. This new list should be the length of each list multiplied by the others. 18 for an list with lists of 3, 2 and 3. Also the lenght of each sub list should be same as the length of lists passed in. Args: lists(list of Lists): A list of lists Returns: list of lists: returns a list of lists constructions of one item from each list in lists. """
if len(lists) == 0: yield [] else: for el in lists[0]: for next_list in choose_1_from_each(lists[1:]): yield [el] + next_list
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolve_one_of(tags, at_least_one): """This searches tags for Entites in at_least_one and returns any match Args: tags(list): List of tags with Entities to search for Entities at_least_one(list): List of Entities to find in tags Returns: object: returns None if no match is found but returns any match as an object """
if len(tags) < len(at_least_one): return None for possible_resolution in choose_1_from_each(at_least_one): resolution = {} pr = possible_resolution[:] for entity_type in pr: last_end_index = -1 if entity_type in resolution: last_end_index = resolution.get[entity_type][-1].get('end_token') tag, value, c = find_first_tag(tags, entity_type, after_index=last_end_index) if not tag: break else: if entity_type not in resolution: resolution[entity_type] = [] resolution[entity_type].append(tag) if len(resolution) == len(possible_resolution): return resolution return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(self, tags, confidence): """Using this method removes tags from the result of validate_with_tags Returns: intent(intent): Resuts from validate_with_tags """
intent, tags = self.validate_with_tags(tags, confidence) return intent
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_with_tags(self, tags, confidence): """Validate weather tags has required entites for this intent to fire Args: tags(list): Tags and Entities used for validation confidence(float): ? Returns: intent, tags: Returns intent and tags used by the intent on falure to meat required entities then returns intent with confidence of 0.0 and an empty list for tags. """
result = {'intent_type': self.name} intent_confidence = 0.0 local_tags = tags[:] used_tags = [] for require_type, attribute_name in self.requires: required_tag, canonical_form, confidence = find_first_tag(local_tags, require_type) if not required_tag: result['confidence'] = 0.0 return result, [] result[attribute_name] = canonical_form if required_tag in local_tags: local_tags.remove(required_tag) used_tags.append(required_tag) # TODO: use confidence based on edit distance and context intent_confidence += confidence if len(self.at_least_one) > 0: best_resolution = resolve_one_of(tags, self.at_least_one) if not best_resolution: result['confidence'] = 0.0 return result, [] else: for key in best_resolution: result[key] = best_resolution[key][0].get('key') # TODO: at least one must support aliases intent_confidence += 1.0 used_tags.append(best_resolution) if best_resolution in local_tags: local_tags.remove(best_resolution) for optional_type, attribute_name in self.optional: optional_tag, canonical_form, conf = find_first_tag(local_tags, optional_type) if not optional_tag or attribute_name in result: continue result[attribute_name] = canonical_form if optional_tag in local_tags: local_tags.remove(optional_tag) used_tags.append(optional_tag) intent_confidence += 1.0 total_confidence = intent_confidence / len(tags) * confidence target_client, canonical_form, confidence = find_first_tag(local_tags, CLIENT_ENTITY_NAME) result['target'] = target_client.get('key') if target_client else None result['confidence'] = total_confidence return result, used_tags
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def require(self, entity_type, attribute_name=None): """ The intent parser should require an entity of the provided type. Args: entity_type(str): an entity type attribute_name(str): the name of the attribute on the parsed intent. Defaults to match entity_type. Returns: self: to continue modifications. """
if not attribute_name: attribute_name = entity_type self.requires += [(entity_type, attribute_name)] return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def optionally(self, entity_type, attribute_name=None): """ Parsed intents from this parser can optionally include an entity of the provided type. Args: entity_type(str): an entity type attribute_name(str): the name of the attribute on the parsed intent. Defaults to match entity_type. Returns: self: to continue modifications. """
if not attribute_name: attribute_name = entity_type self.optional += [(entity_type, attribute_name)] return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build(self): """ Constructs an intent from the builder's specifications. :return: an Intent instance. """
return Intent(self.name, self.requires, self.at_least_one, self.optional)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def term_matrix(idlist, subject_category, taxon, **kwargs): """ Intersection between annotated objects P1 not(P1) F1 0 5 not(F1) 6 0 """
results = search_associations(objects=idlist, subject_taxon=taxon, subject_category=subject_category, select_fields=[M.SUBJECT, M.OBJECT_CLOSURE], facet_fields=[], rows=-1, include_raw=True, **kwargs) docs = results['raw'].docs subjects_per_term = {} smap = {} for d in docs: smap[d[M.SUBJECT]] = 1 for c in d[M.OBJECT_CLOSURE]: if c in idlist: if c not in subjects_per_term: subjects_per_term[c] = [] subjects_per_term[c].append(d[M.SUBJECT]) pop_n = len(smap.keys()) cells = [] for cx in idlist: csubjs = set(subjects_per_term[cx]) for dx in idlist: dsubjs = set(subjects_per_term[dx]) a = len(csubjs.intersection(dsubjs)) b = len(csubjs) - a c = len(dsubjs) - a d = pop_n - len(dsubjs) - b ctable = [[a, b], [c, d]] _, p_under = sp.stats.fisher_exact(ctable, 'less') _, p_over = sp.stats.fisher_exact(ctable, 'greater') cells.append({'c':cx, 'd':dx, 'nc':len(csubjs), 'nd':len(dsubjs), 'n':a, 'p_l':p_under, 'p_g':p_over }) return cells
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_ancestors_through_subont(self, go_term, relations): """ Returns the ancestors from the relation filtered GO subontology of go_term's ancestors. subontology() primarily used here for speed when specifying relations to traverse. Point of this is to first get a smaller graph (all ancestors of go_term regardless of relation) and then filter relations on that instead of the whole GO. """
all_ancestors = self.ontology.ancestors(go_term, reflexive=True) subont = self.ontology.subontology(all_ancestors) return subont.ancestors(go_term, relations)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def go_aspect(self, go_term): """ For GO terms, returns F, C, or P corresponding to its aspect """
if not go_term.startswith("GO:"): return None else: # Check ancestors for root terms if self.is_molecular_function(go_term): return 'F' elif self.is_cellular_component(go_term): return 'C' elif self.is_biological_process(go_term): return 'P'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _neighbors_graph(self, **params) -> Dict: """ Get neighbors of a node parameters are directly passed through to SciGraph: e.g. depth, relationshipType """
response = self._get_response("graph/neighbors", format="json", **params) return response.json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rdfgraph_to_ontol(rg): """ Return an Ontology object from an rdflib graph object Status: Incomplete """
digraph = networkx.MultiDiGraph() from rdflib.namespace import RDF label_map = {} for c in rg.subjects(RDF.type, OWL.Class): cid = contract_uri_wrap(c) logging.info("C={}".format(cid)) for lit in rg.objects(c, RDFS.label): label_map[cid] = lit.value digraph.add_node(cid, label=lit.value) for s in rg.objects(c, RDFS.subClassOf): # todo - blank nodes sid = contract_uri_wrap(s) digraph.add_edge(sid, cid, pred='subClassOf') logging.info("G={}".format(digraph)) payload = { 'graph': digraph, #'xref_graph': xref_graph, #'graphdoc': obographdoc, #'logical_definitions': logical_definitions } ont = Ontology(handle='wd', payload=payload) return ont
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_association(id, **kwargs): """ Fetch an association object by ID """
results = search_associations(id=id, **kwargs) assoc = results['associations'][0] if len(results['associations']) > 0 else {} return assoc
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_associations(**kwargs): """ Fetch a set of association objects based on a query. """
logging.info("CREATING_GOLR_QUERY {}".format(kwargs)) q = GolrAssociationQuery(**kwargs) return q.exec()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bulk_fetch(subject_category, object_category, taxon, rows=MAX_ROWS, **kwargs): """ Fetch associations for a species and pair of categories in bulk. Arguments: - subject_category: String (not None) - object_category: String (not None) - taxon: String - rows: int Additionally, any argument for search_associations can be passed """
assert subject_category is not None assert object_category is not None time.sleep(1) logging.info("Bulk query: {} {} {}".format(subject_category, object_category, taxon)) assocs = search_associations_compact(subject_category=subject_category, object_category=object_category, subject_taxon=taxon, rows=rows, iterate=True, **kwargs) logging.info("Rows retrieved: {}".format(len(assocs))) if len(assocs) == 0: logging.error("No associations returned for query: {} {} {}".format(subject_category, object_category, taxon)) return assocs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_associations_go( subject_category=None, object_category=None, relation=None, subject=None, **kwargs): """ Perform association search using Monarch golr """
go_golr_url = "http://golr.geneontology.org/solr/" go_solr = pysolr.Solr(go_golr_url, timeout=5) go_solr.get_session().headers['User-Agent'] = get_user_agent(caller_name=__name__) return search_associations(subject_category, object_category, relation, subject, solr=go_solr, field_mapping=goassoc_fieldmap(), **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select_distinct(distinct_field=None, **kwargs): """ select distinct values for a given field for a given a query """
results = search_associations(rows=0, select_fields=[], facet_field_limits = { distinct_field : -1 }, facet_fields=[distinct_field], **kwargs ) # TODO: map field return list(results['facet_counts'][distinct_field].keys())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pw_score_cosine(self, s1 : ClassId, s2 : ClassId) -> SimScore: """ Cosine similarity of two subjects Arguments --------- s1 : str class id Return ------ number A number between 0 and 1 """
df = self.assoc_df slice1 = df.loc[s1].values slice2 = df.loc[s2].values return 1 - cosine(slice1, slice2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calculate_mrcas(self, c1 : ClassId, c2 : ClassId) -> Set[ClassId]: """ Calculate the MRCA for a class pair """
G = self.G # reflexive ancestors ancs1 = self._ancestors(c1) | {c1} ancs2 = self._ancestors(c2) | {c2} common_ancestors = ancs1 & ancs2 redundant = set() for a in common_ancestors: redundant = redundant | nx.ancestors(G, a) return common_ancestors - redundant
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pw_compare_class_sets(self, cset1: Set[ClassId], cset2: Set[ClassId]) -> Tuple[ICValue, ICValue, ICValue]: """ Compare two class profiles """
pairs = self.mica_ic_df.loc[cset1, cset2] max0 = pairs.max(axis=0) max1 = pairs.max(axis=1) idxmax0 = pairs.idxmax(axis=0) idxmax1 = pairs.idxmax(axis=1) mean0 = max0.mean() mean1 = max1.mean() return (mean0+mean1)/2, mean0, mean1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_file(self,filename=None, format=None): """ Parse a file into an ontology object, using rdflib """
rdfgraph = rdflib.Graph() if format is None: if filename.endswith(".ttl"): format='turtle' elif filename.endswith(".rdf"): format='xml' rdfgraph.parse(filename, format=format) return self.process_rdfgraph(rdfgraph)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_rdfgraph(self, rg, ont=None): """ Transform a skos terminology expressed in an rdf graph into an Ontology object Arguments --------- rg: rdflib.Graph graph object Returns ------- Ontology """
# TODO: ontology metadata if ont is None: ont = Ontology() subjs = list(rg.subjects(RDF.type, SKOS.ConceptScheme)) if len(subjs) == 0: logging.warning("No ConceptScheme") else: ont.id = self._uri2id(subjs[0]) subset_map = {} for concept in rg.subjects(RDF.type, SKOS.Concept): for s in self._get_schemes(rg, concept): subset_map[self._uri2id(s)] = s for concept in sorted(list(rg.subjects(RDF.type, SKOS.Concept))): concept_uri = str(concept) id=self._uri2id(concept) logging.info("ADDING: {}".format(id)) ont.add_node(id, self._get_label(rg,concept)) for defn in rg.objects(concept, SKOS.definition): if (defn.language == self.lang): td = TextDefinition(id, escape_value(defn.value)) ont.add_text_definition(td) for s in rg.objects(concept, SKOS.broader): ont.add_parent(id, self._uri2id(s)) for s in rg.objects(concept, SKOS.related): ont.add_parent(id, self._uri2id(s), self._uri2id(SKOS.related)) for m in rg.objects(concept, SKOS.exactMatch): ont.add_xref(id, self._uri2id(m)) for m in rg.objects(concept, SKOS.altLabel): syn = Synonym(id, val=self._uri2id(m)) ont.add_synonym(syn) for s in self._get_schemes(rg,concept): ont.add_to_subset(id, self._uri2id(s)) return ont
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_attribute_information_profile( url: str, profile: Optional[Tuple[str]]=None, categories: Optional[Tuple[str]]=None) -> Dict: """ Get the information content for a list of phenotypes and the annotation sufficiency simple and and categorical scores if categories are provied Ref: https://zenodo.org/record/834091#.W8ZnCxhlCV4 Note that the simple score varies slightly from the pub in that it uses max_max_ic instead of mean_max_ic If no arguments are passed this function returns the system (loaded cohort) stats :raises JSONDecodeError: If the response body does not contain valid json. """
owlsim_url = url + 'getAttributeInformationProfile' params = { 'a': profile, 'r': categories } return requests.get(owlsim_url, params=params, timeout=TIMEOUT).json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search( self, id_list: List, negated_classes: List, limit: Optional[int] = 100, method: Optional[SimAlgorithm] = SimAlgorithm.PHENODIGM) -> SimResult: """ Owlsim2 search, calls search_by_attribute_set, and converts to SimResult object :raises JSONDecodeError: If the owlsim response is not valid json. """
return self.filtered_search( id_list=id_list, negated_classes=negated_classes, limit=limit, taxon_filter=None, category_filter=None, method=method )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filtered_search( self, id_list: List, negated_classes: List, limit: Optional[int] = 100, taxon_filter: Optional[int] = None, category_filter: Optional[str] = None, method: Optional[SimAlgorithm] = SimAlgorithm.PHENODIGM) -> SimResult: """ Owlsim2 filtered search, resolves taxon and category to a namespace, calls search_by_attribute_set, and converts to SimResult object """
if len(negated_classes) > 0: logging.warning("Owlsim2 does not support negation, ignoring neg classes") namespace_filter = self._get_namespace_filter(taxon_filter, category_filter) owlsim_results = search_by_attribute_set(self.url, tuple(id_list), limit, namespace_filter) return self._simsearch_to_simresult(owlsim_results, method)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def matchers() -> List[SimAlgorithm]: """ Matchers in owlsim2 """
return [ SimAlgorithm.PHENODIGM, SimAlgorithm.JACCARD, SimAlgorithm.SIM_GIC, SimAlgorithm.RESNIK, SimAlgorithm.SYMMETRIC_RESNIK ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_profile_ic(self, profile: List) -> Dict: """ Given a list of individuals, return their information content """
sim_response = get_attribute_information_profile(self.url, tuple(profile)) profile_ic = {} try: for cls in sim_response['input']: profile_ic[cls['id']] = cls['IC'] except JSONDecodeError as json_exc: raise JSONDecodeError( "Cannot parse owlsim2 response: {}".format(json_exc.msg), json_exc.doc, json_exc.pos ) return profile_ic
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _simsearch_to_simresult(self, sim_resp: Dict, method: SimAlgorithm) -> SimResult: """ Convert owlsim json to SimResult object :param sim_resp: owlsim response from search_by_attribute_set() :param method: SimAlgorithm :return: SimResult object """
sim_ids = get_nodes_from_ids(sim_resp['query_IRIs']) sim_resp['results'] = OwlSim2Api._rank_results(sim_resp['results'], method) # get id type map: ids = [result['j']['id'] for result in sim_resp['results']] id_type_map = get_id_type_map(ids) matches = [] for result in sim_resp['results']: matches.append( SimMatch( id=result['j']['id'], label=result['j']['label'], rank=result['rank'], score=result[OwlSim2Api.method2key[method]], type=id_type_map[result['j']['id']][0], taxon=get_taxon(result['j']['id']), significance="NaN", pairwise_match=OwlSim2Api._make_pairwise_matches(result) ) ) return SimResult( query=SimQuery( ids=sim_ids, unresolved_ids=sim_resp['unresolved'], target_ids=[[]] ), matches=matches, metadata=SimMetadata( max_max_ic=self.statistics.max_max_ic ) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _rank_results(results: List[Dict], method: SimAlgorithm) -> List[Dict]: """ Ranks results - for phenodigm results are ranks but ties need to accounted for for other methods, results need to be reranked :param results: Results from search_by_attribute_set()['results'] or compare_attribute_sets()['results'] :param method: sim method used to rank results :return: Sorted results list """
# https://stackoverflow.com/a/73050 sorted_results = sorted( results, reverse=True, key=lambda k: k[OwlSim2Api.method2key[method]] ) if len(sorted_results) > 0: rank = 1 previous_score = sorted_results[0][OwlSim2Api.method2key[method]] for result in sorted_results: if previous_score > result[OwlSim2Api.method2key[method]]: rank += 1 result['rank'] = rank previous_score = result[OwlSim2Api.method2key[method]] return sorted_results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def translate_facet_field(fcs, invert_subject_object = False): """ Translates solr facet_fields results into something easier to manipulate This has slightly higher overhead for sending over the wire, but is easier to use """
if 'facet_fields' not in fcs: return {} ffs = fcs['facet_fields'] rs={} for (facet, facetresults) in ffs.items(): if invert_subject_object: for (k,v) in INVERT_FIELDS_MAP.items(): if facet == k: facet = v break elif facet == v: facet = k break pairs = {} rs[facet] = pairs for i in range(int(len(facetresults)/2)): (fv,fc) = (facetresults[i*2],facetresults[i*2+1]) pairs[fv] = fc return rs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def goassoc_fieldmap(relationship_type=ACTS_UPSTREAM_OF_OR_WITHIN): """ Returns a mapping of canonical monarch fields to amigo-golr. See: https://github.com/geneontology/amigo/blob/master/metadata/ann-config.yaml """
return { M.SUBJECT: 'bioentity', M.SUBJECT_CLOSURE: 'bioentity', ## In the GO AmiGO instance, the type field is not correctly populated ## See above in the code for hack that restores this for planteome instance ## M.SUBJECT_CATEGORY: 'type', M.SUBJECT_CATEGORY: None, M.SUBJECT_LABEL: 'bioentity_label', M.SUBJECT_TAXON: 'taxon', M.SUBJECT_TAXON_LABEL: 'taxon_label', M.SUBJECT_TAXON_CLOSURE: 'taxon_closure', M.RELATION: 'qualifier', M.OBJECT: 'annotation_class', M.OBJECT_CLOSURE: REGULATES_CLOSURE if relationship_type == ACTS_UPSTREAM_OF_OR_WITHIN else ISA_PARTOF_CLOSURE, M.OBJECT_LABEL: 'annotation_class_label', M.OBJECT_TAXON: 'object_taxon', M.OBJECT_TAXON_LABEL: 'object_taxon_label', M.OBJECT_TAXON_CLOSURE: 'object_taxon_closure', M.OBJECT_CATEGORY: None, M.EVIDENCE_OBJECT_CLOSURE: 'evidence_subset_closure', M.IS_DEFINED_BY: 'assigned_by' }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def map_field(fn, m) : """ Maps a field name, given a mapping file. Returns input if fieldname is unmapped. """
if m is None: return fn if fn in m: return m[fn] else: return fn
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search(self): """ Execute solr search query """
params = self.solr_params() logging.info("PARAMS=" + str(params)) results = self.solr.search(**params) logging.info("Docs found: {}".format(results.hits)) return self._process_search_results(results)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def autocomplete(self): """ Execute solr autocomplete """
self.facet = False params = self.solr_params() logging.info("PARAMS=" + str(params)) results = self.solr.search(**params) logging.info("Docs found: {}".format(results.hits)) return self._process_autocomplete_results(results)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _process_search_results(self, results: pysolr.Results) -> SearchResults: """ Convert solr docs to biolink object :param results: pysolr.Results :return: model.GolrResults.SearchResults """
# map go-golr fields to standard for doc in results.docs: if 'entity' in doc: doc['id'] = doc['entity'] doc['label'] = doc['entity_label'] highlighting = { doc['id']: self._process_highlight(results, doc)._asdict() for doc in results.docs if results.highlighting } payload = SearchResults( facet_counts=translate_facet_field(results.facets), highlighting=highlighting, docs=results.docs, numFound=results.hits ) logging.debug('Docs: {}'.format(len(results.docs))) return payload
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def autocomplete(self): """ Execute solr query for autocomplete """
params = self.set_lay_params() logging.info("PARAMS="+str(params)) results = self.solr.search(**params) logging.info("Docs found: {}".format(results.hits)) return self._process_layperson_results(results)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def translate_objs(self,d,fname): """ Translate a field whose value is expected to be a list """
if fname not in d: # TODO: consider adding arg for failure on null return None #lf = M.label_field(fname) v = d[fname] if not isinstance(v,list): v = [v] objs = [{'id': idval} for idval in v] # todo - labels return objs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def translate_obj(self,d,fname): """ Translate a field value from a solr document. This includes special logic for when the field value denotes an object, here we nest it """
if fname not in d: # TODO: consider adding arg for failure on null return None lf = M.label_field(fname) id = d[fname] id = self.make_canonical_identifier(id) #if id.startswith('MGI:MGI:'): # id = id.replace('MGI:MGI:','MGI:') obj = {'id': id} if id: if self._use_amigo_schema(self.object_category): iri = expand_uri(id) else: iri = expand_uri(id, [get_curie_map('{}/cypher/curies'.format(self.config.scigraph_data.url))]) obj['iri'] = iri if lf in d: obj['label'] = d[lf] cf = fname + "_category" if cf in d: obj['category'] = [d[cf]] if 'aspect' in d and id.startswith('GO:'): obj['category'] = [ASPECT_MAP[d['aspect']]] del d['aspect'] return obj
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def translate_docs(self, ds, **kwargs): """ Translate a set of solr results """
for d in ds: self.map_doc(d, {}, self.invert_subject_object) return [self.translate_doc(d, **kwargs) for d in ds]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def translate_docs_compact(self, ds, field_mapping=None, slim=None, map_identifiers=None, invert_subject_object=False, **kwargs): """ Translate golr association documents to a compact representation """
amap = {} logging.info("Translating docs to compact form. Slim={}".format(slim)) for d in ds: self.map_doc(d, field_mapping, invert_subject_object=invert_subject_object) subject = d[M.SUBJECT] subject_label = d[M.SUBJECT_LABEL] # TODO: use a more robust method; we need equivalence as separate field in solr if map_identifiers is not None: if M.SUBJECT_CLOSURE in d: subject = self.map_id(subject, map_identifiers, d[M.SUBJECT_CLOSURE]) else: logging.debug("NO SUBJECT CLOSURE IN: "+str(d)) rel = d.get(M.RELATION) skip = False # TODO if rel == 'not' or rel == 'NOT': skip = True # this is a list in GO if isinstance(rel,list): if 'not' in rel or 'NOT' in rel: skip = True if len(rel) > 1: logging.warn(">1 relation: {}".format(rel)) rel = ";".join(rel) if skip: logging.debug("Skipping: {}".format(d)) continue subject = self.make_canonical_identifier(subject) #if subject.startswith('MGI:MGI:'): # subject = subject.replace('MGI:MGI:','MGI:') k = (subject,rel) if k not in amap: amap[k] = {'subject':subject, 'subject_label':subject_label, 'relation':rel, 'objects': []} if slim is not None and len(slim)>0: mapped_objects = [x for x in d[M.OBJECT_CLOSURE] if x in slim] logging.debug("Mapped objects: {}".format(mapped_objects)) amap[k]['objects'] += mapped_objects else: amap[k]['objects'].append(d[M.OBJECT]) for k in amap.keys(): amap[k]['objects'] = list(set(amap[k]['objects'])) return list(amap.values())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def map_id(self,id, prefix, closure_list): """ Map identifiers based on an equivalence closure list. """
prefixc = prefix + ':' ids = [eid for eid in closure_list if eid.startswith(prefixc)] # TODO: add option to fail if no mapping, or if >1 mapping if len(ids) == 0: # default to input return id return ids[0]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, ontology=None,subject_category=None,object_category=None,evidence=None,taxon=None,relation=None, file=None, fmt=None, skim=True): """ creates an AssociationSet Currently, this uses an eager binding to a `ontobio.golr` instance. All compact associations for the particular combination of parameters are fetched. Arguments --------- ontology: an `Ontology` object subject_category: string representing category of subjects (e.g. gene, disease, variant) object_category: string representing category of objects (e.g. function, phenotype, disease) taxon: string holding NCBITaxon:nnnn ID """
meta = AssociationSetMetadata(subject_category=subject_category, object_category=object_category, taxon=taxon) if file is not None: return self.create_from_file(file=file, fmt=fmt, ontology=ontology, meta=meta, skim=skim) logging.info("Fetching assocs from store") assocs = bulk_fetch_cached(subject_category=subject_category, object_category=object_category, evidence=evidence, taxon=taxon) logging.info("Creating map for {} subjects".format(len(assocs))) amap = {} subject_label_map = {} for a in assocs: rel = a['relation'] subj = a['subject'] subject_label_map[subj] = a['subject_label'] amap[subj] = a['objects'] aset = AssociationSet(ontology=ontology, meta=meta, subject_label_map=subject_label_map, association_map=amap) return aset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_from_assocs(self, assocs, **args): """ Creates from a list of association objects """
amap = defaultdict(list) subject_label_map = {} for a in assocs: subj = a['subject'] subj_id = subj['id'] subj_label = subj['label'] subject_label_map[subj_id] = subj_label if not a['negated']: amap[subj_id].append(a['object']['id']) aset = AssociationSet(subject_label_map=subject_label_map, association_map=amap, **args) aset.associations_by_subj = defaultdict(list) aset.associations_by_subj_obj = defaultdict(list) for a in assocs: sub_id = a['subject']['id'] obj_id = a['object']['id'] aset.associations_by_subj[sub_id].append(a) aset.associations_by_subj_obj[(sub_id,obj_id)].append(a) return aset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_from_file(self, file=None, fmt='gaf', skim=True, **args): """ Creates from a file. If fmt is set to None then the file suffixes will be used to choose a parser. Arguments --------- file : str or file input file or filename fmt : str name of format e.g. gaf """
if fmt is not None and not fmt.startswith('.'): fmt = '.{}'.format(fmt) d = { '.gaf' : GafParser, '.gpad' : GpadParser, '.hpoa' : HpoaParser, } if fmt is None: filename = file if isinstance(file, str) else file.name suffixes = pathlib.Path(filename).suffixes iterator = (fn() for ext, fn in d.items() if ext in suffixes) else: iterator = (fn() for ext, fn in d.items() if ext == fmt) try: parser = next(iterator) except StopIteration: logging.error("Format not recognized: {}".format(fmt)) logging.info("Parsing {} with {}/{}".format(file, fmt, parser)) if skim: results = parser.skim(file) return self.create_from_tuples(results, **args) else: assocs = parser.parse(file, skipheader=True) return self.create_from_assocs(assocs, **args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_from_remote_file(self, group, snapshot=True, **args): """ Creates from remote GAF """
import requests url = "http://snapshot.geneontology.org/annotations/{}.gaf.gz".format(group) r = requests.get(url, stream=True, headers={'User-Agent': get_user_agent(modules=[requests], caller_name=__name__)}) p = GafParser() results = p.skim(r.raw) return self.create_from_tuples(results, **args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render(ont, query_ids, args): """ Writes or displays graph """
if args.slim.find('m') > -1: logging.info("SLIMMING") g = get_minimal_subgraph(g, query_ids) w = GraphRenderer.create(args.to) if args.showdefs: w.config.show_text_definition = True if args.render: if 'd' in args.render: logging.info("Showing text defs") w.config.show_text_definition = True if args.outfile is not None: w.outfile = args.outfile w.write(ont, query_ids=query_ids, container_predicates=args.container_properties)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_object_closure(subject, object_category=None, **kwargs): """ Find all terms used to annotate subject plus ancestors """
results = search_associations(subject=subject, object_category=object_category, select_fields=[], facet_fields=[M.OBJECT_CLOSURE], facet_limit=-1, rows=0, **kwargs) return set(results['facet_counts'][M.OBJECT_CLOSURE].keys())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def namespace_to_taxon() -> Dict[str, Node]: """ namespace to taxon mapping """
human_taxon = Node( id='NCBITaxon:9606', label='Homo sapiens' ) return { 'MGI': Node( id='NCBITaxon:10090', label='Mus musculus' ), 'MONDO': human_taxon, 'OMIM': human_taxon, 'MONARCH': human_taxon, 'HGNC': human_taxon, 'FlyBase': Node( id='NCBITaxon:7227', label='Drosophila melanogaster' ), 'WormBase': Node( id='NCBITaxon:6239', label='Caenorhabditis elegans' ), 'ZFIN': Node( id='NCBITaxon:7955', label='Danio rerio' ) }