def respond_dataset_correlated_entity(self, content):
        """Response content to find-database-correlated-entity request"""
        source_arg = content.get('SOURCE')
        if not source_arg:
            return self.make_failure('MISSING_MECHANISM')

        source_names = _get_kqml_names(source_arg)
        if not source_names:
            return self.make_failure('MISSING_MECHANISM')

        source_name = source_names[0]
        res = self.CA.find_next_correlation(source_name)
        if res == '':
            return self.make_failure('NO_PATH_FOUND')

        reply = KQMLList('SUCCESS')

        reply.sets('target', res['id2'])
        # TODO: should be float as original or converted to string?
        reply.sets('correlation', str(res['correlation']))
        reply.sets('explainable', res['explainable'])

        return reply
Exemplo n.º 2
0
    def respond_find_treatment(self, content):
        """Response content to find-treatment request."""
        try:
            disease_arg = content.get('disease')
            disease = self.get_agent(disease_arg)
        except Exception as e:
            logger.error(e)
            reply = self.make_failure('INVALID_DISEASE')
            return reply

        disease_name = disease.name.lower().replace('-', ' ')
        disease_name = disease_name.replace('cancer', 'carcinoma')
        logger.debug('Disease: %s' % disease_name)

        try:
            res = self.dtda.get_top_mutation(disease_name)
            if res is None:
                return self.make_failure('NO_MUTATION_STATS')
            mut_protein, mut_percent, agents = res
        except DiseaseNotFoundException:
            reply = self.make_failure('DISEASE_NOT_FOUND')
            return reply

        # TODO: get functional effect from actual mutations
        # TODO: add list of actual mutations to response
        # TODO: get fraction not percentage from DTDA
        reply = KQMLList('SUCCESS')
        protein = self._get_agent_from_gene_name(mut_protein)
        reply.set('protein', self.make_cljson(protein))
        reply.set('disease', disease_arg)
        reply.set('prevalence', '%.2f' % (mut_percent/100.0))
        reply.set('functional-effect', 'ACTIVE')
        # These differ only in mutation, which isn't relevant.
        an_agent = agents[0]
        drugs = self.dtda.find_target_drugs(an_agent)
        reply.set('drugs', Bioagent.make_cljson(drugs))
        return reply
Exemplo n.º 3
0
    def send_provenance_for_stmts(self,
                                  stmt_list,
                                  for_what,
                                  limit=50,
                                  ev_counts=None,
                                  source_counts=None):
        """Send out a provenance tell for a list of INDRA Statements.

        The message is used to provide evidence supporting a conclusion.
        """
        logger.info("Sending provenance for %d statements for \"%s\"." %
                    (len(stmt_list), for_what))
        title = "Supporting evidence for %s" % for_what
        content_fmt = '<h4>%s (max %s):</h4>\n%s<hr>'
        evidence_html = self._make_report_cols_html(
            stmt_list,
            limit=limit,
            ev_counts=ev_counts,
            source_counts=source_counts,
            title=title)

        content = KQMLList('add-provenance')
        content.sets('html', content_fmt % (title, limit, evidence_html))
        return self.tell(content)
Exemplo n.º 4
0
    def respond_show_mutation_data(self, content):
        """Response content to show-mutation-data request"""
        gene_arg = content.get('GENE')

        if not gene_arg:
            self.make_failure('MISSING_MECHANISM')

        gene_names = _get_kqml_names(gene_arg)
        if not gene_names:
            return self.make_failure('MISSING_MECHANISM')
        gene_name = gene_names[0]

        disease_arg = content.get('DISEASE')
        if not disease_arg:
            return self.make_failure('MISSING_MECHANISM')

        disease_names = _get_kqml_names(disease_arg)
        if not disease_names:
            return self.make_failure('INVALID_DISEASE')

        disease_name = _sanitize_disase_name(disease_names[0])
        disease_abbr = self.BA.get_tcga_abbr(disease_name)
        if disease_abbr is None:
            return self.make_failure('INVALID_DISEASE')

        oncoprint_data = self.BA.find_variants_for_genes_cbio(
            gene_names, disease_abbr, "tcga")

        self.send_display_oncoprint(oncoprint_data)

        reply = KQMLList('SUCCESS')

        reply.sets('oncoprint',
                   'SUCCESS' if len(oncoprint_data) > 0 else 'FAILURE')

        return reply
