Domain Knowledge Graph
DKG (mira.dkg)
Construction of domain knowledge graphs.
ASKEMO (mira.dkg.askemo)
- EQUIVALENCE_TYPES = {'skos:broadBarch', 'skos:exactMatch', 'skos:narrowMatch', 'skos:relatedMatch'}
Valid equivalence annotations in ASKEMO
- SYNONYM_TYPES = {'oboInOwl:hasBroadSynonym': 'BROAD', 'oboInOwl:hasExactSynonym': 'EXACT', 'oboInOwl:hasNarrowSynonym': 'NARROW', 'oboInOwl:hasRelatedSynonym': 'RELATED', 'referenced_by_latex': 'RELATED', 'referenced_by_symbol': 'RELATED'}
Keys are values in ASKEMO and values are OBO specificities
- class Term(**data)[source]
Bases:
BaseModelA term in the ASKEMO ontology.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
Client (mira.dkg.client)
Neo4j client module.
- class Neo4jClient(url=None, user=None, password=None)[source]
Bases:
objectA client to Neo4j.
Initialize the Neo4j client.
- create_tx(query, **query_params)[source]
Run a query that creates nodes and/or relations.
- Parameters:
query (
str) – The query string to be executed.query_params – The parameters to be used in the query.
- Returns:
The result of the query
- add_node(entity)[source]
Add a node to the DKG
- Parameters:
entity – The node object that will be added to the DKG
- add_relation(relation)[source]
Add a relation to the DKG
- Parameters:
relation – The relation object that will be added to the DKG
- create_single_property_node_index(index_name, label, property_name, exist_ok=False)[source]
Create a single-property node index.
- query_nodes(query)[source]
Run a read-only query for nodes.
- Parameters:
query (
str) – The query string to be executed.- Returns:
A list of
Nodeinstances corresponding to the results of the query- Return type:
values
- search(query, limit=25, offset=0, prefixes=None, labels=None, wikidata_fallback=False)[source]
Search nodes for a given name or synonym substring.
- Parameters:
query (
str) – The query string to search (by a normalized substring search).limit (
int) – The number of results to return. Useful for pagination.offset (
int) – The offset of the entities to return. Useful for pagination.prefixes (
Union[None,str,Iterable[str]]) – A prefix or list of prefixes. If given, any result matching any of the prefixes will be retained.labels (
Union[None,str,Iterable[str]]) – A label or list of labels used for filtering results. If given, any result with any of the labels will be retained.wikidata_fallback (
bool) – If true, use wikidata for searching if DKG returns no results
- Return type:
A list of entity objects that match all of the query parameters
- get_transitive_closure(rels=None)[source]
Return transitive closure with respect to one or more relations.
Transitive closure is constructed as a set of pairs of node IDs ordered as (successor, descendant). Note that if rels are ones that point towards taxonomical parents (e.g., subclassof, part_of), then the pairs are interpreted as (taxonomical child, taxonomical ancestor).
- class Entity(**data)[source]
Bases:
BaseModelAn entity in the domain knowledge graph.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- classmethod set_link(value, validation_info)[source]
Set the value of the
linkfield based on the value of theidfield. This gets run as a post-init hook by Pydantic
- classmethod from_data(data)[source]
Create from a data dictionary as it’s stored in neo4j.
- Parameters:
data – Either a plain python dictionary or a
neo4j.graph.Nodeobject that will get unpacked. These correspond to the structure of data inside the neo4j graph, and therefore have parallel lists representing dictionaries for properties, xrefs, and synonyms.- Return type:
A MIRA entity
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
Construct (mira.dkg.construct)
Generate the nodes and edges file for the MIRA domain knowledge graph.
After these are generated, see the /docker folder in the repository for loading a neo4j instance.
Example command for local bulk import on mac with neo4j 4.x:
neo4j-admin import --database=mira --delimiter='TAB' --force --skip-duplicate-nodes=true --skip-bad-relationships=true --nodes ~/.data/mira/demo/import/nodes.tsv.gz --relationships ~/.data/mira/demo/import/edges.tsv.gz
Then, restart the neo4j service with homebrew brew services neo4j restart
- class DKGConfig(**data)[source]
Bases:
BaseModelCreate a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class UseCasePaths(use_case, config=None)[source]
Bases:
objectA configuration containing the file paths for use case-specific files.
- class NodeInfo(curie, prefix, label, synonyms, deprecated, type, definition, xrefs, alts, version, property_predicates, property_values, xref_types, synonym_types)[source]
Bases:
NamedTupleCreate new instance of NodeInfo(curie, prefix, label, synonyms, deprecated, type, definition, xrefs, alts, version, property_predicates, property_values, xref_types, synonym_types)
- extract_ontology_subtree(curie, add_subtree=False)[source]
Takes in a curie and extracts the information from the entry in its respective resource ontology to add as a node into the Epidemiology DKG.
There is an option to extract all the information from the entries under the corresponding entry’s subtree in its respective ontology. Relation information is also extracted with this option.
Execution of this method will take a few seconds as the pickled graph object has to be loaded.
Currently we only support the addition of ncbitaxon terms.
- Parameters:
- Returns:
nodes (List[dict]) – A list of node information added to the DKG, where each node is represented as a dictionary.
edges (List[dict]) – A list of edge information added to the DKG, where each edge is represented as a dictionary.
Constructing Registry (mira.dkg.construct_registry)
Constants for the MIRA Metaregistry.
Configuration Models (mira.dkg.models)
Configuration for the DKG.
- class Config(**data)[source]
Bases:
BaseModelConfiguration for a custom metaregistry instance.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class Xref(**data)[source]
Bases:
BaseModelRepresents a typed cross-reference.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class Synonym(**data)[source]
Bases:
BaseModelRepresents a typed synonym.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
Units (mira.dkg.units)
App Utilities (mira.dkg.utils)
Utilities and constants for the MIRA app.
- class MiraState(client, grounder, refinement_closure, lexical_dump, vectors)[source]
Bases:
objectRepresents the state associated with the MIRA app.
- PREFIXES = ['oboinowl', 'owl', 'rdfs', 'bfo', 'caro', 'hp', 'disdriv', 'symp', 'ido', 'vo', 'ovae', 'oae', 'trans', 'doid', 'apollosv', 'efo', 'ncit', 'cemo', 'vido', 'cido', 'idocovid19', 'idomal', 'vsmo', 'covoc', 'probonto', 'geonames']
A list of all prefixes used in MIRA
- DOCKER_FILES_ROOT = PosixPath('/sw')
The root path of the MIRA app when running in a container
Web Client (mira.dkg.web_client)
- web_client(endpoint, method, query_json=None, api_url=None)[source]
A wrapper for sending requests to the REST API and returning the results
- Parameters:
endpoint (
str) – The endpoint to send the request to.method (
Literal['get','post']) – Which method to use. Must be one of ‘post’ and ‘get’.query_json (
Union[Dict[str,Any],List[Tuple[str,Any]],None]) –The data to send with the request. This parameter must be filled if method is ‘post’. If method is ‘get’, and the endpoint expects a list, this parameter needs to be a list of tuples of key-value pairs, i.e. [(key, value)], as per the requests api: https://requests.readthedocs.io/en/latest/api/#requests.get To provide a list for one parameter, repeat the key with each value of the list.
Example: If the endpoint expect key1 to be a list and key2 to be parameter, sending [(key1, value1), (key1, value2), (key2, value3)] as query_json will result in the endpoint receiving the variables key1=[value1, value2], key2=value3
api_url (
Optional[str]) – Provide the base URL to the REST API. Use this argument to override the default set in MIRA_REST_URL or rest_url from the config file.
- Return type:
- Returns:
The data sent back from the endpoint as a json, unless the response is empty, in which case None is returned.
- get_relations_web(relations_model, api_url=None)[source]
Get relations based on the query contained in the RelationQuery model
A wrapper that call the REST API’s get_relations endpoint.
- Parameters:
- Return type:
- Returns:
If any relation exists, a list of RelationResponse models or FullRelationResponse models if a full query was requested.
Examples
To populate the RelationQuery BaseModel, follow this example:
from mira.dkg.api import RelationQuery from mira.dkg.web_client import get_relations_web relation_query = RelationQuery(target_curie="ncbitaxon:10090", relations="vo:0001243") relations = get_relations_web(relations_model=relation_query) print(relations[:5])
- get_entity_web(curie, api_url=None)[source]
Get information about an entity based on its compact URI (CURIE)
A wrapper that calls the REST API’s entity endpoint.
- Parameters:
- Return type:
- Returns:
Returns an Entity model, if the entity exists in the graph.
- get_entities_web(curies)[source]
Get information about multiple entities (e.g., their names, description synonyms, alternative identifiers, database cross-references, etc.) based on their respective compact URIs (CURIEs).
A wrapper that calls the REST API’s entities endpoint.
- get_lexical_web(api_url=None)[source]
Get lexical information for all entities in the graph
A wrapper that calls the REST API’s lexical endpoint.
- ground_web(text, namespaces=None, api_url=None)[source]
Ground text with Gilda to an ontology identifier
A wrapper that calls the REST API’s grounding POST endpoint
- Parameters:
- Return type:
Optional[GroundResults]- Returns:
If the query results in at least one grounding, a GroundResults model is returned with all the results.
- search_web(term, limit=25, offset=0, api_url=None)[source]
Get nodes based on a search to their name/synonyms
A wrapper that call the REST API’s search endpoint
- Parameters:
- Return type:
- Returns:
A list of the matching entities.
- get_transitive_closure_web(relation_types=None, api_url=None)[source]
Get a transitive closure for the given relation type(s)
- Parameters:
- Return type:
- Returns:
A set of tuples of CURIEs representing a transitive closure set for the relations of the requested type(s). The pairs are ordered as (successor, descendant). Note that if the relations are ones that point towards taxonomical parents (e.g., subclassof, part_of), then the pairs are interpreted as (taxonomical child, taxonomical ancestor).
- is_ontological_child_web(child_curie, parent_curie, api_url=None)[source]
Check if one curie is a child term of another curie
- Parameters:
child_curie (
str) – The entity, identified by its CURIE that is assumed to be a child termparent_curie (
str) – The entity, identified by its CURIE that is assumed to be a parent termapi_url (
Optional[str]) – Use this parameter to specify the REST API base url or to override the url set in the environment or the config
- Return type:
- Returns:
True if the assumption that child_curie is an ontological child of parent_curie holds
- exception MissingBaseUrlError[source]
Bases:
ValueErrorRaised when the base url for the REST API is missing