예제 #1
0
def build_onehop_query(
        q_object_category,
        q_subject_category,
        q_subject=None,
        q_object=None,
        genes=None,
        drugs=None,
        outcome=None,
        outcome_name=None,
        outcome_op=None,
        outcome_value=None,
        disease=None,
        trapi_version='1.1',
        biolink_version=None,
        ):
    # Initialize query
    message = Message(trapi_version, biolink_version)
    q = message.query_graph

    # Add nodes
    subject_node = q.add_node(q_subject, q_subject_category)
    object_node = q.add_node(q_object, q_object_category)

    # Add edge
    try:
        edge_predicate = SUBJECT_TO_OBJECT_PREDICATE_MAP[q_subject_category[0]][q_object_category[0]]
    except KeyError:
        raise QueryBuildError('Edge from {} to {} is not supported.'.format(q_subject_category, q_object_category))

    edge_id = q.add_edge(subject_node, object_node, edge_predicate)

    # Add constraints
    if outcome is not None:
        q.add_constraint('predicate_proxy', 'CHP:PredicateProxy', '==', [outcome], edge_id=edge_id)
        q.add_constraint(outcome, outcome, outcome_op, outcome_value, edge_id=edge_id)
    
    # Get context
    context = []
    if genes is not None:
        context.append(BIOLINK_GENE)
    if drugs is not None:
        context.append(BIOLINK_DRUG)
    if disease is not None:
        context.append(BIOLINK_DISEASE)

    # Process context
    if len(context) > 0:
        q.add_constraint('predicate_context', 'CHP:PredicateContext', '==', context, edge_id=edge_id)
        if genes is not None:
            q.add_constraint(BIOLINK_GENE, BIOLINK_GENE, 'matches', genes, edge_id=edge_id)
        if drugs is not None:
            q.add_constraint(BIOLINK_DRUG, BIOLINK_DRUG, 'matches', drugs, edge_id=edge_id)
        if disease is not None:
            q.add_constraint(BIOLINK_DISEASE, BIOLINK_DISEASE, 'matches', disease, edge_id=edge_id)
    query = Query(trapi_version=trapi_version, biolink_version=biolink_version)
    query.message = message
    return query
 def test_ars_predicates_queries(self):
     ars_predicates_dir = os.path.join(self.ncats_test_dir,
                                       'ars-requests/predicates')
     # Added supported Query filenames to list below:
     supported_query_filenames = [
         'conditionGene.json',
         'geneCondition.json',
     ]
     # Run tests
     for filename in supported_query_filenames:
         filepath = os.path.join(ars_predicates_dir, filename)
         query = Query('1.0').load(query_filepath=filepath)
         print(json.dumps(query.to_dict(), indent=2))
예제 #3
0
 def test_batch_drug_wildcard_query(self):
     for trapi_version, queries in self.drug_batch_queries.items():
         query = Query.load(trapi_version, None, query=queries[0])
         interface = TrapiInterface(query=query)
         interface.build_chp_queries()
         interface.run_chp_queries()
         response = interface.construct_trapi_response()
예제 #4
0
 def test_simple_batch_query(self):
     # These are simple queries
     logger.info('Running batch simple query test.')
     for trapi_version, queries in self.batch_queries.items():
         query = Query.load(trapi_version, None, query=queries[0])
         interface = TrapiInterface(query=query)
         interface.build_chp_queries()
         interface.run_chp_queries()
         response = interface.construct_trapi_response()
예제 #5
0
 def test_simple_single_query(self):
     # This is a simple query
     logger.info('Running single simple query test.')
     for trapi_version, queries in self.queries.items():
         query = Query.load(trapi_version, None, query=queries[1])
         interface = TrapiInterface(query=query)
         interface.build_chp_queries()
         interface.run_chp_queries()
         response = interface.construct_trapi_response()
