Пример #1
0
def resultGraph(graph):
    nodes = []
    for node in graph.nodes(data=True):
        node_attributes = [
            NodeAttribute(name=key, value=str(value))
            for key, value in node[1].items() if key not in ['labels', 'name']
        ]
        nodes.append(
            Node(id=str(node[0]),
                 type=[str(label) for label in node[1]['labels']],
                 name=str(node[1]['name']),
                 node_attributes=node_attributes))

    edges = []
    for edge in graph.edges(data=True):
        edge_attributes = [
            EdgeAttribute(name=key, value=str(value))
            for key, value in edge[2].items()
            if key not in ['type', 'source', 'id']
        ]
        if 'source' not in edge[2]:
            edge[2]['source'] = "NA"
        edges.append(
            Edge(type=edge[2]['type'],
                 source_id=str(edge[0]),
                 target_id=str(edge[1]),
                 provided_by=str(edge[2]['source']),
                 id=str(edge[2]['id']),
                 edge_attributes=edge_attributes))

    rg = KnowledgeGraph(nodes=nodes, edges=edges)
    return (rg)
Пример #2
0
def convert_qg_organized_kg_to_standard_kg(organized_kg: QGOrganizedKnowledgeGraph) -> KnowledgeGraph:
    standard_kg = KnowledgeGraph(nodes=dict(), edges=dict())
    for qnode_key, nodes_for_this_qnode_key in organized_kg.nodes_by_qg_id.items():
        for node_key, node in nodes_for_this_qnode_key.items():
            if node_key in standard_kg.nodes:
                standard_kg.nodes[node_key].qnode_keys.append(qnode_key)
            else:
                node.qnode_keys = [qnode_key]
                standard_kg.nodes[node_key] = node
    for qedge_key, edges_for_this_qedge_key in organized_kg.edges_by_qg_id.items():
        for edge_key, edge in edges_for_this_qedge_key.items():
            if edge_key in standard_kg.edges:
                standard_kg.edges[edge_key].qedge_keys.append(qedge_key)
            else:
                edge.qedge_keys = [qedge_key]
                standard_kg.edges[edge_key] = edge
    return standard_kg
Пример #3
0
def get_node_pairs_to_overlay(subject_qnode_key: str, object_qnode_key: str, query_graph: QueryGraph,
                              knowledge_graph: KnowledgeGraph, log: ARAXResponse) -> Set[Tuple[str, str]]:
    """
    This function determines which combinations of subject/object nodes in the KG need to be overlayed (e.g., have a
    virtual edge added between). It makes use of Resultify to determine what combinations of subject and object nodes
    may actually appear together in the same Results. (See issue #1069.) If it fails to narrow the node pairs for
    whatever reason, it defaults to returning all possible combinations of subject/object nodes.
    """
    log.debug(f"Narrowing down {subject_qnode_key}--{object_qnode_key} node pairs to overlay")
    kg_nodes_by_qg_id = get_node_ids_by_qg_id(knowledge_graph)
    kg_edges_by_qg_id = get_edge_ids_by_qg_id(knowledge_graph)
    # Grab the portion of the QG already 'expanded' (aka, present in the KG)
    sub_query_graph = QueryGraph(nodes={key:qnode for key, qnode in query_graph.nodes.items() if key in set(kg_nodes_by_qg_id)},
                                 edges={key:qedge for key, qedge in query_graph.edges.items() if key in set(kg_edges_by_qg_id)})

    # Compute results using Resultify so we can see which nodes appear in the same results
    resultifier = ARAXResultify()
    sub_response = ARAXResponse()
    sub_response.envelope = Response()
    sub_response.envelope.message = Message()
    sub_message = sub_response.envelope.message
    sub_message.query_graph = sub_query_graph
    sub_message.knowledge_graph = KnowledgeGraph(nodes=knowledge_graph.nodes.copy(),
                                                 edges=knowledge_graph.edges.copy())
    #sub_response.envelope.message = sub_message
    resultify_response = resultifier.apply(sub_response, {})

    # Figure out which node pairs appear together in one or more results
    if resultify_response.status == 'OK':
        node_pairs = set()
        for result in sub_message.results:
            subject_curies_in_this_result = {node_binding.id for key, node_binding_list in result.node_bindings.items() for node_binding in node_binding_list if
                                            key == subject_qnode_key}
            object_curies_in_this_result = {node_binding.id for key, node_binding_list in result.node_bindings.items() for node_binding in node_binding_list if
                                            key == object_qnode_key}
            pairs_in_this_result = set(itertools.product(subject_curies_in_this_result, object_curies_in_this_result))
            node_pairs = node_pairs.union(pairs_in_this_result)
        log.debug(f"Identified {len(node_pairs)} node pairs to overlay (with help of resultify)")
        if node_pairs:
            return node_pairs
    # Back up to using the old (O(n^2)) method of all combinations of subject/object nodes in the KG
    log.warning(f"Failed to narrow down node pairs to overlay; defaulting to all possible combinations")
    return set(itertools.product(kg_nodes_by_qg_id[subject_qnode_key], kg_nodes_by_qg_id[object_qnode_key]))
Пример #4
0
 def __init__(self, query_graph):
     self.query_graph = query_graph
     self.results = []
     self.knowledge_graph = KnowledgeGraph(nodes={}, edges={})
     self.nodes = {}
     self.edges = {}
Пример #5
0
    def create_envelope(self, response, describe=False):
        """
        Creates a basic empty ARAXResponse object with basic boilerplate metadata
        :return: ARAXResponse object with execution information and the new message object inside the data envelope
        :rtype: ARAXResponse
        """

        # #### Command definition for autogenerated documentation
        command_definition = {
            'dsl_command': 'create_envelope()',
            'description':
            """The `create_envelope` command creates a basic empty Response object with basic boilerplate metadata
                such as reasoner_id, schema_version, etc. filled in. This DSL command takes no arguments. This command is not explicitly
                necessary, as it is called implicitly when needed. e.g. If a DSL program begins with add_qnode(), the
                create_envelope() will be executed automatically if there is not yet a ARAXResponse. If there is already ARAXResponse in memory,
                then this command will destroy the previous one (in memory) and begin a new envelope.""",
            'parameters': {}
        }

        if describe:
            return command_definition

        #### Store the passed response object
        self.response = response

        #### Create the top-level Response object called an envelope
        response.info("Creating an empty template TRAPI Response")
        envelope = Response()
        response.envelope = envelope
        self.envelope = envelope

        # Create a Message object and place it in the envelope
        message = Message()
        response.envelope.message = message
        self.message = message

        #### Fill it with default information
        envelope.id = None
        envelope.type = "translator_reasoner_response"
        envelope.reasoner_id = "ARAX"
        envelope.tool_version = RTXConfiguration().version
        envelope.schema_version = "1.0.0"
        envelope.status = "OK"
        envelope.description = "Created empty template response"
        envelope.context = "https://raw.githubusercontent.com/biolink/biolink-model/master/context.jsonld"
        envelope.logs = response.messages
        envelope.datetime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        #### Create an empty master knowledge graph
        message.knowledge_graph = KnowledgeGraph()
        message.knowledge_graph.nodes = {}
        message.knowledge_graph.edges = {}

        #### Create an empty query graph
        message.query_graph = QueryGraph()
        message.query_graph.nodes = {}
        message.query_graph.edges = {}

        #### Create empty results
        message.results = []

        #### Return the response
        response.data['envelope'] = envelope
        return response