Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def make_model(self, add_indra_json=True): self.add_indra_json = add_indra_json for stmt in self.statements: if isinstance(stmt, Modification): self._add_modification(stmt) if isinstance(stmt, SelfModification)...
[ "Assemble the CX network from the collected INDRA Statements.\n\n This method assembles a CX network from the set of INDRA Statements.\n The assembled network is set as the assembler's cx argument.\n\n Parameters\n ----------\n add_indra_json : Optional[bool]\n If True,...
Please provide a description of the function:def print_cx(self, pretty=True): def _get_aspect_metadata(aspect): count = len(self.cx.get(aspect)) if self.cx.get(aspect) else 0 if not count: return None data = {'name': aspect, 'idCou...
[ "Return the assembled CX network as a json string.\n\n Parameters\n ----------\n pretty : bool\n If True, the CX string is formatted with indentation (for human\n viewing) otherwise no indentation is used.\n\n Returns\n -------\n json_str : str\n ...
Please provide a description of the function:def save_model(self, file_name='model.cx'): with open(file_name, 'wt') as fh: cx_str = self.print_cx() fh.write(cx_str)
[ "Save the assembled CX network in a file.\n\n Parameters\n ----------\n file_name : Optional[str]\n The name of the file to save the CX network to. Default: model.cx\n " ]
Please provide a description of the function:def upload_model(self, ndex_cred=None, private=True, style='default'): cx_str = self.print_cx() if not ndex_cred: username, password = ndex_client.get_default_ndex_cred({}) ndex_cred = {'user': username, ...
[ "Creates a new NDEx network of the assembled CX model.\n\n To upload the assembled CX model to NDEx, you need to have\n a registered account on NDEx (http://ndexbio.org/) and have\n the `ndex` python package installed. The uploaded network\n is private by default.\n\n Parameters\n...
Please provide a description of the function:def set_context(self, cell_type): node_names = [node['n'] for node in self.cx['nodes']] res_expr = context_client.get_protein_expression(node_names, [cell_type]) res_mut = context_clien...
[ "Set protein expression data and mutational status as node attribute\n\n This method uses :py:mod:`indra.databases.context_client` to get\n protein expression levels and mutational status for a given cell type\n and set a node attribute for proteins accordingly.\n\n Parameters\n -...
Please provide a description of the function:def get_publications(gene_names, save_json_name=None): if len(gene_names) != 2: logger.warning('Other than 2 gene names given.') return [] res_dict = _send_request(gene_names) if not res_dict: return [] if save_json_name is not No...
[ "Return evidence publications for interaction between the given genes.\n\n Parameters\n ----------\n gene_names : list[str]\n A list of gene names (HGNC symbols) to query interactions between.\n Currently supports exactly two genes only.\n save_json_name : Optional[str]\n A file nam...
Please provide a description of the function:def _n(name): n = name.encode('ascii', errors='ignore').decode('ascii') n = re.sub('[^A-Za-z0-9_]', '_', n) n = re.sub(r'(^[0-9].*)', r'p\1', n) return n
[ "Return valid PySB name." ]
Please provide a description of the function:def get_hash_statements_dict(self): res = {stmt_hash: stmts_from_json([stmt])[0] for stmt_hash, stmt in self.__statement_jsons.items()} return res
[ "Return a dict of Statements keyed by hashes." ]
Please provide a description of the function:def merge_results(self, other_processor): if not isinstance(other_processor, self.__class__): raise ValueError("Can only extend with another %s instance." % self.__class__.__name__) self.statements.extend(othe...
[ "Merge the results of this processor with those of another." ]
Please provide a description of the function:def wait_until_done(self, timeout=None): start = datetime.now() if not self.__th: raise IndraDBRestResponseError("There is no thread waiting to " "complete.") self.__th.join(timeout) ...
[ "Wait for the background load to complete." ]
Please provide a description of the function:def _merge_json(self, stmt_json, ev_counts): # Where there is overlap, there _should_ be agreement. self.__evidence_counts.update(ev_counts) for k, sj in stmt_json.items(): if k not in self.__statement_jsons: self...
[ "Merge these statement jsons with new jsons." ]
Please provide a description of the function:def _run_queries(self, agent_strs, stmt_types, params, persist): self._query_over_statement_types(agent_strs, stmt_types, params) assert len(self.__done_dict) == len(stmt_types) \ or None in self.__done_dict.keys(), \ "Done d...
[ "Use paging to get all statements requested." ]
Please provide a description of the function:def get_ids(search_term, **kwargs): use_text_word = kwargs.pop('use_text_word', True) if use_text_word: search_term += '[tw]' params = {'term': search_term, 'retmax': 100000, 'retstart': 0, 'db': 'pubmed', ...
[ "Search Pubmed for paper IDs given a search term.\n\n Search options can be passed as keyword arguments, some of which are\n custom keywords identified by this function, while others are passed on\n as parameters for the request to the PubMed web service\n For details on parameters that can be used in P...
Please provide a description of the function:def get_id_count(search_term): params = {'term': search_term, 'rettype': 'count', 'db': 'pubmed'} tree = send_request(pubmed_search, params) if tree is None: return None else: count = tree.getchildren()[0].text...
[ "Get the number of citations in Pubmed for a search query.\n\n Parameters\n ----------\n search_term : str\n A term for which the PubMed search should be performed.\n\n Returns\n -------\n int or None\n The number of citations for the query, or None if the query fails.\n " ]
Please provide a description of the function:def get_ids_for_gene(hgnc_name, **kwargs): # Get the HGNC ID for the HGNC name hgnc_id = hgnc_client.get_hgnc_id(hgnc_name) if hgnc_id is None: raise ValueError('Invalid HGNC name.') # Get the Entrez ID entrez_id = hgnc_client.get_entrez_id(...
[ "Get the curated set of articles for a gene in the Entrez database.\n\n Search parameters for the Gene database query can be passed in as\n keyword arguments. \n\n Parameters\n ----------\n hgnc_name : string\n The HGNC name of the gene. This is used to obtain the HGNC ID\n (using the h...
Please provide a description of the function:def get_article_xml(pubmed_id): if pubmed_id.upper().startswith('PMID'): pubmed_id = pubmed_id[4:] params = {'db': 'pubmed', 'retmode': 'xml', 'id': pubmed_id} tree = send_request(pubmed_fetch, params) if tree is None:...
[ "Get the XML metadata for a single article from the Pubmed database.\n " ]
Please provide a description of the function:def get_abstract(pubmed_id, prepend_title=True): article = get_article_xml(pubmed_id) if article is None: return None return _abstract_from_article_element(article, prepend_title)
[ "Get the abstract of an article in the Pubmed database." ]
Please provide a description of the function:def get_metadata_from_xml_tree(tree, get_issns_from_nlm=False, get_abstracts=False, prepend_title=False, mesh_annotations=False): # Iterate over the articles and build the results dict results = {} ...
[ "Get metadata for an XML tree containing PubmedArticle elements.\n\n Documentation on the XML structure can be found at:\n - https://www.nlm.nih.gov/bsd/licensee/elements_descriptions.html\n - https://www.nlm.nih.gov/bsd/licensee/elements_alphabetical.html\n\n Parameters\n ----------\n tre...
Please provide a description of the function:def get_metadata_for_ids(pmid_list, get_issns_from_nlm=False, get_abstracts=False, prepend_title=False): if len(pmid_list) > 200: raise ValueError("Metadata query is limited to 200 PMIDs at a time.") params = {'db': 'pubmed', ...
[ "Get article metadata for up to 200 PMIDs from the Pubmed database.\n\n Parameters\n ----------\n pmid_list : list of PMIDs as strings\n Can contain 1-200 PMIDs.\n get_issns_from_nlm : boolean\n Look up the full list of ISSN number for the journal associated with\n the article, whic...
Please provide a description of the function:def get_issns_for_journal(nlm_id): params = {'db': 'nlmcatalog', 'retmode': 'xml', 'id': nlm_id} tree = send_request(pubmed_fetch, params) if tree is None: return None issn_list = tree.findall('.//ISSN') issn_linki...
[ "Get a list of the ISSN numbers for a journal given its NLM ID.\n\n Information on NLM XML DTDs is available at\n https://www.nlm.nih.gov/databases/dtd/\n " ]
Please provide a description of the function:def expand_pagination(pages): # If there is no hyphen, it's a single page, and we're good to go parts = pages.split('-') if len(parts) == 1: # No hyphen, so no split return pages elif len(parts) == 2: start = parts[0] end = parts[...
[ "Convert a page number to long form, e.g., from 456-7 to 456-457." ]
Please provide a description of the function:def _find_sources_with_paths(im, target, sources, polarity): # First, create a list of visited nodes # Adapted from # http://stackoverflow.com/questions/8922060/ # how-to-trace-the-path-in-a-breadth-first-search # FIXME: the sig...
[ "Get the subset of source nodes with paths to the target.\n\n Given a target, a list of sources, and a path polarity, perform a\n breadth-first search upstream from the target to find paths to any of the\n upstream sources.\n\n Parameters\n ----------\n im : networkx.MultiDiGraph\n Graph co...
Please provide a description of the function:def remove_im_params(model, im): for param in model.parameters: # If the node doesn't exist e.g., it may have already been removed), # skip over the parameter without error try: im.remove_node(param.name) except: ...
[ "Remove parameter nodes from the influence map.\n\n Parameters\n ----------\n model : pysb.core.Model\n PySB model.\n im : networkx.MultiDiGraph\n Influence map.\n\n Returns\n -------\n networkx.MultiDiGraph\n Influence map with the parameter nodes removed.\n " ]
Please provide a description of the function:def _find_sources(im, target, sources, polarity): # First, create a list of visited nodes # Adapted from # networkx.algorithms.traversal.breadth_first_search.bfs_edges visited = set([(target, 1)]) # Generate list of predecessor nodes with a sign upda...
[ "Get the subset of source nodes with paths to the target.\n\n Given a target, a list of sources, and a path polarity, perform a\n breadth-first search upstream from the target to determine whether any of\n the queried sources have paths to the target with the appropriate polarity.\n For efficiency, does...
Please provide a description of the function:def _get_signed_predecessors(im, node, polarity): signed_pred_list = [] for pred in im.predecessors(node): pred_edge = (pred, node) yield (pred, _get_edge_sign(im, pred_edge) * polarity)
[ "Get upstream nodes in the influence map.\n\n Return the upstream nodes along with the overall polarity of the path\n to that node by account for the polarity of the path to the given node\n and the polarity of the edge between the given node and its immediate\n predecessors.\n\n Parameters\n ----...
Please provide a description of the function:def _get_edge_sign(im, edge): edge_data = im[edge[0]][edge[1]] # Handle possible multiple edges between nodes signs = list(set([v['sign'] for v in edge_data.values() if v.get('sign')])) if len(signs) > 1: logger....
[ "Get the polarity of the influence by examining the edge sign." ]
Please provide a description of the function:def _add_modification_to_agent(agent, mod_type, residue, position): new_mod = ModCondition(mod_type, residue, position) # Check if this modification already exists for old_mod in agent.mods: if old_mod.equals(new_mod): return agent ne...
[ "Add a modification condition to an Agent." ]
Please provide a description of the function:def _match_lhs(cp, rules): rule_matches = [] for rule in rules: reactant_pattern = rule.rule_expression.reactant_pattern for rule_cp in reactant_pattern.complex_patterns: if _cp_embeds_into(rule_cp, cp): rule_matches.a...
[ "Get rules with a left-hand side matching the given ComplexPattern." ]
Please provide a description of the function:def _cp_embeds_into(cp1, cp2): # Check that any state in cp2 is matched in cp1 # If the thing we're matching to is just a monomer pattern, that makes # things easier--we just need to find the corresponding monomer pattern # in cp1 if cp1 is None or c...
[ "Check that any state in ComplexPattern2 is matched in ComplexPattern1.\n " ]
Please provide a description of the function:def _mp_embeds_into(mp1, mp2): sc_matches = [] if mp1.monomer.name != mp2.monomer.name: return False # Check that all conditions in mp2 are met in mp1 for site_name, site_state in mp2.site_conditions.items(): if site_name not in mp1.site_...
[ "Check that conditions in MonomerPattern2 are met in MonomerPattern1." ]
Please provide a description of the function:def _monomer_pattern_label(mp): site_strs = [] for site, cond in mp.site_conditions.items(): if isinstance(cond, tuple) or isinstance(cond, list): assert len(cond) == 2 if cond[1] == WILD: site_str = '%s_%s' % (sit...
[ "Return a string label for a MonomerPattern." ]
Please provide a description of the function:def _stmt_from_rule(model, rule_name, stmts): stmt_uuid = None for ann in model.annotations: if ann.predicate == 'from_indra_statement': if ann.subject == rule_name: stmt_uuid = ann.object break if stmt_uui...
[ "Return the INDRA Statement corresponding to a given rule by name." ]
Please provide a description of the function:def generate_im(self, model): kappa = kappy.KappaStd() model_str = export.export(model, 'kappa') kappa.add_model_string(model_str) kappa.project_parse() imap = kappa.analyses_influence_map(accuracy='medium') graph = im...
[ "Return a graph representing the influence map generated by Kappa\n\n Parameters\n ----------\n model : pysb.Model\n The PySB model whose influence map is to be generated\n\n Returns\n -------\n graph : networkx.MultiDiGraph\n A MultiDiGraph representi...
Please provide a description of the function:def draw_im(self, fname): im = self.get_im() im_agraph = nx.nx_agraph.to_agraph(im) im_agraph.draw(fname, prog='dot')
[ "Draw and save the influence map in a file.\n\n Parameters\n ----------\n fname : str\n The name of the file to save the influence map in.\n The extension of the file will determine the file format,\n typically png or pdf.\n " ]
Please provide a description of the function:def get_im(self, force_update=False): if self._im and not force_update: return self._im if not self.model: raise Exception("Cannot get influence map if there is no model.") def add_obs_for_agent(agent): ob...
[ "Get the influence map for the model, generating it if necessary.\n\n Parameters\n ----------\n force_update : bool\n Whether to generate the influence map when the function is called.\n If False, returns the previously generated influence map if\n available. De...
Please provide a description of the function:def check_model(self, max_paths=1, max_path_length=5): results = [] for stmt in self.statements: result = self.check_statement(stmt, max_paths, max_path_length) results.append((stmt, result)) return results
[ "Check all the statements added to the ModelChecker.\n\n Parameters\n ----------\n max_paths : Optional[int]\n The maximum number of specific paths to return for each Statement\n to be explained. Default: 1\n max_path_length : Optional[int]\n The maximum ...
Please provide a description of the function:def check_statement(self, stmt, max_paths=1, max_path_length=5): # Make sure the influence map is initialized self.get_im() # Check if this is one of the statement types that we can check if not isinstance(stmt, (Modification, Regulat...
[ "Check a single Statement against the model.\n\n Parameters\n ----------\n stmt : indra.statements.Statement\n The Statement to check.\n max_paths : Optional[int]\n The maximum number of specific paths to return for each Statement\n to be explained. Defau...
Please provide a description of the function:def _find_im_paths(self, subj_mp, obs_name, target_polarity, max_paths=1, max_path_length=5): logger.info(('Running path finding with max_paths=%d,' ' max_path_length=%d') % (max_paths, max_path_length)) # ...
[ "Check for a source/target path in the influence map.\n\n Parameters\n ----------\n subj_mp : pysb.MonomerPattern\n MonomerPattern corresponding to the subject of the Statement\n being checked.\n obs_name : str\n Name of the PySB model Observable correspo...
Please provide a description of the function:def score_paths(self, paths, agents_values, loss_of_function=False, sigma=0.15, include_final_node=False): obs_model = lambda x: scipy.stats.norm(x, sigma) # Build up dict mapping observables to values obs_dict = {} ...
[ "Return scores associated with a given set of paths.\n\n Parameters\n ----------\n paths : list[list[tuple[str, int]]]\n A list of paths obtained from path finding. Each path is a list\n of tuples (which are edges in the path), with the first element\n of the tu...
Please provide a description of the function:def prune_influence_map(self): im = self.get_im() # First, remove all self-loops logger.info('Removing self loops') edges_to_remove = [] for e in im.edges(): if e[0] == e[1]: logger.info('Removing ...
[ "Remove edges between rules causing problematic non-transitivity.\n\n First, all self-loops are removed. After this initial step, edges are\n removed between rules when they share *all* child nodes except for each\n other; that is, they have a mutual relationship with each other and\n sh...
Please provide a description of the function:def prune_influence_map_subj_obj(self): def get_rule_info(r): result = {} for ann in self.model.annotations: if ann.subject == r: if ann.predicate == 'rule_has_subject': resu...
[ "Prune influence map to include only edges where the object of the\n upstream rule matches the subject of the downstream rule." ]
Please provide a description of the function:def add_section(self, section_name): self.section_headings.append(section_name) if section_name in self.sections: raise ValueError("Section %s already exists." % section_name) self.sections[section_name] = [] return
[ "Create a section of the report, to be headed by section_name\n\n Text and images can be added by using the `section` argument of the\n `add_text` and `add_image` methods. Sections can also be ordered by\n using the `set_section_order` method.\n\n By default, text and images that have no...
Please provide a description of the function:def set_section_order(self, section_name_list): self.section_headings = section_name_list[:] for section_name in self.sections.keys(): if section_name not in section_name_list: self.section_headings.append(section_name) ...
[ "Set the order of the sections, which are by default unorderd.\n\n Any unlisted sections that exist will be placed at the end of the\n document in no particular order.\n " ]
Please provide a description of the function:def add_text(self, text, *args, **kwargs): # Pull down some kwargs. section_name = kwargs.pop('section', None) # Actually do the formatting. para, sp = self._preformat_text(text, *args, **kwargs) # Select the appropriate lis...
[ "Add text to the document.\n\n Text is shown on the final document in the order it is added, either\n within the given section or as part of the un-sectioned list of content.\n\n Parameters\n ----------\n text : str\n The text to be added.\n style : str\n ...
Please provide a description of the function:def add_image(self, image_path, width=None, height=None, section=None): if width is not None: width = width*inch if height is not None: height = height*inch im = Image(image_path, width, height) if section is N...
[ "Add an image to the document.\n\n Images are shown on the final document in the order they are added,\n either within the given section or as part of the un-sectioned list of\n content.\n\n Parameters\n ----------\n image_path : str\n A path to the image on the ...
Please provide a description of the function:def make_report(self, sections_first=True, section_header_params=None): full_story = list(self._preformat_text(self.title, style='Title', fontsize=18, alignment='center')) # Set the default section head...
[ "Create the pdf document with name `self.name + '.pdf'`.\n\n Parameters\n ----------\n sections_first : bool\n If True (default), text and images with sections are presented first\n and un-sectioned content is appended afterword. If False, sectioned\n text and i...
Please provide a description of the function:def _make_sections(self, **section_hdr_params): sect_story = [] if not self.section_headings and len(self.sections): self.section_headings = self.sections.keys() for section_name in self.section_headings: section_stor...
[ "Flatten the sections into a single story list." ]
Please provide a description of the function:def _preformat_text(self, text, style='Normal', space=None, fontsize=12, alignment='left'): if space is None: space=(1,12) ptext = ('<para alignment=\"%s\"><font size=%d>%s</font></para>' % (alignm...
[ "Format the text for addition to a story list." ]
Please provide a description of the function:def get_mesh_name_from_web(mesh_id): url = MESH_URL + mesh_id + '.json' resp = requests.get(url) if resp.status_code != 200: return None mesh_json = resp.json() try: label = mesh_json['@graph'][0]['label']['@value'] except (KeyErr...
[ "Get the MESH label for the given MESH ID using the NLM REST API.\n\n Parameters\n ----------\n mesh_id : str\n MESH Identifier, e.g. 'D003094'.\n\n Returns\n -------\n str\n Label for the MESH ID, or None if the query failed or no label was\n found.\n " ]
Please provide a description of the function:def get_mesh_name(mesh_id, offline=False): indra_mesh_mapping = mesh_id_to_name.get(mesh_id) if offline or indra_mesh_mapping is not None: return indra_mesh_mapping # Look up the MESH mapping from NLM if we don't have it locally return get_mesh_n...
[ "Get the MESH label for the given MESH ID.\n\n Uses the mappings table in `indra/resources`; if the MESH ID is not listed\n there, falls back on the NLM REST API.\n\n Parameters\n ----------\n mesh_id : str\n MESH Identifier, e.g. 'D003094'.\n offline : bool\n Whether to allow querie...
Please provide a description of the function:def get_mesh_id_name(mesh_term, offline=False): indra_mesh_id = mesh_name_to_id.get(mesh_term) if indra_mesh_id is not None: return indra_mesh_id, mesh_term indra_mesh_id, new_term = \ mesh_name_to_id_name.get(mesh_term, (None, None)) if...
[ "Get the MESH ID and name for the given MESH term.\n\n Uses the mappings table in `indra/resources`; if the MESH term is not\n listed there, falls back on the NLM REST API.\n\n Parameters\n ----------\n mesh_term : str\n MESH Descriptor or Concept name, e.g. 'Breast Cancer'.\n offline : boo...
Please provide a description of the function:def get_mesh_id_name_from_web(mesh_term): url = MESH_URL + 'sparql' query = % (mesh_term, mesh_term) args = {'query': query, 'format': 'JSON', 'inference': 'true'} # Interestingly, the following call using requests.get to package the # query does no...
[ "Get the MESH ID and name for the given MESH term using the NLM REST API.\n\n Parameters\n ----------\n mesh_term : str\n MESH Descriptor or Concept name, e.g. 'Breast Cancer'.\n\n Returns\n -------\n tuple of strs\n Returns a 2-tuple of the form `(id, name)` with the ID of the\n ...
Please provide a description of the function:def make(directory): if os.path.exists(directory): if os.path.isdir(directory): click.echo('Directory already exists') else: click.echo('Path exists and is not a directory') sys.exit() os.makedirs(directory) ...
[ "Makes a RAS Machine directory" ]
Please provide a description of the function:def run_with_search(model_path, config, num_days): from indra.tools.machine.machine import run_with_search_helper run_with_search_helper(model_path, config, num_days=num_days)
[ "Run with PubMed search for new papers." ]
Please provide a description of the function:def run_with_pmids(model_path, pmids): from indra.tools.machine.machine import run_with_pmids_helper run_with_pmids_helper(model_path, pmids)
[ "Run with given list of PMIDs." ]
Please provide a description of the function:def id_lookup(paper_id, idtype=None): if idtype is not None and idtype not in ('pmid', 'pmcid', 'doi'): raise ValueError("Invalid idtype %s; must be 'pmid', 'pmcid', " "or 'doi'." % idtype) if paper_id.upper().startswith('PMC'): ...
[ "This function takes a Pubmed ID, Pubmed Central ID, or DOI\n and use the Pubmed ID mapping\n service and looks up all other IDs from one\n of these. The IDs are returned in a dictionary." ]
Please provide a description of the function:def get_xml(pmc_id): if pmc_id.upper().startswith('PMC'): pmc_id = pmc_id[3:] # Request params params = {} params['verb'] = 'GetRecord' params['identifier'] = 'oai:pubmedcentral.nih.gov:%s' % pmc_id params['metadataPrefix'] = 'pmc' # ...
[ "Returns XML for the article corresponding to a PMC ID." ]
Please provide a description of the function:def extract_paragraphs(xml_string): tree = etree.fromstring(xml_string.encode('utf-8')) paragraphs = [] # In NLM xml, all plaintext is within <p> tags, and is the only thing # that can be contained in <p> tags. To handle to possibility of namespaces ...
[ "Returns list of paragraphs in an NLM XML.\n\n Parameters\n ----------\n xml_string : str\n String containing valid NLM XML.\n\n Returns\n -------\n list of str\n List of extracted paragraphs in an NLM XML\n " ]
Please provide a description of the function:def filter_pmids(pmid_list, source_type): global pmids_fulltext_dict # Check args if source_type not in ('fulltext', 'oa_xml', 'oa_txt', 'auth_xml'): raise ValueError("source_type must be one of: 'fulltext', 'oa_xml', " "'oa_...
[ "Filter a list of PMIDs for ones with full text from PMC.\n\n Parameters\n ----------\n pmid_list : list of str\n List of PMIDs to filter.\n source_type : string\n One of 'fulltext', 'oa_xml', 'oa_txt', or 'auth_xml'.\n\n Returns\n -------\n list of str\n PMIDs available in...
Please provide a description of the function:def get_example_extractions(fname): "Get extractions from one of the examples in `cag_examples`." with open(fname, 'r') as f: sentences = f.read().splitlines() rdf_xml_dict = {} for sentence in sentences: logger.info("Reading \"%s\"..." % sent...
[]
Please provide a description of the function:def make_example_graphs(): "Make graphs from all the examples in cag_examples." cag_example_rdfs = {} for i, fname in enumerate(os.listdir('cag_examples')): cag_example_rdfs[i+1] = get_example_extractions(fname) return make_cag_graphs(cag_example_rdfs...
[]
Please provide a description of the function:def _assemble_agent_str(agent): agent_str = agent.name # Only do the more detailed assembly for molecular agents if not isinstance(agent, ist.Agent): return agent_str # Handle mutation conditions if agent.mutations: is_generic = Fal...
[ "Assemble an Agent object to text." ]
Please provide a description of the function:def _join_list(lst, oxford=False): if len(lst) > 2: s = ', '.join(lst[:-1]) if oxford: s += ',' s += ' and ' + lst[-1] elif len(lst) == 2: s = lst[0] + ' and ' + lst[1] elif len(lst) == 1: s = lst[0] el...
[ "Join a list of words in a gramatically correct way." ]
Please provide a description of the function:def _assemble_activeform(stmt): subj_str = _assemble_agent_str(stmt.agent) if stmt.is_active: is_active_str = 'active' else: is_active_str = 'inactive' if stmt.activity == 'activity': stmt_str = subj_str + ' is ' + is_active_str ...
[ "Assemble ActiveForm statements into text." ]
Please provide a description of the function:def _assemble_modification(stmt): sub_str = _assemble_agent_str(stmt.sub) if stmt.enz is not None: enz_str = _assemble_agent_str(stmt.enz) if _get_is_direct(stmt): mod_str = ' ' + _mod_process_verb(stmt) + ' ' else: ...
[ "Assemble Modification statements into text." ]
Please provide a description of the function:def _assemble_association(stmt): member_strs = [_assemble_agent_str(m.concept) for m in stmt.members] stmt_str = member_strs[0] + ' is associated with ' + \ _join_list(member_strs[1:]) return _make_sentence(stmt_str)
[ "Assemble Association statements into text." ]
Please provide a description of the function:def _assemble_complex(stmt): member_strs = [_assemble_agent_str(m) for m in stmt.members] stmt_str = member_strs[0] + ' binds ' + _join_list(member_strs[1:]) return _make_sentence(stmt_str)
[ "Assemble Complex statements into text." ]
Please provide a description of the function:def _assemble_autophosphorylation(stmt): enz_str = _assemble_agent_str(stmt.enz) stmt_str = enz_str + ' phosphorylates itself' if stmt.residue is not None: if stmt.position is None: mod_str = 'on ' + ist.amino_acids[stmt.residue]['full_na...
[ "Assemble Autophosphorylation statements into text." ]
Please provide a description of the function:def _assemble_regulate_activity(stmt): subj_str = _assemble_agent_str(stmt.subj) obj_str = _assemble_agent_str(stmt.obj) if stmt.is_activation: rel_str = ' activates ' else: rel_str = ' inhibits ' stmt_str = subj_str + rel_str + obj_s...
[ "Assemble RegulateActivity statements into text." ]
Please provide a description of the function:def _assemble_regulate_amount(stmt): obj_str = _assemble_agent_str(stmt.obj) if stmt.subj is not None: subj_str = _assemble_agent_str(stmt.subj) if isinstance(stmt, ist.IncreaseAmount): rel_str = ' increases the amount of ' el...
[ "Assemble RegulateAmount statements into text." ]
Please provide a description of the function:def _assemble_translocation(stmt): agent_str = _assemble_agent_str(stmt.agent) stmt_str = agent_str + ' translocates' if stmt.from_location is not None: stmt_str += ' from the ' + stmt.from_location if stmt.to_location is not None: stmt_s...
[ "Assemble Translocation statements into text." ]
Please provide a description of the function:def _assemble_gap(stmt): subj_str = _assemble_agent_str(stmt.gap) obj_str = _assemble_agent_str(stmt.ras) stmt_str = subj_str + ' is a GAP for ' + obj_str return _make_sentence(stmt_str)
[ "Assemble Gap statements into text." ]
Please provide a description of the function:def _assemble_gef(stmt): subj_str = _assemble_agent_str(stmt.gef) obj_str = _assemble_agent_str(stmt.ras) stmt_str = subj_str + ' is a GEF for ' + obj_str return _make_sentence(stmt_str)
[ "Assemble Gef statements into text." ]
Please provide a description of the function:def _assemble_conversion(stmt): reactants = _join_list([_assemble_agent_str(r) for r in stmt.obj_from]) products = _join_list([_assemble_agent_str(r) for r in stmt.obj_to]) if stmt.subj is not None: subj_str = _assemble_agent_str(stmt.subj) ...
[ "Assemble a Conversion statement into text." ]
Please provide a description of the function:def _assemble_influence(stmt): subj_str = _assemble_agent_str(stmt.subj.concept) obj_str = _assemble_agent_str(stmt.obj.concept) # Note that n is prepended to increase to make it "an increase" if stmt.subj.delta['polarity'] is not None: subj_del...
[ "Assemble an Influence statement into text." ]
Please provide a description of the function:def _make_sentence(txt): #Make sure first letter is capitalized txt = txt.strip(' ') txt = txt[0].upper() + txt[1:] + '.' return txt
[ "Make a sentence from a piece of text." ]
Please provide a description of the function:def _get_is_hypothesis(stmt): '''Returns true if there is evidence that the statement is only hypothetical. If all of the evidences associated with the statement indicate a hypothetical interaction then we assume the interaction is hypothetical.''' for ev...
[]
Please provide a description of the function:def make_model(self): stmt_strs = [] for stmt in self.statements: if isinstance(stmt, ist.Modification): stmt_strs.append(_assemble_modification(stmt)) elif isinstance(stmt, ist.Autophosphorylation): ...
[ "Assemble text from the set of collected INDRA Statements.\n\n Returns\n -------\n stmt_strs : str\n Return the assembled text as unicode string. By default, the text\n is a single string consisting of one or more sentences with\n periods at the end.\n " ...
Please provide a description of the function:def add_statements(self, stmts): for stmt in stmts: if not self.statement_exists(stmt): self.statements.append(stmt)
[ "Add INDRA Statements to the assembler's list of statements.\n\n Parameters\n ----------\n stmts : list[indra.statements.Statement]\n A list of :py:class:`indra.statements.Statement`\n to be added to the statement list of the assembler.\n " ]
Please provide a description of the function:def make_model(self): ppa = PysbPreassembler(self.statements) ppa.replace_activities() self.statements = ppa.statements self.sbgn = emaker.sbgn() self._map = emaker.map() self.sbgn.append(self._map) for stmt in...
[ "Assemble the SBGN model from the collected INDRA Statements.\n\n This method assembles an SBGN model from the set of INDRA Statements.\n The assembled model is set as the assembler's sbgn attribute (it is\n represented as an XML ElementTree internally). The model is returned\n as a seri...
Please provide a description of the function:def print_model(self, pretty=True, encoding='utf8'): return lxml.etree.tostring(self.sbgn, pretty_print=pretty, encoding=encoding, xml_declaration=True)
[ "Return the assembled SBGN model as an XML string.\n\n Parameters\n ----------\n pretty : Optional[bool]\n If True, the SBGN string is formatted with indentation (for human\n viewing) otherwise no indentation is used. Default: True\n\n Returns\n -------\n ...
Please provide a description of the function:def save_model(self, file_name='model.sbgn'): model = self.print_model() with open(file_name, 'wb') as fh: fh.write(model)
[ "Save the assembled SBGN model in a file.\n\n Parameters\n ----------\n file_name : Optional[str]\n The name of the file to save the SBGN network to.\n Default: model.sbgn\n " ]
Please provide a description of the function:def _glyph_for_complex_pattern(self, pattern): # Make the main glyph for the agent monomer_glyphs = [] for monomer_pattern in pattern.monomer_patterns: glyph = self._glyph_for_monomer_pattern(monomer_pattern) monomer_g...
[ "Add glyph and member glyphs for a PySB ComplexPattern." ]
Please provide a description of the function:def _glyph_for_monomer_pattern(self, pattern): pattern.matches_key = lambda: str(pattern) agent_id = self._make_agent_id(pattern) # Handle sources and sinks if pattern.monomer.name in ('__source', '__sink'): return None ...
[ "Add glyph for a PySB MonomerPattern." ]
Please provide a description of the function:def load_go_graph(go_fname): global _go_graph if _go_graph is None: _go_graph = rdflib.Graph() logger.info("Parsing GO OWL file") _go_graph.parse(os.path.abspath(go_fname)) return _go_graph
[ "Load the GO data from an OWL file and parse into an RDF graph.\n\n Parameters\n ----------\n go_fname : str\n Path to the GO OWL file. Can be downloaded from\n http://geneontology.org/ontology/go.owl.\n\n Returns\n -------\n rdflib.Graph\n RDF graph containing GO data.\n "...
Please provide a description of the function:def update_id_mappings(g): g = load_go_graph(go_owl_path) query = _prefixes + logger.info("Querying for GO ID mappings") res = g.query(query) mappings = [] for id_lit, label_lit in sorted(res, key=lambda x: x[0]): mappings.append((id_li...
[ "Compile all ID->label mappings and save to a TSV file.\n\n Parameters\n ----------\n g : rdflib.Graph\n RDF graph containing GO data.\n ", "\n SELECT ?id ?label\n WHERE {\n ?class oboInOwl:id ?id .\n ?class rdfs:label ?label\n }\n " ]
Please provide a description of the function:def get_default_ndex_cred(ndex_cred): if ndex_cred: username = ndex_cred.get('user') password = ndex_cred.get('password') if username is not None and password is not None: return username, password username = get_config('NDE...
[ "Gets the NDEx credentials from the dict, or tries the environment if None" ]
Please provide a description of the function:def send_request(ndex_service_url, params, is_json=True, use_get=False): if use_get: res = requests.get(ndex_service_url, json=params) else: res = requests.post(ndex_service_url, json=params) status = res.status_code # If response is imme...
[ "Send a request to the NDEx server.\n\n Parameters\n ----------\n ndex_service_url : str\n The URL of the service to use for the request.\n params : dict\n A dictionary of parameters to send with the request. Parameter keys\n differ based on the type of request.\n is_json : bool\...
Please provide a description of the function:def create_network(cx_str, ndex_cred=None, private=True): username, password = get_default_ndex_cred(ndex_cred) nd = ndex2.client.Ndex2('http://public.ndexbio.org', username=username, password=password) ...
[ "Creates a new NDEx network of the assembled CX model.\n\n To upload the assembled CX model to NDEx, you need to have\n a registered account on NDEx (http://ndexbio.org/) and have\n the `ndex` python package installed. The uploaded network\n is private by default.\n\n Parameters\n ----------\n ...
Please provide a description of the function:def update_network(cx_str, network_id, ndex_cred=None): server = 'http://public.ndexbio.org' username, password = get_default_ndex_cred(ndex_cred) nd = ndex2.client.Ndex2(server, username, password) try: logger.info('Getting network summary...')...
[ "Update an existing CX network on NDEx with new CX content.\n\n Parameters\n ----------\n cx_str : str\n String containing the CX content.\n network_id : str\n UUID of the network on NDEx.\n ndex_cred : dict\n A dictionary with the following entries:\n 'user': NDEx user na...
Please provide a description of the function:def set_style(network_id, ndex_cred=None, template_id=None): if not template_id: template_id = "ea4ea3b7-6903-11e7-961c-0ac135e8bacf" server = 'http://public.ndexbio.org' username, password = get_default_ndex_cred(ndex_cred) source_network = nd...
[ "Set the style of the network to a given template network's style\n\n Parameters\n ----------\n network_id : str\n The UUID of the NDEx network whose style is to be changed.\n ndex_cred : dict\n A dictionary of NDEx credentials.\n template_id : Optional[str]\n The UUID of the NDE...
Please provide a description of the function:def initialize(self, cfg_file=None, mode=None): self.sim = ScipyOdeSimulator(self.model) self.state = numpy.array(copy.copy(self.sim.initials)[0]) self.time = numpy.array(0.0) self.status = 'initialized'
[ "Initialize the model for simulation, possibly given a config file.\n\n Parameters\n ----------\n cfg_file : Optional[str]\n The name of the configuration file to load, optional.\n " ]
Please provide a description of the function:def update(self, dt=None): # EMELI passes dt = -1 so we need to handle that here dt = dt if (dt is not None and dt > 0) else self.dt tspan = [0, dt] # Run simulaton with initials set to current state res = self.sim.run(tspan=t...
[ "Simulate the model for a given time interval.\n\n Parameters\n ----------\n dt : Optional[float]\n The time step to simulate, if None, the default built-in time step\n is used.\n " ]
Please provide a description of the function:def set_value(self, var_name, value): if var_name in self.outside_name_map: var_name = self.outside_name_map[var_name] print('%s=%.5f' % (var_name, 1e9*value)) if var_name == 'Precipitation': value = 1e9*va...
[ "Set the value of a given variable to a given value.\n\n Parameters\n ----------\n var_name : str\n The name of the variable in the model whose value should be set.\n\n value : float\n The value the variable should be set to\n " ]
Please provide a description of the function:def get_value(self, var_name): if var_name in self.outside_name_map: var_name = self.outside_name_map[var_name] species_idx = self.species_name_map[var_name] return self.state[species_idx]
[ "Return the value of a given variable.\n\n Parameters\n ----------\n var_name : str\n The name of the variable whose value should be returned\n\n Returns\n -------\n value : float\n The value of the given variable in the current state\n " ]
Please provide a description of the function:def get_input_var_names(self): in_vars = copy.copy(self.input_vars) for idx, var in enumerate(in_vars): if self._map_in_out(var) is not None: in_vars[idx] = self._map_in_out(var) return in_vars
[ "Return a list of variables names that can be set as input.\n\n Returns\n -------\n var_names : list[str]\n A list of variable names that can be set from the outside\n " ]
Please provide a description of the function:def get_output_var_names(self): # Return all the variables that aren't input variables all_vars = list(self.species_name_map.keys()) output_vars = list(set(all_vars) - set(self.input_vars)) # Re-map to outside var names if needed ...
[ "Return a list of variables names that can be read as output.\n\n Returns\n -------\n var_names : list[str]\n A list of variable names that can be read from the outside\n " ]
Please provide a description of the function:def make_repository_component(self): component = etree.Element('component') comp_name = etree.Element('comp_name') comp_name.text = self.model.name component.append(comp_name) mod_path = etree.Element('module_path') ...
[ "Return an XML string representing this BMI in a workflow.\n\n This description is required by EMELI to discover and load models.\n\n Returns\n -------\n xml : str\n String serialized XML representation of the component in the\n model repository.\n " ]
Please provide a description of the function:def export_into_python(self): pkl_path = self.model.name + '.pkl' with open(pkl_path, 'wb') as fh: pickle.dump(self, fh, protocol=2) py_str = % os.path.abspath(pkl_path) py_str = textwrap.dedent(py_str) py_path = ...
[ "Write the model into a pickle and create a module that loads it.\n\n The model basically exports itself as a pickle file and a Python\n file is then written which loads the pickle file. This allows importing\n the model in the simulation workflow.\n ", "\n import pickle\n ...
Please provide a description of the function:def _map_in_out(self, inside_var_name): for out_name, in_name in self.outside_name_map.items(): if inside_var_name == in_name: return out_name return None
[ "Return the external name of a variable mapped from inside." ]