Example #1
0
def test_example1():
    query_graph = {
        "edges": {
            "e00": {
                "subject": "n00",
                "object": "n01"
            },
            "e01": {
                "subject": "n00",
                "object": "n01",
                "predicate": "biolink:contraindicated_for",
                "exclude": True
            }
        },
        "nodes": {
            "n00": {
                "id": "MONDO:0001627",
                "category": "biolink:Disease"
            },
            "n01": {
                "category": "biolink:ChemicalSubstance"
            }
        }
    }

    from ARAX_messenger import ARAXMessenger
    response = ARAXResponse()
    messenger = ARAXMessenger()
    messenger.create_envelope(response)

    response.envelope.message.query_graph = QueryGraph().from_dict(query_graph)

    query_graph_info = QueryGraphInfo()
    result = query_graph_info.assess(response.envelope.message)
    response.merge(result)
    if result.status != 'OK':
        print(response.show(level=ARAXResponse.DEBUG))
        return response

    query_graph_info_dict = {
        'n_nodes': query_graph_info.n_nodes,
        'n_edges': query_graph_info.n_edges,
        'is_bifurcated_graph': query_graph_info.is_bifurcated_graph,
        'start_node': query_graph_info.start_node,
        'node_info': query_graph_info.node_info,
        'edge_info': query_graph_info.edge_info,
        'node_order': query_graph_info.node_order,
        'edge_order': query_graph_info.edge_order,
        'node_category_map': query_graph_info.node_category_map,
        'edge_predicate_map': query_graph_info.edge_predicate_map,
    }
    print(
        json.dumps(ast.literal_eval(repr(query_graph_info_dict)),
                   sort_keys=True,
                   indent=2))
Example #2
0
def main():

    test_example1()
    return

    #### Create a response object
    response = ARAXResponse()

    #### Create an ActionsParser object
    from actions_parser import ActionsParser
    actions_parser = ActionsParser()

    #### Set a simple list of actions
    actions_list = [
        "filter(start_node=1, maximum_results=10, minimum_confidence=0.5)",
        "return(message=true,store=false)"
    ]

    #### Parse the action_list and print the result
    result = actions_parser.parse(actions_list)
    response.merge(result)
    if result.status != 'OK':
        print(response.show(level=ARAXResponse.DEBUG))
        return response
    actions = result.data['actions']

    #### Read message #2 from the database. This should be the acetaminophen proteins query result message
    sys.path.append(
        os.path.dirname(os.path.abspath(__file__)) + "/../../UI/Feedback")
    from RTXFeedback import RTXFeedback
    araxdb = RTXFeedback()
    message_dict = araxdb.getMessage(2)

    #### The stored message comes back as a dict. Transform it to objects
    from ARAX_messenger import ARAXMessenger
    message = ARAXMessenger().from_dict(message_dict)
    #print(json.dumps(message.to_dict(),sort_keys=True,indent=2))

    #### Create a filter object and use it to apply action[0] from the list
    query_graph_info = QueryGraphInfo()
    result = query_graph_info.assess(message)
    response.merge(result)
    if result.status != 'OK':
        print(response.show(level=ARAXResponse.DEBUG))
        return response

    query_graph_info_dict = {
        'n_nodes': query_graph_info.n_nodes,
        'n_edges': query_graph_info.n_edges,
        'is_bifurcated_graph': query_graph_info.is_bifurcated_graph,
        'start_node': query_graph_info.start_node,
        'node_info': query_graph_info.node_info,
        'edge_info': query_graph_info.edge_info,
        'node_order': query_graph_info.node_order,
        'edge_order': query_graph_info.edge_order,
        'node_category_map': query_graph_info.node_category_map,
        'edge_predicate_map': query_graph_info.edge_predicate_map,
    }
    print(
        json.dumps(ast.literal_eval(repr(query_graph_info_dict)),
                   sort_keys=True,
                   indent=2))