Exemplo n.º 5
0
    def respond_find_causal_path(self, content):
        """Response content to find-causal-path request"""

        source_arg = content.gets('SOURCE')
        target_arg = content.gets('TARGET')
        direction = content.gets('DIRECTION')

        if not source_arg or not target_arg:
            return self.make_failure('MISSING_MECHANISM')

        target_names = _get_term_names(target_arg)
        source_names = _get_term_names(source_arg)

        if not target_names or not source_names:
            return self.make_failure('NO_PATH_FOUND')

        source_name = source_names[0]
        target_name = target_names[0]

        target = {'id': target_name, 'pSite': ''}
        source = {'id': source_name, 'pSite': ''}

        result = self.CA.find_causality({'source': source, 'target': target, 'direction':direction})

        if not result:
            return self.make_failure('NO_PATH_FOUND')

        indra_json = json.dumps([make_indra_json(result)])

        reply = KQMLList('SUCCESS')
        reply.sets('paths', indra_json)

        # Send PC links to provenance tab
        self.send_provenance(result) # ['uri_str'])

        return reply
Exemplo n.º 6
0
    def respond_model_undo(self, content):
        """Return response content to model-undo request."""
        res = self.mra.model_undo()
        no_display = content.get('no-display')
        new_model_id = res.get('model_id')
        # Start a SUCCESS message
        msg = KQMLPerformative('SUCCESS')
        # Add the model id
        msg.set('model-id', str(new_model_id))
        # Add the INDRA model json
        model = res.get('model')

        # Handle empty model
        if not model:
            self.send_clean_model()

        model_msg = encode_indra_stmts(model)
        msg.sets('model', model_msg)
        # Get the action and add it to the message
        action = res.get('action')
        actionl = KQMLList()
        if action['action'] == 'remove_stmts':
            actionl.append('remove_stmts')
            actionl.sets('statements',
                         encode_indra_stmts(action['statements']))
        msg.set('action', actionl)

        # Add the diagram
        diagrams = res.get('diagrams')
        if not no_display:
            if diagrams:
                rxn_diagram = diagrams.get('reactionnetwork')
                if rxn_diagram:
                    msg.sets('diagram', rxn_diagram)
                self.send_display_model(diagrams)
        return msg
Exemplo n.º 7
0
    def respond_expand_model(self, content):
        """Return response content to expand-model request."""
        model_id = self._get_model_id(content)
        descr_format = content.gets('format')
        no_display = content.get('no-display')
        try:
            if not descr_format:
                descr = content.get('description')
                js = json.dumps(self.converter.cl_to_json(descr))
                res = self.mra.expand_model_from_json(js, model_id)
            elif descr_format == 'ekb':
                descr = content.gets('description')
                res = self.mra.expand_model_from_ekb(descr, model_id)
            elif descr_format == 'indra_json':
                descr = content.gets('description')
                res = self.mra.expand_model_from_json(descr, model_id)
            else:
                err_msg = 'Invalid description format: %s' % descr_format
                raise InvalidModelDescriptionError(err_msg)
        except Exception as e:
            raise InvalidModelDescriptionError(e)
        new_model_id = res.get('model_id')
        if new_model_id is None:
            raise InvalidModelDescriptionError()
        # Start a SUCCESS message
        msg = KQMLPerformative('SUCCESS')
        # Add the model id
        msg.set('model-id', str(new_model_id))
        # Add the INDRA model json
        model = res.get('model')
        model_msg = encode_indra_stmts(model)
        msg.set('model', model_msg)
        # Add the INDRA model new json
        model_new = res.get('model_new')

        # Indicate whether the goal has been explained
        has_expl = res.get('has_explanation')
        if has_expl is not None:
            msg.set('has_explanation', str(has_expl).upper())

        # Send out various model diagnosis messages
        diagnostic_tells = self.send_model_diagnoses(res)
        if diagnostic_tells:
            suggs = KQMLList()
            for text in diagnostic_tells:
                sugg = KQMLList()
                sugg.sets('TEXT', text)
                suggs.append(sugg)
            msg.set('suggestions', suggs)

        # Once we sent out the diagnosis messages, we make sure we keep
        # track of whether we have an explanation
        if has_expl:
            self.have_explanation = True

        if model_new and (descr_format == 'ekb' or not descr_format):
            self.send_background_support(model_new)
        if model_new:
            model_new_msg = encode_indra_stmts(model_new)
            msg.set('model-new', model_new_msg)
        # Add the diagram
        if not no_display:
            diagrams = res.get('diagrams')
            if diagrams:
                rxn_diagram = diagrams.get('reactionnetwork')
                if rxn_diagram:
                    msg.sets('diagram', rxn_diagram)
                self.send_display_model(diagrams)
        # Analyze the model for issues

        # Report ambiguities
        ambiguities = res.get('ambiguities')
        if ambiguities:
            ambiguities_msg = get_ambiguities_msg(ambiguities)
            msg.set('ambiguities', ambiguities_msg)
        return msg