예제 #6
0
 def test_wildcard_batch_onehop_query(self):
     for trapi_version, queries in self.wildcard_batch_queries.items():
         for name, query_dict in queries.items():
             #if name != 'gene_to_disease_proxy_context':
             #    continue
             query = Query.load(trapi_version, None, query=query_dict)
             interface = TrapiInterface(query=query)
             interface.build_chp_queries()
             interface.run_chp_queries()
             response = interface.construct_trapi_response()
예제 #7
0
 def test_inverse_wildcard_query(self):
     for trapi_version, queries in self.gene_queries.items():
         query = Query.load(trapi_version, None, query=queries[0])
         for edge_id, edge in query.message.query_graph.edges.items():
             predicate = edge.predicates[0]
             inverse = edge.predicates[0].get_inverse()
             edge.set_predicates(inverse)
         interface = TrapiInterface(query=query)
         interface.build_chp_queries()
         interface.run_chp_queries()
         response = interface.construct_trapi_response()
예제 #8
0
 def test_inverse_query(self):
     # This is a simple query
     logger.info('Running default inverse query test.')
     for trapi_version, queries in self.queries.items():
         query = Query.load(trapi_version, None, query=queries[1])
         for edge_id, edge in query.message.query_graph.edges.items():
             predicate = edge.predicates[0]
             inverse = edge.predicates[0].get_inverse()
             edge.set_predicates(inverse)
         interface = TrapiInterface(query=query)
         interface.build_chp_queries()
         interface.run_chp_queries()
         response = interface.construct_trapi_response()
    def process_request(self, request, trapi_version):
        """ Helper function that extracts the query from the message.
        """
        logger.info('Starting query.')
        query = Query.load(self.trapi_version,
                           biolink_version=None,
                           query=request.data)

        # Setup query in Base Processor
        self.setup_query(query)

        logger.info('Query loaded')

        return query
예제 #10
0
 def test_inverse_onehop_query(self):
     for trapi_version, queries in self.standard_single_queries.items():
         for name, query_dict in queries.items():
             #if name != 'gene_to_disease_proxy_context':
             #    continue
             query = Query.load(trapi_version, None, query=query_dict)
             for edge_id, edge in query.message.query_graph.edges.items():
                 predicate = edge.predicates[0]
                 inverse = edge.predicates[0].get_inverse()
                 if inverse is not None:
                     edge.set_predicates(inverse)
             interface = TrapiInterface(query=query)
             interface.build_chp_queries()
             interface.run_chp_queries()
             response = interface.construct_trapi_response()
예제 #11
0
 def test_ars_notnone_queries(self):
     from trapi_model.query import Query
     from trapi_model.exceptions import UnknownBiolinkEntity
     ars_predicates_dir = os.path.join(self.ncats_test_dir,
                                       'ars-requests/not-none')
     # Run tests
     for filename in os.listdir(ars_predicates_dir):
         try:
             if os.path.splitext(filename)[-1] == '.json':
                 filepath = os.path.join(ars_predicates_dir, filename)
                 query = Query.load('1.0', None, query_filepath=filepath)
                 query_dict = query.to_dict()
                 if query.is_batch_query():
                     batch = query.expand_batch_query()
         except UnknownBiolinkEntity as ex:
             logger.critical('Failed on file {} with {}'.format(
                 filename, ex.message))
 def get_responses(self, queries=None, trapi_queries=None):
     # Initialize interface
     interface = TrapiInterface(
         bkb_handler=self.bkb_handler,
         dynamic_reasoner=self.dynamic_reasoner,
         joint_reasoner=self.joint_reasoner,
     )
     # Load queries
     if trapi_queries is None:
         trapi_queries = [
             Query.load(query["trapi_version"], None, query=query)
             for query in queries
         ]
     # Process trapi query
     interface.setup_trapi_queries(trapi_queries)
     # Build CHP queries
     interface.build_chp_queries()
     # Run CHP queries
     interface.run_chp_queries()
     # Get Responses
     responses = interface.construct_trapi_responses()
     return responses
 def test_inverse_query(self):
     standard_queries = copy.deepcopy(self.standard_queries)
     descriptions = [
         query.pop("test_description", None)
         for query in self.standard_queries
     ]
     # Make inverse queries
     trapi_queries = [
         Query.load(query["trapi_version"], None, query=query)
         for query in standard_queries
     ]
     for query in trapi_queries:
         for edge_id, edge in query.message.query_graph.edges.items():
             predicate = edge.predicates[0]
             inverse = edge.predicates[0].get_inverse()
             if inverse is not None:
                 edge.set_predicates(inverse)
                 # Switch subject and object
                 edge_subject = copy.deepcopy(edge.subject)
                 edge_object = copy.deepcopy(edge.object)
                 edge.subject = edge_object
                 edge.object = edge_subject
     responses = self.get_responses(trapi_queries=trapi_queries)