Example #3
0
def main():

    #### Create a response object that contains the final results of our efforts
    response = ARAXResponse()
    #### Setting the output to STDERR will write out information as we go along in addition to supplying it with the response
    #ARAXResponse.output = 'STDERR'

    #### Create the ARAXMessenger
    messenger = ARAXMessenger()

    #### Test fetch_message()
    if False:
        messenger = ARAXMessenger()
        result = messenger.apply_fetch_message(
            messenger.message,
            {'uri': 'https://arax.ncats.io/api/arax/v1.0/message/1'})
        response.merge(result)
        if result.status != 'OK':
            print(response.show(level=ARAXResponse.DEBUG))
            return response
        message = messenger.message
        print(response.show(level=ARAXResponse.DEBUG))
        #print(json.dumps(message.to_dict(),sort_keys=True,indent=2))
        return

    #### Create an envelope in which to work
    messenger.create_envelope(response)
    if response.status != 'OK':
        print(response.show(level=ARAXResponse.DEBUG))
        return response
    message = response.envelope.message

    #### Some qnode examples
    parameters_sets = [
        {
            'id': 'DOID:9281'
        },
        {
            'id': 'Orphanet:673'
        },
        {
            'name': 'acetaminophen',
            'category': 'biolink:ChemicalSubstance'
        },
        {
            'id': 'NCIT:C198'
        },
        {
            'id': 'UMLS:C4710278'
        },
        {
            'category': 'biolink:Protein',
            'key': 'n10'
        },
        {
            'id': ['UniProtKB:P14136', 'UniProtKB:P35579']
        },
        {
            'id': ['UniProtKB:P14136', 'UniProtKB:P35579'],
            'is_set': 'false'
        },
    ]

    for parameter in parameters_sets:
        #### Add a QNode
        messenger.add_qnode(response, parameter)
        if response.status != 'OK':
            print(response.show(level=ARAXResponse.DEBUG))
            return response

    #### Some qedge examples
    parameters_sets = [
        {
            'subject': 'n00',
            'object': 'n01'
        },
        {
            'subject': 'n01',
            'object': 'n10',
            'predicate': 'treats'
        },
    ]

    for parameter in parameters_sets:
        #### Add a QEdge
        messenger.add_qedge(response, parameter)
        if response.status != 'OK':
            print(response.show(level=ARAXResponse.DEBUG))
            return response

    #### Delete one of the edges
    messenger.remove_qedge(response, {'key': 'e00'})
    if response.status != 'OK':
        print(response.show(level=ARAXResponse.DEBUG))
        return response

    #### Show the final result
    print(response.show(level=ARAXResponse.DEBUG))
    print(json.dumps(response.envelope.to_dict(), sort_keys=True, indent=2))