Exemplo n.º 8
0
 def create_message(self):
     content = KQMLList('TEST')
     content.sets('description', '')
     msg = KQMLPerformative('REQUEST')
     msg.set('content', content)
     return msg, content
Exemplo n.º 9
0
def render_status(status):
    reply_content = KQMLList()
    reply_content.add(":status")
    if 'plot' in status:
        plot_data = status['plot']
        plot = KQMLList()
        plot.add(':plot')
        if 'legend' in plot_data:
            legend = KQMLList()
            legend.add(':legend')
            for label in plot_data['legend']:
                legend.add('"' + label + '"')
            plot.add(legend)
        if 'observables' in plot_data:
            observables = KQMLList()
            observables.add(':observables')
            for o in plot_data['observables']:
                observation = KQMLList()
                observation.add(':observation')
                if 'time' in o:
                    time = KQMLList()
                    time.add(':time')
                    time.add(render_value(o['time']))
                    observation.add(time)
                if 'values' in o:
                    values = KQMLList()
                    values.add(':values')
                    for f in o['values']:
                        values.add(render_value(f))
                    observation.add(values)
                observables.add(observation)
            plot.add(observables)
        reply_content.add(plot)
    if 'tracked_events' in status:
        tracked_events = KQMLList()
        tracked_events.add(':tracked_events')
        tracked_events.add(render_value(status['tracked_events']))
        plot.add(tracked_events)
    if 'is_running' in status:
        is_running = KQMLList()
        is_running.add(':is_running')
        is_running.add(render_value(status['is_running']))
        plot.add(is_running)
    if 'event_percentage' in status:
        event_percentage = KQMLList()
        event_percentage.add(':event_percentage')
        event_percentage.add(render_value(status['event_percentage']))
        plot.add(event_percentage)
    if 'time_percentage' in status:
        time_percentage = KQMLList()
        time_percentage.add(':time_percentage')
        time_percentage.add(render_value(status['time_percentage']))
        plot.add(time_percentage)
    if 'time' in status:
        time = KQMLList()
        time.add(':time')
        time.add(render_value(status['time']))
        plot.add(time)
    if 'event' in status:
        event = KQMLList()
        event.add(':event')
        event.add(render_value(status['event']))
        plot.add(event)
    # trips is not happy with this not sure why
    # if 'log_messages':
    #     log_messages = KQMLList()
    #     log_messages.add(':log_messages')
    #     for message in status['log_messages']:
    #         log_messages.add("'"+render_value(message)+"'")
    #     plot.add(log_messages)
    return reply_content
Exemplo n.º 10
0
 def respond_get_all_drugs(self, content):
     """Respond with all the drugs we have to tell you about."""
     reply = KQMLList('SUCCESS')
     reply.set('drugs', self.make_cljson(self.dtda.get_all_drugs()))
     return reply
Exemplo n.º 11
0
 def respond_get_all_gene_targets(self, content):
     reply = KQMLList('SUCCESS')
     reply.set('genes', self.make_cljson(self.dtda.get_all_targets()))
     return reply
