Esempio n. 1
0
    def post(self):
        """
        query
        ---
        tag: validation
        description: TranQL Query
        requestBody:
            description: Input message
            required: true
            content:
                application/json:
                    schema:
                        type: object
                        properties:
                            query:
                                type: string
        responses:
            '200':
                description: Success
                content:
                    text/plain:
                        schema:
                            type: string
                            example: "Successfully validated"
            '400':
                description: Malformed message
                content:
                    text/plain:
                        schema:
                            type: string

        """
        #self.validate (request)
        result = {}
        tranql = TranQL()
        try:
            logging.debug(request.json)
            query = request.json['query'] if 'query' in request.json else ''
            logging.debug(f"--> query: {query}")
            context = tranql.execute(query)  #, cache=True)
            result = context.mem.get('result', {})
            logger.debug(f" -- backplane: {context.mem.get('backplane', '')}")
            if len(context.mem.get('requestErrors', [])) > 0:
                errors = self.handle_exception(context.mem['requestErrors'],
                                               warning=True)
                for key in errors:
                    result[key] = errors[key]
        except Exception as e:
            traceback.print_exc()
            errors = [e, *tranql.context.mem.get('requestErrors', [])]
            result = self.handle_exception(errors)
        with open('query.out', 'w') as stream:
            json.dump(result, stream, indent=2)
        return result
Esempio n. 2
0
def test_interpreter_set (requests_mock):
    set_mock(requests_mock, "workflow-5")
    """ Test set statements by executing a few and checking values after. """
    print ("test_interpreter_set ()")
    tranql = TranQL ()
    tranql.resolve_names = False
    tranql.execute ("""
        -- Test set statements.
        SET disease = 'asthma'
        SET max_p_value = '0.5'
        SET cohort = 'COHORT:22'
        SET population_density = 2
        SET icees.population_density_cluster = 'http://localhost/ICEESQuery'
        SET gamma.quick = 'http://robokop.renci.org:80/api/simple/quick/' """)

    variables = [ "disease", "max_p_value", "cohort", "icees.population_density_cluster", "gamma.quick" ]
    output = { k : tranql.context.resolve_arg (f"${k}") for k in variables }
    #print (f"resolved variables --> {json.dumps(output, indent=2)}")
    assert output['disease'] == "asthma"
    assert output['cohort'] == "COHORT:22"
Esempio n. 3
0
File: api.py Progetto: patlsc/tranql
    def post(self):
        """
        query
        ---
        tag: validation
        description: TranQL Query
        requestBody:
            description: Input message
            required: true
            content:
                application/json:
                    schema:
                        type: object
                        properties:
                            query:
                                type: string
        responses:
            '200':
                description: Success
                content:
                    text/plain:
                        schema:
                            type: string
                            example: "Successfully validated"
            '400':
                description: Malformed message
                content:
                    text/plain:
                        schema:
                            type: string

        """
        #self.validate (request)
        result = {}
        try:
            tranql = TranQL()
            logging.debug(request.json)
            query = request.json['query'] if 'query' in request.json else ''
            logging.debug(f"----------> query: {query}")
            context = tranql.execute(query)  #, cache=True)
            result = context.mem.get('result', {})
            logger.debug(f" -- backplane: {context.mem.get('backplane', '')}")
        except TranQLException as e:
            result = {
                "status": "error",
                "message": str(e),
                "details": e.details
            }
        except Exception as e:
            traceback.print_exc(e)
            result = {"status": "error", "message": str(e), "details": ''}
        return result
Esempio n. 4
0
def test_program (requests_mock):
    print ("test_program ()")
    mock_map = MockMap (requests_mock, "workflow-5")
    tranql = TranQL (options = {
        "asynchronous" : False,
        "resolve_names" : False
    })
    ast = tranql.execute ("""
    --
    -- Workflow 5
    --
    --   Modules 1-4: Chemical Exposures by Clinical Clusters
    --      For sub-clusters within the overall ICEES asthma cohort defined by
    --      differential population density, which chemicals are related to these
    --      clusters with a p_value less than some threshold?
    --
    --   Modules 5-*: Knowledge Graph Phenotypic Associations
    --      For chemicals produced by the first steps, what phenotypes are
    --      associated with exposure to these chemicals?
    --
    SET id_filters = "SCTID,rxcui,CAS,SMILES,umlscui"

    SELECT population_of_individual_organisms->drug_exposure
      FROM "/clinical/cohort/disease_to_chemical_exposure"
     WHERE EstResidentialDensity < '2'
       AND population_of_individual_organizms = 'x'
       AND cohort = 'all_patients'
       AND max_p_value = '0.1'
       SET '$.knowledge_graph.nodes.[*].id' AS chemical_exposures

    SELECT chemical_substance->gene->biological_process->phenotypic_feature
      FROM "/graph/gamma/quick"
     WHERE chemical_substance = $chemical_exposures
       SET knowledge_graph
    """)

    #print (f"{ast}")
    expos = tranql.context.resolve_arg("$chemical_exposures")
    #print (f" expos =======> {json.dumps(expos)}")

    kg = tranql.context.resolve_arg("$knowledge_graph")
    assert kg['knowledge_graph']['nodes'][0]['id'] == "CHEBI:28177"
    assert kg['knowledge_map'][0]['node_bindings']['chemical_substance'] == "CHEBI:28177"
Esempio n. 5
0
    def post(self):
        """
        Query TranQL
        ---
        tags: [query]
        description: Execute a TranQL query.
        requestBody:
          name: query
          description: A valid TranQL program
          required: true
          content:
            text/plain:
             schema:
               type: string
             example: >
               select chemical_substance->gene->disease
                 from \"/graph/gamma/quick\"
                where disease=\"asthma\"
        parameters:
            - in: query
              name: dynamic_id_resolution
              schema:
                type: boolean
              required: false
              default: false
              description: Specifies if dynamic id lookup of curies will be performed
            - in: query
              name: asynchronous
              schema:
                type: boolean
              required: false
              default: true
              description: Specifies if requests made by TranQL will be asynchronous.
        responses:
            '200':
                description: Message
                content:
                    application/json:
                        schema:
                          $ref: '#/definitions/Message'
            '500':
                description: An error was encountered
                content:
                    application/json:
                        schema:
                          $ref: '#/definitions/Error'

        """
        #self.validate (request)
        result = {}

        logging.debug(request.data)
        query = request.data.decode('utf-8')
        dynamic_id_resolution = request.args.get('dynamic_id_resolution',
                                                 'False').upper() == 'TRUE'
        asynchronous = request.args.get('asynchronous',
                                        'True').upper() == 'TRUE'
        logging.debug(f"--> query: {query}")
        tranql = TranQL(
            options={
                "dynamic_id_resolution": dynamic_id_resolution,
                "asynchronous": asynchronous
            })
        try:
            context = tranql.execute(query)  #, cache=True)
            result = context.mem.get('result', {})
            logger.debug(f" -- backplane: {context.mem.get('backplane', '')}")
            if len(context.mem.get('requestErrors', [])) > 0:
                errors = self.handle_exception(context.mem['requestErrors'],
                                               warning=True)
                result.update(errors)
        except Exception as e:
            traceback.print_exc()
            errors = [e, *tranql.context.mem.get('requestErrors', [])]
            result = self.handle_exception(errors)
        with open('query.out', 'w') as stream:
            json.dump(result, stream, indent=2)

        return self.response(result)