Example #4
0
def test_example1():

    test_query_graphs = [
        {
            "description": "Two nodes, one edge linking them, 1 CURIE",
            "nodes": {
                "n00": {
                    "ids": ["MONDO:0001627"]
                },
                "n01": {
                    "categories": ["biolink:ChemicalEntity"]
                }
            },
            "edges": {
                "e00": {
                    "subject": "n00",
                    "object": "n01",
                    "predicates": ["biolink:physically_interacts_with"]
                }
            }
        },
        {
            "description":
            "Two nodes, two edges linking them, 1 CURIE, one of which is excluded",
            "nodes": {
                "n00": {
                    "ids": ["MONDO:0001627"]
                },
                "n01": {
                    "categories": ["biolink:ChemicalEntity"]
                }
            },
            "edges": {
                "e00": {
                    "subject": "n00",
                    "object": "n01"
                },
                "e01": {
                    "subject": "n00",
                    "object": "n01",
                    "predicates": ["biolink:contraindicated_for"],
                    "exclude": True
                }
            }
        },
        {
            "description":
            "Two nodes, one edge linking them, both nodes are CURIEs",
            "nodes": {
                "n00": {
                    "ids": ["MONDO:0001627"]
                },
                "n01": {
                    "ids": ["CHEMBL.COMPOUND:CHEMBL112"]
                }
            },
            "edges": {
                "e00": {
                    "subject": "n00",
                    "object": "n01"
                }
            }
        },
        {
            "description":
            "Three nodes, 2 edges, 1 CURIE, simple linear chain",
            "nodes": {
                "n00": {
                    "ids": ["MONDO:0001627"]
                },
                "n01": {
                    "categories": ["biolink:ChemicalEntity"]
                },
                "n02": {
                    "categories": ["biolink:Protein"]
                }
            },
            "edges": {
                "e00": {
                    "subject": "n00",
                    "object": "n01",
                    "predicates": ["biolink:physically_interacts_with"]
                },
                "e01": {
                    "subject": "n01",
                    "object": "n02"
                }
            }
        },
        {
            "description":
            "Three nodes, 2 edges, but the CURIE is in the middle. What does that even mean?",
            "nodes": {
                "n00": {
                    "categories": ["biolink:ChemicalEntity"]
                },
                "n01": {
                    "ids": ["MONDO:0001627"]
                },
                "n02": {
                    "categories": ["biolink:Protein"]
                }
            },
            "edges": {
                "e00": {
                    "subject": "n00",
                    "object": "n01",
                    "predicates": ["biolink:physically_interacts_with"]
                },
                "e01": {
                    "subject": "n01",
                    "object": "n02"
                }
            }
        },
        {
            "description": "Four nodes, 3 edges, 1 CURIE, simple linear chain",
            "nodes": {
                "n00": {
                    "ids": ["MONDO:0001627"]
                },
                "n01": {
                    "categories": ["biolink:ChemicalEntity"]
                },
                "n02": {
                    "categories": ["biolink:Protein"]
                },
                "n03": {
                    "categories": ["biolink:Disease"]
                }
            },
            "edges": {
                "e00": {
                    "subject": "n00",
                    "object": "n01",
                    "predicates": ["biolink:physically_interacts_with"]
                },
                "e01": {
                    "subject": "n01",
                    "object": "n02"
                },
                "e02": {
                    "subject": "n02",
                    "object": "n03"
                }
            }
        },
        {
            "description": "Two nodes, one edge linking them, 0 CURIEs",
            "nodes": {
                "n00": {
                    "categories": ["biolink:Drug"]
                },
                "n01": {
                    "categories": ["biolink:ChemicalEntity"]
                }
            },
            "edges": {
                "e00": {
                    "subject": "n00",
                    "object": "n01",
                    "predicates": ["biolink:physically_interacts_with"]
                }
            }
        },
        {
            "description": "One node only",
            "nodes": {
                "n00": {
                    "ids": ["MONDO:0001627"]
                }
            },
            "edges": {}
        },
    ]

    from ARAX_messenger import ARAXMessenger

    for test_query_graph in test_query_graphs:
        response = ARAXResponse()
        messenger = ARAXMessenger()
        messenger.create_envelope(response)

        print(
            '=================================================================='
        )
        description = test_query_graph['description']
        del test_query_graph['description']
        print(f"Query Graph '{description}'")

        response.envelope.message.query_graph = QueryGraph().from_dict(
            test_query_graph)

        query_graph_info = QueryGraphInfo()
        result = query_graph_info.assess(response.envelope.message)
        response.merge(result)
        if result.status != 'OK':
            print(response.show(level=ARAXResponse.DEBUG))
            return response

        query_graph_info_dict = {
            'n_nodes':
            query_graph_info.n_nodes,
            'n_edges':
            query_graph_info.n_edges,
            'is_bifurcated_graph':
            query_graph_info.is_bifurcated_graph,
            'start_node':
            query_graph_info.start_node['key'],
            'simple_query_graph_template':
            query_graph_info.query_graph_templates['simple'],
            #'start_node': query_graph_info.start_node,
            #'node_info': query_graph_info.node_info,
            #'edge_info': query_graph_info.edge_info,
            #'node_order': query_graph_info.node_order,
            #'edge_order': query_graph_info.edge_order,
            #'node_category_map': query_graph_info.node_category_map,
            #'edge_predicate_map': query_graph_info.edge_predicate_map,
        }
        print(
            json.dumps(ast.literal_eval(repr(query_graph_info_dict)),
                       sort_keys=True,
                       indent=2))
Example #5
0
def main():

    #### Create a response object
    response = ARAXResponse()

    #### Create an ActionsParser object
    from actions_parser import ActionsParser
    actions_parser = ActionsParser()

    #### Set a simple list of actions
    actions_list = [
        "filter(start_node=1, maximum_results=10, minimum_confidence=0.5)",
        "return(message=true,store=false)"
    ]

    #### Parse the action_list and print the result
    result = actions_parser.parse(actions_list)
    response.merge(result)
    if result.status != 'OK':
        print(response.show(level=ARAXResponse.DEBUG))
        return response
    actions = result.data['actions']

    #### Read message #2 from the database. This should be the acetaminophen proteins query result message
    sys.path.append(
        os.path.dirname(os.path.abspath(__file__)) + "/../../UI/Feedback")
    from RTXFeedback import RTXFeedback
    araxdb = RTXFeedback()
    message_dict = araxdb.getMessage(2)

    #### The stored message comes back as a dict. Transform it to objects
    sys.path.append(
        os.path.dirname(os.path.abspath(__file__)) +
        "/../OpenAPI/python-flask-server/")
    from swagger_server.models.message import Message
    message = Message().from_dict(message_dict)

    #### Create a filter object and use it to apply action[0] from the list
    filter = ARAXFilter()
    result = filter.apply(message, actions[0]['parameters'])
    response.merge(result)
    if result.status != 'OK':
        print(response.show(level=ARAXResponse.DEBUG))
        return response
    response.data = result.data

    #### Show the final message
    print(response.show(level=ARAXResponse.DEBUG))
    response.data['message_stats'] = {
        'n_results': message.n_results,
        'id': message.id,
        'reasoner_id': message.reasoner_id,
        'tool_version': message.tool_version
    }
    print(
        json.dumps(ast.literal_eval(repr(response.data['parameters'])),
                   sort_keys=True,
                   indent=2))
    for result in message.results:
        if result.essence is not None:
            essence = result.essence
        else:
            essence = f"{len(result.node_bindings)} node bindings, {len(result.edge_bindings)} edge bindings"
        print(f" - {essence}")
    print(
        json.dumps(ast.literal_eval(repr(response.data['message_stats'])),
                   sort_keys=True,
                   indent=2))