Exemplo n.º 12
0
    def respond_satisfies_pattern(self, content):
        """Return response content to satisfies-pattern request."""
        model_indra_clj = content.get('model')
        pattern_lst = content.get('pattern')
        conditions_lst = content.get('conditions')

        try:
            stmts = decode_indra_stmts(model_indra_clj)
            model = assemble_model(stmts)
        except Exception as e:
            logger.exception(e)
            reply_content = self.make_failure('INVALID_MODEL')
            return reply_content

        try:
            pattern = get_temporal_pattern(pattern_lst)
        except tra.InvalidTimeIntervalError as e:
            logger.exception(e)
            reply_content = self.make_failure('INVALID_TIME_LIMIT')
            return reply_content
        except tra.InvalidTemporalPatternError as e:
            logger.exception(e)
            reply_content = self.make_failure('INVALID_PATTERN')
            return reply_content
        except tra.InvalidMolecularEntityError as e:
            logger.exception(e)
            reply_content = self.make_failure('INVALID_ENTITY_DESCRIPTION')
            return reply_content

        if conditions_lst is None:
            conditions = None
        else:
            try:
                conditions = []
                for condition_lst in conditions_lst:
                    condition = get_molecular_condition(condition_lst)
                    conditions.append(condition)
            except Exception as e:
                logger.exception(e)
                reply_content = self.make_failure('INVALID_CONDITIONS')
                return reply_content

        try:
            sat_rate, num_sim, suggestion_kqml, suggestion_obj, fig_path = \
                self.tra.check_property(model, pattern, conditions)
        except tra.MissingMonomerError as e:
            logger.exception(e)
            reply_content = self.make_failure('MODEL_MISSING_MONOMER')
            if e.monomer:
                reply_content.set('entity', self.make_cljson(e.monomer))
            return reply_content
        except tra.MissingMonomerSiteError as e:
            logger.exception(e)
            reply_content = self.make_failure('MODEL_MISSING_MONOMER_SITE')
            return reply_content
        except tra.SimulatorError as e:
            logger.exception(e)
            reply_content = self.make_failure('KAPPA_FAILURE')
            return reply_content
        except Exception as e:
            logger.exception(e)
            reply_content = self.make_failure('INVALID_PATTERN')
            return reply_content

        self.send_display_figure(fig_path)

        reply = KQMLList('SUCCESS')
        content = KQMLList()
        content.set('satisfies-rate', '%.1f' % sat_rate)
        content.set('num-sim', '%d' % num_sim)
        if suggestion_kqml:
            sugg = KQMLList.from_string(suggestion_kqml)
            content.set('suggestion', sugg)
        reply.set('content', content)
        return reply
Exemplo n.º 13
0
 def create_message(self):
     drug = agent_clj_from_text('SB525334')
     content = KQMLList('FIND-DRUG-TARGETS')
     content.set('drug', drug)
     return get_request(content), content
 def respond_reset_causality_indices(self, content):
     self.CA.reset_indices()
     reply = KQMLList('SUCCESS')
     return reply
Exemplo n.º 15
0
 def create_message(self):
     content = KQMLList('CHOOSE-SENSE')
     agent = agent_clj_from_text('BRAF')
     content.set('agent', agent)
     print(content)
     return get_request(content), content
Exemplo n.º 16
0
 def create_message(self):
     content = KQMLList('GET-ALL-GENE-TARGETS')
     return get_request(content), content
Exemplo n.º 17
0
 def create_message(self):
     # Here we create a KQML request that the TFTA needs to respond to
     keyword = self.keyword
     content = KQMLList('FIND-TF-KEYWORD')
     content.set('keyword', keyword)
     return get_request(content), content
Exemplo n.º 18
0
 def create_message(self):
     content = KQMLList('GET-ALL-DISEASES')
     return get_request(content), content
Exemplo n.º 19
0
 def create_message(self):
     disease = agent_clj_from_text('common cold')
     content = KQMLList('FIND-TREATMENT')
     content.set('disease', disease)
     return get_request(content), content
Exemplo n.º 20
0
 def create_message(self):
     disease = agent_clj_from_text('prostate cancer')
     content = KQMLList('FIND-DISEASE-TARGETS')
     content.set('disease', disease)
     return get_request(content), content
