text
stringlengths
81
112k
Compute edges def compute_edges(ast: BELAst, spec: BELSpec) -> Edges: """Compute edges""" edges = [] if ast.bel_object.__class__.__name__ == "BELAst": edges.append(ast.bel_object) process_ast(edges, ast, spec) return edges
Process computed edge rule Recursively processes BELAst versus a single computed edge rule Args: edges (List[Tuple[Union[Function, str], str, Function]]): BEL Edge ASTs ast (Function): BEL Function AST rule (Mapping[str, Any]: computed edge rule def process_rule(edges: Edges, ast: Fun...
Load orthologs into ArangoDB Args: fo: file obj - orthologs file metadata: dict containing the metadata for orthologs def load_orthologs(fo: IO, metadata: dict): """Load orthologs into ArangoDB Args: fo: file obj - orthologs file metadata: dict containing the metadata for ...
Ortholog node and edge iterator def orthologs_iterator(fo, version): """Ortholog node and edge iterator""" species_list = config["bel_resources"].get("species_list", []) fo.seek(0) with gzip.open(fo, "rt") as f: for line in f: edge = json.loads(line) if "metadata" in e...
Process nanopub into edges and load into EdgeStore Args: nanopub: BEL Nanopub rules: list of compute rules to process orthologize_targets: list of species in TAX:<int> format Returns: list: of edges Edge object: { "edge": { "subject": { ...
Extract species from ast.species set of tuples (id, label) def extract_ast_species(ast): """Extract species from ast.species set of tuples (id, label)""" species_id = "None" species_label = "None" species = [ (species_id, species_label) for (species_id, species_label) in ast.species if species...
Create edges (SRO) for assertions given orthologization targets Args: assertions: list of BEL statements (SRO object) orthologize_targets: list of species in TAX:<int> format bel_version: to be used for processing assertions api_url: BEL API url endpoint to use for terminologies and...
Orthologize context Replace Species context with new orthologize target and add a annotation type of OrthologizedFrom def orthologize_context( orthologize_target: str, annotations: Mapping[str, Any] ) -> Mapping[str, Any]: """Orthologize context Replace Species context with new orthologize target and...
Migrate BEL 1 to 2.0.0 Args: bel: BEL 1 Returns: bel: BEL 2 def migrate(belstr: str) -> str: """Migrate BEL 1 to 2.0.0 Args: bel: BEL 1 Returns: bel: BEL 2 """ bo.ast = bel.lang.partialparse.get_ast_obj(belstr, "2.0.0") return migrate_ast(bo.ast).to...
Migrate BEL1 assertion into BEL 2.0.0 SRO triple def migrate_into_triple(belstr: str) -> str: """Migrate BEL1 assertion into BEL 2.0.0 SRO triple""" bo.ast = bel.lang.partialparse.get_ast_obj(belstr, "2.0.0") return migrate_ast(bo.ast).to_triple()
Convert BEL1 AST Function to BEL2 AST Function def convert(ast): """Convert BEL1 AST Function to BEL2 AST Function""" if ast and ast.type == "Function": # Activity function conversion if ( ast.name != "molecularActivity" and ast.name in spec["namespaces"]["Activity"]["l...
Convert BEL1 tloc() to BEL2 def convert_tloc(ast): """Convert BEL1 tloc() to BEL2""" from_loc_arg = ast.args[1] to_loc_arg = ast.args[2] from_loc = Function("fromLoc", spec, parent_function=ast) from_loc.add_argument( NSArg(from_loc_arg.namespace, from_loc_arg.value, parent_function=from_l...
Convert BEL1 activities to BEL2 act() def convert_activity(ast): """Convert BEL1 activities to BEL2 act()""" if len(ast.args) > 1: log.error(f"Activity should not have more than 1 argument {ast.to_string()}") p_arg = ast.args[0] # protein argument print("p_arg", p_arg) ma_arg = Function(...
Update BEL1 pmod() protein modification term def convert_pmod(pmod): """Update BEL1 pmod() protein modification term""" if pmod.args[0].value in spec["bel1_migration"]["protein_modifications"]: pmod.args[0].value = spec["bel1_migration"]["protein_modifications"][ pmod.args[0].value ...
Convert BEL1 fus() to BEL2 fus() def convert_fus(ast): """Convert BEL1 fus() to BEL2 fus()""" parent_fn_name = ast.name_short prefix_list = {"p": "p.", "r": "r.", "g": "c."} prefix = prefix_list[parent_fn_name] fus1_ns = ast.args[0].namespace fus1_val = ast.args[0].value arg_fus = ast.ar...
Convert BEL1 sub() to BEL2 var() def convert_sub(sub): """Convert BEL1 sub() to BEL2 var()""" args = sub.args (ref_aa, pos, new_aa) = args parent_fn_name = sub.parent_function.name_short prefix_list = {"p": "p.", "r": "r.", "g": "c."} prefix = prefix_list[parent_fn_name] new_var_arg = f'...
Convert BEL1 trunc() to BEL2 var() def convert_trunc(trunc): """Convert BEL1 trunc() to BEL2 var()""" parent_fn_name = trunc.parent_function.name_short prefix_list = {"p": "p.", "r": "r.", "g": "c."} prefix = prefix_list[parent_fn_name] new_var_arg = f'"truncated at {trunc.args[0].value}"' n...
Get username/password Use provided username and password OR in config OR blank in that order def get_user_creds(username, password): """Get username/password Use provided username and password OR in config OR blank in that order """ username = utils.first_true( [username, config["bel_api"...
Get arango client and edgestore db handle def get_client(host=None, port=None, username=None, password=None, enable_logging=True): """Get arango client and edgestore db handle""" host = utils.first_true( [host, config["bel_api"]["servers"]["arangodb_host"], "localhost"] ) port = utils.first_tr...
Get Edgestore arangodb database handle Args: client (arango.client.ArangoClient): Description username (None, optional): Description password (None, optional): Description edgestore_db_name (str, optional): Description edgestore_edges_name (str, optional): Description ...
Get BEL namespace arango db handle def get_belns_handle(client, username=None, password=None): """Get BEL namespace arango db handle""" (username, password) = get_user_creds(username, password) sys_db = client.db("_system", username=username, password=password) # Create a new database named "belns" ...
Get BEL API arango db handle def get_belapi_handle(client, username=None, password=None): """Get BEL API arango db handle""" (username, password) = get_user_creds(username, password) sys_db = client.db("_system", username=username, password=password) # Create a new database named "belapi" try: ...
Delete Arangodb database def delete_database(client, db_name, username=None, password=None): """Delete Arangodb database """ (username, password) = get_user_creds(username, password) sys_db = client.db("_system", username=username, password=password) try: return sys_db.delete_database(d...
Batch load documents Args: db: ArangoDB client database handle doc_iterator: function that yields (collection_name, doc_key, doc) on_duplicate: defaults to replace, but can be error, update, replace or ignore https://python-driver-for-arangodb.readthedocs.io/en/master/specs.html?h...
Remove illegal chars from potential arangodb _key (id) Args: _id (str): id to be used as arangodb _key Returns: (str): _key value with illegal chars removed def arango_id_to_key(_id): """Remove illegal chars from potential arangodb _key (id) Args: _id (str): id to be used as ...
Load BEL Resource file Forceupdate will create a new index in Elasticsearch regardless of whether an index with the resource version already exists. Args: resource_url: URL from which to download the resource to load into the BEL API forceupdate: force full update - e.g. don't leave Elasti...
Get term(s) using term_id - given term_id may match multiple term records Term ID has to match either the id, alt_ids or obsolete_ids def get_terms(term_id): """Get term(s) using term_id - given term_id may match multiple term records Term ID has to match either the id, alt_ids or obsolete_ids """ ...
Get equivalents given ns:id Args: term_id (str): term id Returns: List[Mapping[str, Union[str, bool]]]: e.g. [{'term_id': 'HGNC:5', 'namespace': 'HGNC'}, 'primary': False] def get_equivalents(term_id: str) -> List[Mapping[str, Union[str, bool]]]: """Get equivalents given ns:id Args:...
Get normalized term def get_normalized_term(term_id: str, equivalents: list, namespace_targets: dict) -> str: """Get normalized term""" if equivalents and len(equivalents) > 0: for start_ns in namespace_targets: if re.match(start_ns, term_id): for target_ns in namespace_tar...
Get term labels given term ids This only takes the first term returned for a term_id so use the unique term_id for a term not an alternate id that might not be unique. def get_labels(term_ids: list) -> dict: """Get term labels given term ids This only takes the first term returned for a term_id so us...
Get normalized terms - canonical/decanonical forms def get_normalized_terms(term_id: str) -> dict: """Get normalized terms - canonical/decanonical forms""" canonical = term_id decanonical = term_id canonical_namespace_targets = config["bel"]["lang"]["canonical"] decanonical_namespace_targets = co...
Generate SOAP parameters. def _get_params(self): """ Generate SOAP parameters. """ params = {'accountNumber': self._service.accountNumber} # Include object variables that are in field_order for key, val in self.__dict__.iteritems(): if key i...
Generates a hash based on the specific fields for the method. def _generate_hash(self): """ Generates a hash based on the specific fields for the method. """ self.hash = None str_hash = '' for key, val in self._get_params().iteritems(): str_...
Make the SOAP request and convert the result to a dictionary. def _send_request(self): """ Make the SOAP request and convert the result to a dictionary. """ # Generate the hash variable and parameters self._generate_hash() params = self._get_params() ...
Custom client factory to set proxy options. def client_factory(self): """ Custom client factory to set proxy options. """ if self._service.production: url = self.production_url else: url = self.testing_url proxy_options = dict() ...
Prepares the action for a keyboard combination, also filters another "strange" actions declared by the user. def get_combination_action(combination): """ Prepares the action for a keyboard combination, also filters another "strange" actions declared by the user. """ accepted_actions = ('link', ...
Process passed dict with key combinations or the HOTKEYS dict from settings. def get_processed_hotkeys(hotkeys=None): """ Process passed dict with key combinations or the HOTKEYS dict from settings. """ hotkeys = hotkeys or ks_settings.HOTKEYS processed_hotkeys = AutoVivification() if n...
Calculates the list of key codes from a string with key combinations. Ex: 'CTRL+A' will produce the output (17, 65) def get_key_codes(keys): """ Calculates the list of key codes from a string with key combinations. Ex: 'CTRL+A' will produce the output (17, 65) """ keys = keys.strip().upper().sp...
Parse and semantically validate BEL statement Parses a BEL statement given as a string and returns an AST, Abstract Syntax Tree (defined in ast.py) if the statement is valid, self.parse_valid. Else, the AST attribute is None and there will be validation error messages in self.validation_message...
Takes an AST and returns a canonicalized BEL statement string. Args: namespace_targets (Mapping[str, List[str]]): override default canonicalization settings of BEL.bio API api_url - see {api_url}/status to get default canonicalization settings Returns: BEL: retu...
Adds canonical and decanonical values to NSArgs in AST This prepares the AST object for (de)canonicalization def collect_nsarg_norms(self): """Adds canonical and decanonical values to NSArgs in AST This prepares the AST object for (de)canonicalization """ start_time = datetime...
Orthologize BEL AST to given species_id Will return original entity (ns:value) if no ortholog found. Args: species_id (str): species id to convert genes/rna/proteins into Returns: BEL: returns self def orthologize(self, species_id: str) -> "BEL": """Orthologiz...
Add NSArg orthologs for given species (TAX:<number format) This will add orthologs to the AST for all of the given species (as available). NOTE: This will run self.collect_nsarg_norms() first if not already available as we need the canonical forms of the NSArgs def collect_orthologs(self, spe...
Computed edges from primary BEL statement Takes an AST and generates all computed edges based on BEL Specification YAML computed signatures. Will run only the list of computed edge rules if given. Args: rules (list): a list of rules to filter; only the rules in this list will be ap...
Convert AST object to BEL triple Args: fmt (str): short, medium, long formatted BEL statements short = short function and short relation format medium = short function and long relation format long = long function and long relation format Ret...
Convert AST object to tree view of BEL AST Returns: printed tree of BEL AST def print_tree(self) -> str: """Convert AST object to tree view of BEL AST Returns: printed tree of BEL AST """ if self.ast: return self.ast.print_tree(ast_obj=self...
Convert Tatsu AST dictionary to BEL AST object Args: ast_dict (Mapping[str, Any]) Returns: BELAst: object representing the BEL Statement AST def ast_dict_to_objects(ast_dict: Mapping[str, Any], bel_obj) -> BELAst: """Convert Tatsu AST dictionary to BEL AST object Args: ast_di...
Convert AST object to string Args: fmt (str): short, medium, long formatted BEL statements short = short function and short relation format medium = short function and long relation format long = long function and long relation format cano...
Convert AST object to BEL triple Args: fmt (str): short, medium, long formatted BEL statements short = short function and short relation format medium = short function and long relation format long = long function and long relation format Ret...
Convert AST object to tree view of BEL AST Returns: prints tree of BEL AST to STDOUT def print_tree(self, ast_obj=None): """Convert AST object to tree view of BEL AST Returns: prints tree of BEL AST to STDOUT """ if not ast_obj: ast_obj = s...
Convert AST object to string Args: fmt (str): short, medium, long formatted BEL statements short = short function and short relation format medium = short function and long relation format long = long function and long relation format Returns...
Generate subcomponents of the BEL subject or object These subcomponents are used for matching parts of a BEL subject or Object in the Edgestore. Args: AST subcomponents: Pass an empty list to start a new subcomponents request Returns: List[str]: su...
Deprecated def change_nsvalue(self, namespace, value): """Deprecated""" self.namespace = namespace self.value = value
Update Namespace and valueast. Args: nsval: e.g. HGNC:AKT1 ns: namespace val: value of entity def update_nsval( self, *, nsval: str = None, ns: str = None, val: str = None ) -> None: """Update Namespace and valueast. Args: nsval: e.g...
Decanonical ortholog name used def orthologize(self, ortho_species_id, belast): """Decanonical ortholog name used""" if ( self.orthologs and ortho_species_id in self.orthologs and ortho_species_id != self.species_id ): self.orthology_species = or...
Convert CSV str to list def convert_csv_str_to_list(csv_str: str) -> list: """Convert CSV str to list""" csv_str = re.sub("^\s*{", "", csv_str) csv_str = re.sub("}\s*$", "", csv_str) r = csv.reader([csv_str]) row = list(r)[0] new = [] for col in row: col = re.sub('^\s*"?\s*', "", c...
Parse BEL Script Citation string into nanopub_bel citation object def process_citation(citation_str: str) -> dict: """Parse BEL Script Citation string into nanopub_bel citation object""" citation_obj = {} citation_list = convert_csv_str_to_list(citation_str) (citation_type, name, doc_id, pub_date, au...
Split bel statement into subject, relation, object tuple def split_bel_stmt(stmt: str, line_num) -> tuple: """Split bel statement into subject, relation, object tuple""" m = re.match(f"^(.*?\))\s+([a-zA-Z=\->\|:]+)\s+([\w(]+.*?)$", stmt, flags=0) if m: return (m.group(1), m.group(2), m.group(3)) ...
Yield nanopub object def yield_nanopub(assertions, annotations, line_num): """Yield nanopub object""" if not assertions: return {} anno = copy.deepcopy(annotations) evidence = anno.pop("evidence", None) stmt_group = anno.pop("statement_group", None) citation = anno.pop("citation", No...
Process SET DOCUMENT line in BEL script def process_documentline(line, nanopubs_metadata): """Process SET DOCUMENT line in BEL script""" matches = re.match('SET DOCUMENT\s+(\w+)\s+=\s+"?(.*?)"?$', line) key = matches.group(1) val = matches.group(2) nanopubs_metadata[key] = val return nanopubs...
Process DEFINE line in BEL script def process_definition(line, nanopubs_metadata): """Process DEFINE line in BEL script""" matches = re.match('DEFINE\s+(\w+)\s+(\w+)\s+AS\s+URL\s+"(.*?)"\s*$', line) if matches: def_type = matches.group(1).lower() if def_type == "namespace": def...
Process UNSET lines in BEL Script def process_unset(line, annotations): """Process UNSET lines in BEL Script""" matches = re.match('UNSET\s+"?(.*?)"?\s*$', line) if matches: val = matches.group(1) if val == "ALL" or val == "STATEMENT_GROUP": annotations = {} elif re.mat...
Convert annotations into nanopub_bel annotations format def process_set(line, annotations): """Convert annotations into nanopub_bel annotations format""" matches = re.match('SET\s+(\w+)\s*=\s*"?(.*?)"?\s*$', line) key = None if matches: key = matches.group(1) val = matches.group(2) ...
Convert any multi-line SET statements into single line SET statements def preprocess_belscript(lines): """ Convert any multi-line SET statements into single line SET statements""" set_flag = False for line in lines: if set_flag is False and re.match("SET", line): set_flag = True ...
Lines from the BELScript - can be an iterator or list yields Nanopubs in nanopubs_bel-1.0.0 format def parse_belscript(lines): """Lines from the BELScript - can be an iterator or list yields Nanopubs in nanopubs_bel-1.0.0 format """ nanopubs_metadata = {} annotations = {} assertions = []...
this method reference from httprunner def __stringify_body(self, request_or_response): ''' this method reference from httprunner ''' headers = self.__track_info['{}_headers'.format(request_or_response)] body = self.__track_info.get('{}_body'.format(request_or_response)) if isi...
set dynamic value from the string data of response @param name: glob parameter name @param regx: re._pattern_type e.g. DyStrData("a",re.compile('123')) def DyStrData(cls,name, regx, index = 0): ''' set dynamic value from the string data of response @par...
set dynamic value from the json data of response @param name: glob parameter name @param sequence: sequence for the json e.g. result={"a":1, "b":[1,2,3,4], "c":{"d":5,"e":6}, "f":{"g":[7,8,9]}, "h":[{"i":10,"j"...
Read file and generate nanopubs If filename has *.gz, will read as a gzip file If filename has *.jsonl*, will parsed as a JSONLines file IF filename has *.json*, will be parsed as a JSON file If filename has *.yaml* or *.yml*, will be parsed as a YAML file Args: filename (str): filename t...
Create Nanopubs output filehandle \b If output fn is '-' will write JSONlines to STDOUT If output fn has *.gz, will written as a gzip file If output fn has *.jsonl*, will written as a JSONLines file IF output fn has *.json*, will be written as a JSON file If output fn has *.yaml* or *.yml*, wi...
Write edges to file Args: edges (Mapping[str, Any]): in edges JSON Schema format filename (str): filename to write jsonlines (bool): output in JSONLines format? gzipflag (bool): create gzipped file? yaml (bool): create yaml file? def write_edges( edges: Mapping[str, Any...
Add index alias to index_name def add_index_alias(es, index_name, alias_name): """Add index alias to index_name""" es.indices.put_alias(index=index_name, name=terms_alias)
Delete the terms index def delete_index(es, index_name: str): """Delete the terms index""" if not index_name: log.warn("No index name given to delete") return None result = es.indices.delete(index=index_name) return result
Create terms index def create_terms_index(es, index_name: str): """Create terms index""" with open(mappings_terms_fn, "r") as f: mappings_terms = yaml.load(f, Loader=yaml.SafeLoader) try: es.indices.create(index=index_name, body=mappings_terms) except Exception as e: log.erro...
Delete all terms indexes def delete_terms_indexes(es, index_name: str = "terms_*"): """Delete all terms indexes""" try: es.indices.delete(index=index_name) except Exception as e: log.error(f"Could not delete all terms indices: {e}")
Bulk load docs Args: es: elasticsearch handle docs: Iterator of doc objects - includes index_name def bulk_load_docs(es, docs): """Bulk load docs Args: es: elasticsearch handle docs: Iterator of doc objects - includes index_name """ chunk_size = 200 try: ...
Semantically validate BEL AST Add errors and warnings to bel_obj.validation_messages Error Levels are similar to log levels - selecting WARNING includes both WARNING and ERROR, selecting ERROR just includes ERROR Args: bo: main BEL language object error_level: return ERRORs only or al...
Recursively validate function signatures Determine if function matches one of the available signatures. Also, 1. Add entity types to AST NSArg, e.g. Abundance, ... 2. Add optional to AST Arg (optional means it is not a fixed, required argument and needs to be sorted for canonicalization, ...
Check function args - return message if function args don't match function signature Called from validate_functions We have following types of arguments to validate: 1. Required, position_dependent arguments, e.g. p(HGNC:AKT1), NSArg HGNC:AKT1 is required and must be first argument 2. Optional...
Recursively validate arg (NSArg and StrArg) values Check that NSArgs are found in BELbio API and match appropriate entity_type. Check that StrArgs match their value - either default namespace or regex string Generate a WARNING if not. Args: bo: bel object Returns: bel object def...
Get belbio configuration from files def get_belbio_conf_files(): """Get belbio configuration from files """ home = os.path.expanduser("~") cwd = os.getcwd() belbio_conf_fp, belbio_secrets_fp = "", "" env_conf_dir = os.getenv("BELBIO_CONF", "").rstrip("/") conf_paths = [ f"{cwd}/...
Load the configuration def load_configuration(): """Load the configuration""" (belbio_conf_fp, belbio_secrets_fp) = get_belbio_conf_files() log.info(f"Using conf: {belbio_conf_fp} and secrets files: {belbio_secrets_fp} ") config = {} if belbio_conf_fp: with open(belbio_conf_fp, "r") as f:...
Get versions of bel modules and tools def get_versions(config) -> dict: """Get versions of bel modules and tools""" # Collect bel package version try: import bel.__version__ config["bel"]["version"] = bel.__version__.__version__ except KeyError: config["bel"] = {"version": bel...
Override config with environment variables Environment variables have to be prefixed with BELBIO_ which will be stripped before splitting on '__' and lower-casing the environment variable name that is left into keys for the config dictionary. Example: BELBIO_BEL_API__SERVERS__API_URL=http:...
Override config with additional configuration in override_config or override_config_fn Used in script to merge CLI options with Config Args: config: original configuration override_config: new configuration to override/extend current config override_config_fn: new configuration filenam...
Recursively merge two dictionaries Update two dicts of dicts recursively, if either mapping has leaves that are non-dicts, the second's leaf overwrites the first's. import collections import functools e.g. functools.reduce(rec_merge, (d1, d2, d3, d4)) def rec_merge(d1, d2): """ Recursive...
Load terms into Elasticsearch and ArangoDB Forceupdate will create a new index in Elasticsearch regardless of whether an index with the resource version already exists. Args: fo: file obj - terminology file metadata: dict containing the metadata for terminology forceupdate: force f...
Add index_name to term documents for bulk load def terms_iterator_for_elasticsearch(fo: IO, index_name: str): """Add index_name to term documents for bulk load""" species_list = config["bel_resources"].get("species_list", []) fo.seek(0) # Seek back to beginning of file with gzip.open(fo, "rt") as f:...
Lowercase the term value (not the namespace prefix) Args: term_id (str): term identifier with namespace prefix, e.g. MESH:Atherosclerosis Returns: str: lowercased, e.g. MESH:atherosclerosis def lowercase_term_id(term_id: str) -> str: """Lowercase the term value (not the namespace prefix) ...
Needed for things like abstracts which have internal tags (see PMID:27822475) def node_text(node): """Needed for things like abstracts which have internal tags (see PMID:27822475)""" if node.text: result = node.text else: result = "" for child in node: if child.tail is not None...
Get Pubtator Bioconcepts from Pubmed Abstract Re-configure the denotations into an annotation dictionary format and collapse duplicate terms so that their spans are in a list. def get_pubtator(pmid): """Get Pubtator Bioconcepts from Pubmed Abstract Re-configure the denotations into an annotation dict...
Create pub_date from what Pubmed provides in Journal PubDate entry def process_pub_date(year, mon, day): """Create pub_date from what Pubmed provides in Journal PubDate entry """ pub_date = None if year and re.match("[a-zA-Z]+", mon): pub_date = datetime.datetime.strptime( f"{year}...
Get pubmed xml for pmid and convert to JSON Remove MESH terms if they are duplicated in the compound term set ArticleDate vs PubDate gets complicated: https://www.nlm.nih.gov/bsd/licensee/elements_descriptions.html see <ArticleDate> and <PubDate> Only getting pub_year at this point from the <PubDate> elem...
Enhance pubmed namespace IDs Add additional entity and annotation types to annotations Use preferred id for namespaces as needed Add strings from Title, Abstract matching Pubtator BioConcept spans NOTE - basically duplicated code with bel_api:api.services.pubmed Args: pubmed Returns:...
Get fully annotated pubmed doc with Pubtator and full entity/annotation_types Args: pmid: Pubmed PMID Returns: Mapping[str, Any]: pubmed dictionary def get_pubmed_for_beleditor(pmid: str) -> Mapping[str, Any]: """Get fully annotated pubmed doc with Pubtator and full entity/annotation_type...
Get orthologs for given gene_id and species Canonicalize prior to ortholog query and decanonicalize the resulting ortholog Args: canonical_gene_id: canonical gene_id for which to retrieve ortholog species: target species for ortholog - tax id format TAX:<number> Returns: List[...
Normalize strings with booleans into Python types. def normalize_value(val): """ Normalize strings with booleans into Python types. """ if val is not None: if val.lower() == 'false': val = False elif val.lower() == 'true': val = True return val
Normalizes the values in a dictionary recursivly. def normalize_dictionary_values(dictionary): """ Normalizes the values in a dictionary recursivly. """ for key, val in dictionary.iteritems(): if isinstance(val, dict): dictionary[key] = normalize_dictionary_values(val) ...
Wrapper for requests.get(url) Args: url: url to retrieve params: query string parameters timeout: allow this much time for the request and time it out if over cache: Cache for up to a day unless this is false Returns: Requests Result obj or None if timed out def get_ur...
Return time in milliseconds from start_time def timespan(start_time): """Return time in milliseconds from start_time""" timespan = datetime.datetime.now() - start_time timespan_ms = timespan.total_seconds() * 1000 return timespan_ms