def main():

    #### Create a response object
    response = ARAXResponse()

    #### Create an ActionsParser object
    from actions_parser import ActionsParser
    actions_parser = ActionsParser()

    #### Set a simple list of actions
    actions_list = [
        "filter(start_node=1, maximum_results=10, minimum_confidence=0.5)",
        "return(message=true,store=false)"
    ]

    #### Parse the action_list and print the result
    result = actions_parser.parse(actions_list)
    response.merge(result)
    if result.status != 'OK':
        print(response.show(level=ARAXResponse.DEBUG))
        return response
    actions = result.data['actions']

    #### Read message #2 from the database. This should be the acetaminophen proteins query result message
    sys.path.append(
        os.path.dirname(os.path.abspath(__file__)) + "/../../UI/Feedback")
    from RTXFeedback import RTXFeedback
    araxdb = RTXFeedback()
    message_dict = araxdb.getMessage(2)

    #### The stored message comes back as a dict. Transform it to objects
    from ARAX_messenger import ARAXMessenger
    message = ARAXMessenger().from_dict(message_dict)

    #### Asses some information about the QueryGraph
    query_graph_info = QueryGraphInfo()
    result = query_graph_info.assess(message)
    response.merge(result)
    if result.status != 'OK':
        print(response.show(level=ARAXResponse.DEBUG))
        return response
    #print(json.dumps(ast.literal_eval(repr(query_graph_info.node_order)),sort_keys=True,indent=2))

    #### Assess some information about the KnowledgeGraph
    knowledge_graph_info = KnowledgeGraphInfo()
    result = knowledge_graph_info.check_for_query_graph_tags(
        message, query_graph_info)
    response.merge(result)
    if result.status != 'OK':
        print(response.show(level=ARAXResponse.DEBUG))
        return response

    #### Try to add query_graph_ids to the KnowledgeGraph
    result = knowledge_graph_info.add_query_graph_tags(message,
                                                       query_graph_info)
    response.merge(result)
    if result.status != 'OK':
        print(response.show(level=ARAXResponse.DEBUG))
        return response

    #### Reassess some information about the KnowledgeGraph
    result = knowledge_graph_info.check_for_query_graph_tags(
        message, query_graph_info)
    response.merge(result)
    if result.status != 'OK':
        print(response.show(level=ARAXResponse.DEBUG))
        return response

    print(response.show(level=ARAXResponse.DEBUG))

    tmp = {
        'query_graph_id_node_status':
        knowledge_graph_info.query_graph_id_node_status,
        'query_graph_id_edge_status':
        knowledge_graph_info.query_graph_id_edge_status,
        'n_nodes': knowledge_graph_info.n_nodes,
        'n_edges': knowledge_graph_info.n_edges
    }
    #print(json.dumps(message.to_dict(),sort_keys=True,indent=2))
    print(json.dumps(ast.literal_eval(repr(tmp)), sort_keys=True, indent=2))