Exemplo n.º 21
0
    def respond_build_model(self, content):
        """Return response content to build-model request."""
        descr_format = content.gets('format')
        if descr_format:
            logger.info('Building model from format: %s' % descr_format)
        no_display = content.get('no-display')
        if not descr_format:
            descr = content.get('description')
            js_data = self.converter.cl_to_json(descr)
            if isinstance(js_data, dict):
                logger.error('JSON data should be a list not a dict.')
                raise InvalidModelDescriptionError("Model description should "
                                                   "be a list of events.")
            js = json.dumps(js_data)
            res = self.mra.build_model_from_json(js)
        elif descr_format == 'ekb':
            descr = content.gets('description')
            res = self.mra.build_model_from_ekb(descr)
        elif descr_format == 'indra_json':
            descr = content.gets('description')
            res = self.mra.build_model_from_json(descr)
        else:
            err_msg = 'Invalid description format: %s' % descr_format
            raise InvalidModelDescriptionError(err_msg)
        if res.get('error'):
            raise InvalidModelDescriptionError(res.get('error'))
        model_id = res.get('model_id')
        if model_id is None:
            raise InvalidModelDescriptionError()
        # Start a SUCCESS message
        msg = KQMLPerformative('SUCCESS')
        # Add the model id
        msg.set('model-id', str(model_id))
        # Add the INDRA model json
        model = res.get('model')
        if model and (descr_format == 'ekb' or not descr_format):
            self.send_background_support(model)
        model_msg = encode_indra_stmts(model)
        msg.set('model', model_msg)
        # Add the diagrams
        diagrams = res.get('diagrams')
        if not no_display:
            if diagrams:
                rxn_diagram = diagrams.get('reactionnetwork')
                if rxn_diagram:
                    msg.sets('diagram', rxn_diagram)
                self.send_display_model(diagrams)

        # Indicate whether the goal has been explained
        has_expl = res.get('has_explanation')
        if has_expl is not None:
            msg.set('has_explanation', str(has_expl).upper())

        # Send out various model diagnosis messages
        diagnostic_tells = self.send_model_diagnoses(res)
        if diagnostic_tells:
            suggs = KQMLList()
            for text in diagnostic_tells:
                sugg = KQMLList()
                sugg.sets('TEXT', text)
                suggs.append(sugg)
            msg.set('suggestions', suggs)

        # Once we sent out the diagnosis messages, we make sure we keep
        # track of whether we have an explanation
        if has_expl:
            self.have_explanation = True

        # Analyze the model for issues
        # Report ambiguities
        ambiguities = res.get('ambiguities')
        if ambiguities:
            ambiguities_msg = get_ambiguities_msg(ambiguities)
            msg.set('ambiguities', ambiguities_msg)
        return msg
Exemplo n.º 22
0
 def send_clean_model(self):
     msg = KQMLPerformative('request')
     content = KQMLList('clean-model')
     msg.set('content', content)
     self.send(msg)
Exemplo n.º 23
0
 def make_failure(self, reason=None):
     msg = KQMLList('FAILURE')
     if reason:
         msg.set('reason', reason)
     return msg
Exemplo n.º 24
0
 def create_message(self):
     # Here we create a KQML request that the TFTA needs to respond to
     target = ekb_kstring_from_text(self.target)
     content = KQMLList('FIND-TARGET-TF')
     content.set('target', target)
     return get_request(content), content
Exemplo n.º 25
0
 def create_message(self):
     # Here we create a KQML request that the TFTA needs to respond to
     pathway = ekb_kstring_from_text(self.pathway)
     content = KQMLList('FIND-GENE-PATHWAY')
     content.set('pathway', pathway)
     return get_request(content), content
Exemplo n.º 26
0
 def create_message(self):
     target = agent_clj_from_text(self.target)
     content = KQMLList('FIND-TARGET-DRUG')
     content.set('target', target)
     return get_request(content), content
Exemplo n.º 27
0
 def create_statements(self):
     content = KQMLList('INDRA-TO-NL')
     stmts_cl_json = self.bioagent.make_cljson(self.statements)
     content.set('statements', stmts_cl_json)
     return get_request(content), content
Exemplo n.º 28
0
 def create_message(self):
     # Here we create a KQML request that the TFTA needs to respond to
     mirna = ekb_kstring_from_text(self.mirna)
     content = KQMLList('FIND-GENE-COUNT-MIRNA')
     content.set('miRNA', mirna)
     return get_request(content), content
Exemplo n.º 29
0
def make_failure(reason):
    msg = KQMLList('FAILURE')
    msg.set('reason', reason)
    return msg
Exemplo n.º 30
0
 def say(self, message):
     """Say something to the user."""
     if message:
         msg = KQMLList('say')
         msg.append(KQMLString(message))
         self.request(msg)