예제 #14
0
def build_standard_query(
        genes=None,
        drugs=None,
        outcome=None,
        outcome_name=None,
        outcome_op=None,
        outcome_value=None,
        disease=None,
        trapi_version='1.1',
        biolink_version=None,
        batch_genes=None,
        batch_drugs=None,
        batch_diseases=None,
        ):

    if outcome is None:
        raise QueryBuildError('You must specify an outcome CURIE.')
    if outcome_op is None:
        raise QueryBuildError("You must specify an outcome operation consistent with \
                with your desired TRAPI version's Constraint Object.")
    if outcome_value is None:
        raise QueryBuildError('You must specify an outcome value to test.')
    if disease is None and batch_diseases is None:
        raise QueryBuildError('You must specify a disease.')
    if disease is not None and batch_diseases is not None:
        raise QueryBuildError('Only specify either diseases or batch diseases not both.')

    # Initialize Message
    message = Message(trapi_version, biolink_version)
    q = message.query_graph
    
    # Add disease or batch disease node
    if disease is not None:
        disease_node = q.add_node(disease, BIOLINK_DISEASE)
    else:
        disease_node = q.add_node(batch_diseases, BIOLINK_DISEASE)

    if genes is not None:
        # Add gene nodes
        gene_nodes = []
        for gene in genes:
            gene_nodes.append(q.add_node(gene, BIOLINK_GENE))
    
        # Connect all gene nodes to disease.
        for gene_node in gene_nodes:
            q.add_edge(gene_node, disease_node, BIOLINK_GENE_ASSOCIATED_WITH_CONDITION)

    # Setup batch genes
    if batch_genes is not None:
        if type(batch_genes) is not list:
            raise QueryBuildError('Batch genes must be a list.')
        batch_gene_node = q.add_node(batch_genes, BIOLINK_GENE)
        q.add_edge(batch_gene_node, disease_node, BIOLINK_GENE_ASSOCIATED_WITH_CONDITION)

    if drugs is not None:
        # Add drug nodes
        if drugs is not None:
            drug_nodes = []
            for drug in drugs:
                drug_nodes.append(q.add_node(drug, BIOLINK_DRUG))

        # Connect all drug nodes to disease.
        for drug_node in drug_nodes:
            q.add_edge(drug_node, disease_node, BIOLINK_TREATS)

    # Setup batch drugs
    if batch_drugs is not None:
        if type(batch_drugs) is not list:
            raise QueryBuildError('Batch drugs must be a list.')
        batch_drug_node = q.add_node(batch_drugs, BIOLINK_DRUG)
        q.add_edge(batch_drug_node, disease_node, BIOLINK_TREATS)

    # Connect drug node to outcome node
    outcome_node = q.add_node(outcome, BIOLINK_PHENOTYPIC_FEATURE)
    phenotype_edge = q.add_edge(disease_node, outcome_node, BIOLINK_HAS_PHENOTYPE)
    q.add_constraint(outcome_name, outcome, outcome_op, outcome_value, edge_id=phenotype_edge)

    query = Query(trapi_version=trapi_version, biolink_version=biolink_version)
    query.message = message
    return query