def main():
    ### Note that most of this is just manually doing what ARAXQuery() would normally do for you

    #### Create a response object
    response = ARAXResponse()

    #### Create an ActionsParser object
    from actions_parser import ActionsParser
    actions_parser = ActionsParser()

    #### Set a simple list of actions
    # actions_list = [
    #    "overlay(compute_confidence_scores=true)",
    #    "return(message=true,store=false)"
    # ]

    actions_list = [
        #"filter_kg(action=remove_edges_by_predicate, edge_predicate=physically_interacts_with, remove_connected_nodes=false)",
        #"filter_kg(action=remove_edges_by_predicate, edge_predicate=physically_interacts_with, remove_connected_nodes=something)",
        #"filter(action=remove_nodes_by_category, node_category=protein)",
        #"overlay(action=compute_ngd)",
        #"filter(action=remove_edges_by_attribute, edge_attribute=ngd, threshold=.63, direction=below, remove_connected_nodes=t)",
        #"filter(action=remove_edges_by_attribute, edge_attribute=ngd, threshold=.6, remove_connected_nodes=False)",
        "filter(action=remove_orphaned_nodes)",
        "return(message=true,store=false)"
    ]

    #### Parse the action_list and print the result
    result = actions_parser.parse(actions_list)
    response.merge(result)
    if result.status != 'OK':
        print(response.show(level=ARAXResponse.DEBUG))
        return response
    actions = result.data['actions']

    #### Read message #2 from the database. This should be the acetaminophen proteins query result message
    sys.path.append(
        os.path.dirname(os.path.abspath(__file__)) + "/../../UI/Feedback")
    from RTXFeedback import RTXFeedback
    araxdb = RTXFeedback()

    #message_dict = araxdb.getMessage(2)  # acetaminophen2proteins graph
    # message_dict = araxdb.getMessage(13)  # ibuprofen -> proteins -> disease # work computer
    # message_dict = araxdb.getMessage(14)  # pleuropneumonia -> phenotypic_feature # work computer
    # message_dict = araxdb.getMessage(16)  # atherosclerosis -> phenotypic_feature  # work computer
    # message_dict = araxdb.getMessage(5)  # atherosclerosis -> phenotypic_feature  # home computer
    # message_dict = araxdb.getMessage(10)
    message_dict = araxdb.getMessage(40)

    #### The stored message comes back as a dict. Transform it to objects
    from ARAX_messenger import ARAXMessenger
    message = ARAXMessenger().from_dict(message_dict)
    # print(json.dumps(message.to_dict(),sort_keys=True,indent=2))

    #### Create an overlay object and use it to apply action[0] from the list
    #filterkg = ARAXFilterKG()
    #result = filterkg.apply(message, actions[0]['parameters'])
    #response.merge(result)

    # Apply overlay so you get an edge attribute to work with, then apply the filter
    #from ARAX_overlay import ARAXOverlay
    #overlay = ARAXOverlay()
    #result = overlay.apply(message, actions[0]['parameters'])
    #response.merge(result)
    # then apply the filter
    filterkg = ARAXFilterKG()
    result = filterkg.apply(message, actions[0]['parameters'])
    response.merge(result)

    # if result.status != 'OK':
    #    print(response.show(level=ARAXResponse.DEBUG))
    #    return response
    # response.data = result.data

    #### If successful, show the result
    # print(response.show(level=ARAXResponse.DEBUG))
    # response.data['message_stats'] = { 'n_results': message.n_results, 'id': message.id,
    #    'reasoner_id': message.reasoner_id, 'tool_version': message.tool_version }
    # response.data['message_stats']['confidence_scores'] = []
    # for result in message.results:
    #    response.data['message_stats']['confidence_scores'].append(result.confidence)

    # print(json.dumps(ast.literal_eval(repr(response.data['parameters'])),sort_keys=True,indent=2))
    # print(json.dumps(ast.literal_eval(repr(response.data['message_stats'])),sort_keys=True,indent=2))
    # a comment on the end so you can better see the network on github

    # look at the response
    # print(response.show(level=ARAXResponse.DEBUG))
    # print(response.show())
    # print("Still executed")

    # look at the edges
    # print(json.dumps(ast.literal_eval(repr(message.knowledge_graph.edges.values())),sort_keys=True,indent=2))
    # print(json.dumps(ast.literal_eval(repr(message.knowledge_graph.nodes.values())), sort_keys=True, indent=2))
    # print(json.dumps(message.to_dict(), sort_keys=True, indent=2))
    # print(response.show(level=ARAXResponse.DEBUG))

    # just print off the values
    # print(json.dumps(ast.literal_eval(repr(message.knowledge_graph.edges.values())), sort_keys=True, indent=2))
    # for edge in message.knowledge_graph.edges.values():
    #    if hasattr(edge, 'attributes') and edge.attributes and len(edge.attributes) >= 1:
    #        print(edge.attributes.pop().value)
    print(
        json.dumps(ast.literal_eval(
            repr(message.knowledge_graph.edges.values())),
                   sort_keys=True,
                   indent=2))
    print(response.show(level=ARAXResponse.DEBUG))
    vals = []
    for key, node in message.knowledge_graph.nodes.items():
        print(key)
    print(len(message.knowledge_graph.nodes))
    for edge in message.knowledge_graph.edges.values():
        if hasattr(edge, 'attributes') and edge.attributes and len(
                edge.attributes) >= 1:
            vals.append(edge.attributes.pop().value)
    print(sorted(vals))