예제 #1
0
    def respond_get_paper_model(self, content):
        """Get and display the model from a paper, indicated by pmid."""
        pmid_raw = content.gets('pmid')
        prefix = 'PMID-'
        if pmid_raw.startswith(prefix) and pmid_raw[len(prefix):].isdigit():
            pmid = pmid_raw[len(prefix):]
        else:
            return self.make_failure('BAD_INPUT')
        try:
            stmts = get_statements_for_paper([('pmid', pmid)],
                                             simple_response=True)
        except IndraDBRestAPIError as e:
            if e.status_code == 404 and 'Invalid or unavailable' in e.reason:
                logger.error("Could not find pmid: %s" % e.reason)
                return self.make_failure('MISSING_MECHANISM')
            else:
                raise e

        if not stmts:
            resp = KQMLPerformative('SUCCESS')
            resp.set('relations-found', 0)
            return resp
        stmts = ac.map_grounding(stmts)
        stmts = ac.map_sequence(stmts)
        unique_stmts = ac.run_preassembly(stmts, return_toplevel=True)
        diagrams = _make_diagrams(stmts)
        self.send_display_model(diagrams)
        resp = KQMLPerformative('SUCCESS')
        resp.set('relations-found', len(unique_stmts))
        resp.set('dump-limit', str(DUMP_LIMIT))
        return resp
예제 #2
0
 def subscribe_tell(self, tell_type):
     msg = KQMLPerformative('subscribe')
     content = KQMLList('tell')
     content.append('&key')
     content.set('content', KQMLList.from_string('(%s . *)' % tell_type))
     msg.set('content', content)
     self.send(msg)
예제 #3
0
 def reply_with_content(self, msg, reply_content):
     "A wrapper around the reply method from KQMLModule."
     if not self.testing:
         reply_msg = KQMLPerformative('reply')
         reply_msg.set('content', reply_content)
         self.reply(msg, reply_msg)
     return (msg, reply_content)
예제 #4
0
 def send_display_figure(self, path):
     msg = KQMLPerformative('tell')
     content = KQMLList('display-image')
     content.set('type', 'simulation')
     content.sets('path', path)
     msg.set('content', content)
     self.send(msg)
예제 #5
0
 def respond_remove_mechanism(self, content):
     """Return response content to model-remove-mechanism request."""
     ekb = content.gets('description')
     model_id = self._get_model_id(content)
     no_display = content.get('no-display')
     try:
         res = self.mra.remove_mechanism(ekb, model_id)
     except Exception as e:
         raise InvalidModelDescriptionError(e)
     model_id = res.get('model_id')
     if model_id is None:
         raise InvalidModelDescriptionError('Could not find model id.')
     # 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')
     model_msg = encode_indra_stmts(model)
     msg.sets('model', model_msg)
     # Add the removed statements
     removed = res.get('removed')
     if removed:
         removed_msg = encode_indra_stmts(removed)
         msg.sets('removed', removed_msg)
     # 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(rxn_diagram)
     return msg
예제 #6
0
 def subscribe_request(self, req_type):
     msg = KQMLPerformative('subscribe')
     content = KQMLList('request')
     content.append('&key')
     content.set('content', KQMLList.from_string('(%s . *)' % req_type))
     msg.set('content', content)
     self.send(msg)
예제 #7
0
 def subscribe_tell(self, tell_type):
     msg = KQMLPerformative('subscribe')
     content = KQMLList('tell')
     content.append('&key')
     content.set('content', KQMLList.from_string('(%s . *)' % tell_type))
     msg.set('content', content)
     self.send(msg)
예제 #8
0
 def subscribe_request(self, req_type):
     msg = KQMLPerformative('subscribe')
     content = KQMLList('request')
     content.append('&key')
     content.set('content', KQMLList.from_string('(%s . *)' % req_type))
     msg.set('content', content)
     self.send(msg)
예제 #9
0
 def respond_dont_know(self, msg, content_string):
     resp = '(ONT::TELL :content (ONT::DONT-KNOW :content %s))' %\
         content_string
     resp_list = KQMLList.from_string(resp)
     reply_msg = KQMLPerformative('reply')
     reply_msg.set_parameter(':content', resp_list)
     self.reply(msg, reply_msg)
예제 #10
0
 def respond_confirm_relation_from_literature(self, content):
     """Confirm a protein-protein interaction given subject, object, verb"""
     try:
         subj, obj, stmt_type, filter_agents = self._get_query_info(content)
         finder = \
             self.msa.find_mechanism_from_input(subj, obj, None, stmt_type,
                                                ev_limit=5, persist=False,
                                                timeout=5,
                                                filter_agents=filter_agents)
         self._send_provenance_async(finder,
             'confirming that some statements match')
     except MSALookupError as mle:
         return self.make_failure(mle.args[0])
     stmts = finder.get_statements(timeout=20)
     if stmts is None:
         # TODO: Handle this more gracefully, if possible.
         return self.make_failure('MISSING_MECHANISM')
     num_stmts = len(stmts)
     description = finder.describe(include_negative=False) \
         if stmts else None
     #self.say(description)
     resp = KQMLPerformative('SUCCESS')
     resp.set('some-relations-found', 'TRUE' if num_stmts else 'FALSE')
     resp.set('num-relations-found', str(num_stmts))
     resp.set('dump-limit', str(DUMP_LIMIT))
     resp.sets('suggestion', description if description else 'nil')
     return resp
예제 #11
0
    def receive_request(self, msg, content):
        '''
        If a "request" message is received, decode the task and the content
        and call the appropriate function to prepare the response. A reply
        message is then sent back.
        '''
        content_list = content
        task_str = content_list[0].to_string().upper()
        if task_str == 'IS-DRUG-TARGET':
            reply_content = self.respond_is_drug_target(content_list)
        elif task_str == 'FIND-TARGET-DRUG':
            reply_content = self.respond_find_target_drug(content_list)
        elif task_str == 'FIND-DISEASE-TARGETS':
            reply_content = self.respond_find_disease_targets(content_list)
        elif task_str == 'FIND-TREATMENT':
            reply_content = self.respond_find_treatment(content_list)
            if reply_content is None:
                self.respond_dont_know(msg,
                                       '(ONT::A X1 :instance-of ONT::DRUG)')
                return
        else:
            self.error_reply(msg, 'unknown request task ' + task_str)
            return

        reply_msg = KQMLPerformative('reply')
        reply_msg.set_parameter(':content', reply_content)
        self.reply(msg, reply_msg)
예제 #12
0
 def send_display_figure(self, path):
     msg = KQMLPerformative('tell')
     content = KQMLList('display-image')
     content.set('type', 'simulation')
     content.sets('path', path)
     msg.set('content', content)
     self.send(msg)
예제 #13
0
 def insert_data(self, receiver, data, wm_only=False):
     msg = KQMLPerformative('insert')
     msg.set('sender', self.name)
     msg.set('receiver', receiver)
     if wm_only:
         msg.append(':wm-only?')
     msg.set('content', listify(data))
     self.connect(self.host, self.port)
     self.send(msg)
예제 #14
0
 def reply(self,):
     reply_msg = KQMLPerformative('reply')
     reply_content = KQMLList()
     for t in self.tests:
         print 'reply {0}'.format(t)
         t_content = t.get_content()
         if t_content:
             reply_content.add(t_content.to_string())
     reply_msg.setParameter(':content', reply_content)
     return reply_msg
예제 #15
0
 def receive_request(self, msg, content):
     '''
     If a "request" message is received, decode the task and the content
     and call the appropriate function to prepare the response. A reply
     "tell" message is then sent back.
     '''
     content_list = content
     task_str = content_list[0].to_string().upper()
     arguments = self.request_arguments(content_list)
     if task_str == 'KAPPA-VERSION':
         try:
             reply_content = self.respond_version()
         except Exception as e:
             message = 'Could not get Kappa version: (%s)' % e
             self.error_reply(msg, message)
             return
     elif task_str == 'KAPPA-PARSE':
         try:
             reply_content = self.respond_parse(arguments)
         except Exception as e:
             message = 'Could not parse Kappa model: (%s)' % e
             self.error_reply(msg, message)
             return
     elif task_str == 'KAPPA-START':
         try:
             reply_content = self.respond_start(arguments)
         except Exception as e:
             message = 'Could not start Kappa simulation: (%s)' % e
             self.error_reply(msg, message)
             return
     elif task_str == 'KAPPA-STATUS':
         try:
             reply_content = self.respond_status(arguments)
         except Exception as e:
             message = 'Could not get Kappa status: (%s)' % e
             self.error_reply(msg, message)
             return
     elif task_str == 'KAPPA-STOP':
         try:
             reply_content = self.respond_stop(arguments)
         except Exception as e:
             message = 'Could not stop Kappa simulation: (%s)' % e
             self.error_reply(msg, message)
             return
     else:
         message = '"unknown request task ' + task_str + '"'
         self.error_reply(msg, message)
         return
     reply_msg = KQMLPerformative('reply')
     reply_msg.set_parameter(':content', reply_content)
     logger.debug(reply_content.to_string())
     self.reply(msg, reply_msg)
예제 #16
0
    def respond_get_common(self, content):
        """Find the common up/down streams of a protein."""
        # TODO: This entire function could be part of the MSA.
        if not CAN_CHECK_STATEMENTS:
            return self.make_failure(
                'NO_KNOWLEDGE_ACCESS',
                'Cannot access the database through the web api.'
                )
        genes_ekb = content.gets('genes')
        agents = _get_agents(genes_ekb)
        if len(agents) < 2:
            return self.make_failure('NO_TARGET',
                                     'Only %d < 2 agents given.' % len(agents))

        direction = content.gets('up-down')
        logger.info("Got genes: %s and direction %s." % (agents, direction))

        # Choose some parameters based on direction.
        if direction == 'ONT::MORE':
            method = 'common_upstreams'
            prefix = 'up'
        elif direction == 'ONT::SUCCESSOR':
            method = 'common_downstreams'
            prefix = 'down'
        else:
            # TODO: With the new MSA we could handle common neighbors.
            return self.make_failure("UNKNOWN_ACTION", direction)

        # Find the commonalities.
        try:
            finder = self.msa.find_mechanisms(method, *agents)
        except EntityError as e:
            return self.make_failure("MISSING_TARGET", e.args[0])

        # Get post statements to provenance.
        if len(agents) > 2:
            name_list = ', '.join(ag.name for ag in agents[:-1]) + ','
        else:
            name_list = agents[0].name
        name_list += ' and ' + agents[-1].name
        msg = ('%sstreams of ' % prefix).capitalize() + name_list
        self.send_provenance_for_stmts(finder.get_statements(), msg,
                                       ev_counts=finder.get_ev_totals())

        # Create the reply
        resp = KQMLPerformative('SUCCESS')
        gene_list = KQMLList()
        for gene in finder.get_common_entities():
            gene_list.append(gene)
        resp.set('commons', gene_list)
        resp.sets('prefix', prefix)
        return resp
예제 #17
0
    def create_message(self):
        content = KQMLPerformative('SATISFIES-PATTERN')
        content.set('model', self.model)
        patt = KQMLList()
        patt.sets('type', 'eventual_value')
        ents = KQMLList()
        ent = KQMLList()
        ent.sets('description', agent_clj_from_text('phosphorylated MAPK1'))
        ents.append(ent)
        patt.set('entities', ents)
        val = KQMLList()
        val.sets('type', 'qualitative')
        val.sets('value', 'low')
        patt.set('value', val)
        content.set('pattern', patt)

        conds = KQMLList()
        cond = KQMLList()
        cond.sets('type', 'multiple')
        quant = KQMLList()
        quant.sets('type', 'total')
        ent = KQMLList()
        ent.sets('description', agent_clj_from_text('DUSP6'))
        quant.set('entity', ent)
        cond.sets('quantity', quant)
        #val = KQMLList()
        #val.sets('type', 'number')
        cond.set('value', KQMLToken('10'))
        #cond.set('value', val)
        conds.append(cond)
        content.set('conditions', conds)

        msg = get_request(content)
        return msg, content
    def insert_data(self, receiver, data, wm_only=False):
        """Takes the data input by the user and processes it into an insert
        message which is subsequently sent off to Companions.

        Arguments:
            receiver {str} -- name of the receiver
            data {[type]} -- anything that can be listified

        Keyword Arguments:
            wm_only {bool} -- whether or not this should only be inserted into
                              the working memory (default: {False})
        """
        msg = KQMLPerformative('insert')
        msg.set('sender', self.name)
        msg.set('receiver', receiver)
        if wm_only:
            msg.data.append(':wm-only?')  # KMQLPerformative has no function
            # append, instead we must access the KQMLList inside the
            # KQMLPerformative .data attribute...
        msg.set('content', listify(data))
        # pylint: disable=no-member
        # pylint was unable to pick up on the host and port variables being in
        # a defaults dict which is then used to do __setattr__ with the key
        # value pairs from the dict.
        # self.connect(self.host, self.port)
        self.send(msg)
예제 #19
0
    def respond_phosphorylation_activating(self, content):
        """Return response content to phosphorylation_activating request."""
        if not CAN_CHECK_STATEMENTS:
            return self.make_failure(
                'NO_KNOWLEDGE_ACCESS',
                'Cannot access the database through the web api.'
                )
        heading = content.head()
        m = re.match('(\w+)-(\w+)', heading)
        if m is None:
            return self.make_failure('UNKNOWN_ACTION')
        action, polarity = [s.lower() for s in m.groups()]
        target_ekb = content.gets('target')
        if target_ekb is None or target_ekb == '':
            return self.make_failure('MISSING_TARGET')
        agent = _get_agent(target_ekb)
        logger.debug('Found agent (target): %s.' % agent.name)
        site = content.gets('site')
        if site is None:
            residue = None
            position = None
        else:
            try:
                residue, position = site.split('-')
            except:
                return self.make_failure('INVALID_SITE')

        finder = self.msa.find_phos_activeforms(agent, residue=residue,
                                                position=position,
                                                action=action,
                                                polarity=polarity)
        stmts = finder.get_statements()
        self.say(finder.describe())

        logger.info("Found %d matching statements." % len(stmts))
        if not len(stmts):
            return self.make_failure(
                'MISSING_MECHANISM',
                "Could not find statement matching phosphorylation activating "
                "%s, %s, %s, %s." % (agent.name, residue, position,
                                     'phosphorylation')
                )
        else:
            msg = "phosphorylation at %s%s activates %s." \
                  % (residue, position, agent.name)
            self.send_provenance_for_stmts(stmts, msg,
                                           ev_counts=finder.get_ev_totals())
            msg = KQMLPerformative('SUCCESS')
            msg.set('is-activating', 'TRUE')
            return msg
예제 #20
0
    def respond_get_paper_model(self, content):
        """Get and display the model from a paper, indicated by pmid."""
        pmid_raw = content.gets('pmid')
        prefix = 'PMID-'
        if pmid_raw.startswith(prefix) and pmid_raw[len(prefix):].isdigit():
            pmid = pmid_raw[len(prefix):]
        else:
            return self.make_failure('BAD_INPUT')
        try:
            stmts = get_statements_for_paper([('pmid', pmid)])
        except IndraDBRestAPIError as e:
            if e.status_code == 404 and 'Invalid or unavailable' in e.reason:
                logger.error("Could not find pmid: %s" % e.reason)
                return self.make_failure('MISSING_MECHANISM')
            else:
                raise e

        if not stmts:
            resp = KQMLPerformative('SUCCESS')
            resp.set('relations-found', 0)
            return resp
        stmts = ac.map_grounding(stmts)
        stmts = ac.map_sequence(stmts)
        unique_stmts = ac.run_preassembly(stmts, return_toplevel=True)
        diagrams = _make_diagrams(stmts)
        self.send_display_model(diagrams)
        resp = KQMLPerformative('SUCCESS')
        resp.set('relations-found', len(unique_stmts))
        resp.set('dump-limit', str(DUMP_LIMIT))
        return resp
예제 #21
0
 def achieve_on_agent(self, receiver, data):
     msg = KQMLPerformative('achieve')
     msg.set('sender', self.name)
     msg.set('receiver', receiver)
     msg.set('content', listify(data))
     self.connect(self.host, self.port)
     self.send(msg)
    def send_generic(msg: KQMLPerformative, out: BufferedWriter):
        """Basic send mechanism copied (more or less) from pykqml. Writes the
        msg as a string to the output buffer then flushes it.

        Args:
            msg (KQMLPerformative): Message to be sent
            out (BufferedWriter): The output to write to, needed for sending to
                Companions and sending on our own port.
        """
        LOGGER.debug('Sending: %s', msg)
        try:
            msg.write(out)
        except IOError:
            LOGGER.error('IOError during message sending')
        out.write(b'\n')
        out.flush()
예제 #23
0
    def __init__(self, argv):
        super(TRA_Module, self).__init__(argv)
        self.tasks = ["SATISFIES-PATTERN"]
        parser = argparse.ArgumentParser()
        parser.add_argument("--kappa_url", help="kappa endpoint")
        args = parser.parse_args()
        if args.kappa_url:
            self.kappa_url = args.kappa_url
        else:
            logger.error("No Kappa URL given.")
            sys.exit()
        # Generate a basic model as placeholder (for testing)
        # model_text = 'MAPK1 binds MAP2K1.'
        # pa = PysbAssembler()
        # pa.add_statements(trips.process_text(model_text).statements)
        # self.model = pa.make_model()

        # Send subscribe messages
        for task in self.tasks:
            msg_txt = "(subscribe :content (request &key :content (%s . *)))" % task
            self.send(KQMLPerformative.from_string(msg_txt))
        # Instantiate a singleton TRA agent
        try:
            kappa = kappa_client.KappaRuntime(self.kappa_url)
            self.tra = TRA(kappa)
        except Exception as e:
            logger.error("Could not instantiate TRA with Kappa service.")
            self.tra = None
        self.ready()
        super(TRA_Module, self).start()
예제 #24
0
def _get_perf(text, msg_id):
    text = text.encode('utf-8')
    msg = KQMLPerformative('REQUEST')
    msg.set('receiver', 'DRUM')
    content = KQMLList('run-text')
    content.sets('text', text)
    msg.set('content', content)
    msg.set('reply-with', msg_id)
    return msg
예제 #25
0
def _get_perf(text, msg_id):
    """Return a request message for a given text."""
    msg = KQMLPerformative('REQUEST')
    msg.set('receiver', 'READER')
    content = KQMLList('run-text')
    content.sets('text', text)
    msg.set('content', content)
    msg.set('reply-with', msg_id)
    return msg
예제 #26
0
    def respond_model_remove_mechanism(self, content):
        """Return response content to model-remove-mechanism request."""
        model_id = self._get_model_id(content)
        descr = content.get('description')
        js = json.dumps(self.converter.cl_to_json(descr))
        no_display = content.get('no-display')
        try:
            res = self.mra.remove_mechanism(js, model_id)
        except Exception as e:
            raise InvalidModelDescriptionError(e)
        model_id = res.get('model_id')
        if model_id is None:
            raise InvalidModelDescriptionError('Could not find model id.')
        # 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')
        model_msg = encode_indra_stmts(model)
        msg.set('model', model_msg)

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

        # Get the action and add it to the message
        removed = res.get('removed')
        if not removed:
            msg = self.make_failure('REMOVE_FAILED')
            return msg
        else:
            actionl = KQMLList('remove_stmts')
            actionl.set('statements', encode_indra_stmts(removed))
            msg.set('action', actionl)

        # Add the diagram
        diagrams = res.get('diagrams')
        logger.info(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
예제 #27
0
 def respond_choose_sense(self, content):
     """Return response content to choose-sense request."""
     ekb = content.gets('ekb-term')
     msg = KQMLPerformative('SUCCESS')
     try:
         agents, ambiguities = self.bs.choose_sense(ekb)
     except InvalidAgentError:
         logger.info("agent not recognized:\n{}\n".format(ekb))
     else:
         kagents = []
         for term_id, agent_tuple in agents.items():
             kagent = get_kagent(agent_tuple, term_id)
             kagents.append(kagent)
         msg.set('agents', KQMLList(kagents))
     if ambiguities:
         ambiguities_msg = get_ambiguities_msg(ambiguities)
         msg.set('ambiguities', ambiguities_msg)
     return msg
예제 #28
0
 def register(self):
     if self.name is not None:
         perf = KQMLPerformative('register')
         perf.set('sender', self.name)
         perf.set('receiver', 'facilitator')
         content = KQMLList([
             '"socket://' + self.host + ':' + str(self.localPort) + '"',
             'nil', 'nil', self.localPort
         ])
         perf.set('content', content)
         self.send(perf)
예제 #29
0
 def get_content(self):
     """Convert the entry to a message."""
     if not self.content:
         maxlen = 100000
         if len(self.message) <= maxlen:
             self.content = KQMLPerformative.from_string(self.message)
         else:
             raise KQMLException('Message is longer than %d characters'
                                 % maxlen)
     return self.content
    def achieve_on_agent(self, receiver, data):
        """Sends a KQML message to the proper receiver with the data formatted
        properly as a list.

        Arguments:
            receiver {str} -- name of the receiver
            data {[type]} -- anything
        """
        msg = KQMLPerformative('achieve')
        msg.set('sender', self.name)
        msg.set('receiver', receiver)
        msg.set('content', listify(data))
        self.send(msg)
    def send_provenance(self, result):
        id1 = result['id1']
        mods1 = result['mods1']
        id2 = result['id2']
        mods2 = result['mods2']
        rel = result['rel']

        title = str(id1) + ' ' + str(rel) + ' ' + str(id2)

        uri_str = result['uri_str']
        pc_url = 'http://www.pathwaycommons.org/pc2/get?' + uri_str + 'format=SBGN'
        html = '<a href= \'' + pc_url + '\' target= \'_blank\' > PC link</a>'
        msg = KQMLPerformative('tell')
        content = KQMLList('add-provenance')
        content.sets('html', html)
        pc_url_formatted = "http://www.pathwaycommons.org/pc2/get?" + uri_str + "format=SBGN"
        content.sets('pc', pc_url_formatted)
        content.sets('title', title)
        msg.set('content', content)
        self.send(msg)
예제 #32
0
 def register(self):
     if self.name is not None:
         perf = KQMLPerformative('register')
         perf.set('name', self.name)
         if self.group_name is not None:
             try:
                 if self.group_name.startswith('('):
                     perf.sets('group', self.group_name)
                 else:
                     perf.set('group', self.group_name)
             except IOError:
                 logger.error('bad group name: ' + self.group_name)
         self.send(perf)
def performative(string: str) -> KQMLPerformative:
    """Wrapper for KQMLPerformative.from_string, produces a performative object
    from a KQML string

    Arguments:
        string (str): well formed KQML performative as a string

    Returns:
        KQMLPerformative
    """
    return KQMLPerformative.from_string(string)
예제 #34
0
 def __init__(self, argv):
     super(MRA_Module, self).__init__(argv)
     self.tasks = ["BUILD-MODEL", "EXPAND-MODEL", "MODEL-HAS-MECHANISM"]
     self.models = []
     for task in self.tasks:
         msg_txt = "(subscribe :content (request &key :content (%s . *)))" % task
         self.send(KQMLPerformative.from_string(msg_txt))
     # Instantiate a singleton MRA agent
     self.mra = MRA()
     self.ready()
     super(MRA_Module, self).start()
예제 #35
0
 def receive_request(self, msg, content):
     """
     If a "request" message is received, decode the task and the content
     and call the appropriate function to prepare the response. A reply
     "tell" message is then sent back.
     """
     try:
         task_str = content[0].to_string().upper()
     except Exception as e:
         logger.error("Could not get task string from request.")
         logger.error(e)
         self.error_reply(msg, "Invalid task")
     if task_str == "BUILD-MODEL":
         try:
             reply_content = self.respond_build_model(content)
         except InvalidModelDescriptionError as e:
             logger.error("Invalid model description.")
             logger.error(e)
             fail_msg = "(FAILURE :reason INVALID_DESCRIPTION)"
             reply_content = KQMLList.from_string(fail_msg)
     elif task_str == "EXPAND-MODEL":
         try:
             reply_content = self.respond_expand_model(content)
         except InvalidModelIdError as e:
             logger.error("Invalid model ID.")
             logger.error(e)
             fail_msg = "(FAILURE :reason INVALID_MODEL_ID)"
             reply_content = KQMLList.from_string(fail_msg)
         except InvalidModelDescriptionError as e:
             logger.error("Invalid model description.")
             logger.error(e)
             fail_msg = "(FAILURE :reason INVALID_DESCRIPTION)"
             reply_content = KQMLList.from_string(fail_msg)
     elif task_str == "MODEL-HAS-MECHANISM":
         reply_content = self.respond_has_mechanism(content)
     else:
         self.error_reply(msg, "Unknown task " + task_str)
         return
     reply_msg = KQMLPerformative("reply")
     reply_msg.set_parameter(":content", reply_content)
     self.reply(msg, reply_msg)
예제 #36
0
    def receive_request(self, msg, content):
        """
        If a "request" message is received, decode the task and the content
        and call the appropriate function to prepare the response. A reply
        "tell" message is then sent back.
        """
        content_list = content
        task_str = content_list[0].to_string().upper()
        if task_str == "SIMULATE-MODEL":
            try:
                reply_content = self.respond_simulate_model(content_list)
            except Exception as e:
                self.error_reply(msg, "Error in performing simulation task.")
                return
        else:
            self.error_reply(msg, "Unknown request task " + task_str)
            return

        reply_msg = KQMLPerformative("reply")
        reply_msg.set_parameter(":content", reply_content)
        self.reply(msg, reply_msg)
def full_remove_packaging(perf: KQMLPerformative):
    """Take a performative and strip package info from it

    Args:
        perf (KQMLPerformative): performative to strip

    Returns:
        KQMLPerformative: striped of package info
    """
    filter_list = [remove_packaging(s) for s in perf.to_string().split()]
    temp_perf = ' '.join(filter_list)
    return performative('(' + temp_perf if temp_perf[0] != '(' else temp_perf)
예제 #38
0
 def respond_build_model(self, content):
     """Return response content to build-model request."""
     descr = content.gets('description')
     descr_format = content.gets('format')
     no_display = content.get('no-display')
     if not descr_format or descr_format == 'ekb':
         res = self.mra.build_model_from_ekb(descr)
     elif descr_format == 'indra_json':
         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:
         self.send_background_support(model)
     model_msg = encode_indra_stmts(model)
     msg.sets('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)
     ambiguities = res.get('ambiguities')
     if ambiguities:
         ambiguities_msg = get_ambiguities_msg(ambiguities)
         msg.set('ambiguities', ambiguities_msg)
     return msg
예제 #39
0
    def receive_subscribe(self, msg, content):
        """Override of KQMLModule default, expects a performative of ask-all.

        Gets the ask-all query from the message contents (the contents of
        the content variable is the query that we care about), then checks
        to see if the query head is in the dictionary of available asks and
        checks if the query string is in the dictionary of subscribers. If both
        of these are true we then append the message to the subscriber query,
        clean out any previous subscription data, and reply with a tell ok
        message.

        Arguments:
            msg {KQMLPerformative} -- performative to be passed along in reply
                                      and stored in the subscribers dictionary
            content {KQMLPerformative} -- ask-all for a query
        """
        LOGGER.debug('received subscribe: %s', content)  # lazy logging
        if content.head() == 'ask-all':
            # TODO - track msg ideas and use for filtering
            query = content.get('content')
            query_string = query.to_string()
            if query.head() in self.asks and query_string in self.subscribers:
                self.subscribers[query_string].append(msg)
                self.subcribe_data_old[query_string] = None
                self.subcribe_data_new[query_string] = None
                reply_msg = KQMLPerformative('tell')
                reply_msg.set(':sender', self.name)
                reply_msg.set('content', ':ok')
                self.reply(msg, reply_msg)
예제 #40
0
    def receive_request(self, msg, content):
        """
        If a "request" message is received, decode the task and the content
        and call the appropriate function to prepare the response. A reply
        "tell" message is then sent back.
        """
        if self.tra is None:
            reply_content = KQMLList.from_string("(FAILURE :reason KAPPA_FAILURE)")
            reply_msg = KQMLPerformative("reply")
            reply_msg.set_parameter(":content", reply_content)
            self.reply(msg, reply_msg)
            return

        content_list = content
        task_str = content_list[0].to_string().upper()
        if task_str == "SATISFIES-PATTERN":
            try:
                reply_content = self.respond_satisfies_pattern(content_list)
            except Exception as e:
                self.error_reply(msg, "Error in performing satisfies " + "pattern task.")
                return
        else:
            self.error_reply(msg, "Unknown request task " + task_str)
            return

        reply_msg = KQMLPerformative("reply")
        reply_msg.set_parameter(":content", reply_content)
        self.reply(msg, reply_msg)
예제 #41
0
    def receive_other_performative(self, msg):
        """Override of KQMLModule default... ping isn't currently supported by
        pykqml so we handle other to catch ping and otherwise throw an error.

        Arguments:
            msg {KQMLPerformative} -- other type of performative, if ping we
                                      reply with a ping update otherwise error
        """
        if msg.head() == 'ping':
            reply_content = KQMLList([':agent', self.name])
            reply_content.append(':uptime')
            reply_content.append(self._uptime())
            # TODO - check if .set('status', ':OK') can be used here instead
            reply_content.append(':status')
            reply_content.append(':OK')
            reply_content.append(':state')
            reply_content.append('idle')
            reply_content.append(':machine')
            reply_content.append(socket.gethostname())
            reply = KQMLPerformative('update')
            reply.set('sender', self.name)
            # reply.set('receiver', msg.get('sender'))
            # reply.set('in-reply-to', msg.get('reply-with'))
            reply.set('content', reply_content)
            self.reply(msg, reply)
        else:
            self.error_reply(msg, 'unexpected performative: ' + str(msg))
예제 #42
0
    def respond_model_remove_mechanism(self, content):
        """Return response content to model-remove-mechanism request."""
        ekb = content.gets('description')
        model_id = self._get_model_id(content)
        no_display = content.get('no-display')
        try:
            res = self.mra.remove_mechanism(ekb, model_id)
        except Exception as e:
            raise InvalidModelDescriptionError(e)
        model_id = res.get('model_id')
        if model_id is None:
            raise InvalidModelDescriptionError('Could not find model id.')
        # 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')
        model_msg = encode_indra_stmts(model)
        msg.sets('model', model_msg)

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

        # Get the action and add it to the message
        removed = res.get('removed')
        if not removed:
            msg = self.make_failure('REMOVE_FAILED')
            return msg
        else:
            actionl = KQMLList('remove_stmts')
            actionl.sets('statements', encode_indra_stmts(removed))
            msg.set('action', actionl)

        # Add the diagram
        diagrams = res.get('diagrams')
        logger.info(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
예제 #43
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')
        model_id = res.get('model_id')
        # Start a SUCCESS message
        msg = KQMLPerformative('SUCCESS')
        # Add the model id
        msg.set('model-id', 'NIL' if model_id is None else str(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.set('model', model_msg)
        # Get the action and add it to the message
        action = res.get('action')
        actionl = KQMLList()
        # Here we handle no action as effectively an empty remove action
        if action['action'] in ('no_op', 'remove_stmts'):
            actionl.append('remove_stmts')
            actionl.set(
                '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
예제 #44
0
 def send_display_model(self, model, diagrams):
     msg = KQMLPerformative('tell')
     content = KQMLList('display-model')
     content.set('type', 'indra')
     content.sets('model', model)
     msg.set('content', content)
     self.send(msg)
     for diagram_type, path in diagrams.items():
         if not path:
             continue
         msg = KQMLPerformative('tell')
         content = KQMLList('display-image')
         content.set('type', diagram_type)
         content.sets('path', path)
         msg.set('content', content)
         self.send(msg)
예제 #45
0
 def register(self):
     """Overrides the KQMLModule default and uses Companions standards to
     send proper registration.
     """
     if self.name is not None:
         perf = KQMLPerformative('register')
         perf.set('sender', self.name)
         perf.set('receiver', 'facilitator')
         # pylint: disable=no-member
         # pylint was unable to pick up on the host variable being in a
         # defaults dict which is then used to do __setattr__ with the key
         # value pairs from the dict.
         socket_url = f'"socket://{self.host}:{self.local_port}"'
         content = KQMLList([socket_url, 'nil', 'nil', self.local_port])
         perf.set('content', content)
         self.send(perf)
예제 #46
0
 def init(self):
     '''
     Initialize TRIPS module
     '''
     super(Test_Module, self).init()
     # Send subscribe messages
     for task, subtasks in self.tasks.iteritems():
         for subtask in subtasks:
             msg_txt = '(subscribe :content (request &key :content ' +\
                 '(%s &key :content (%s . *))))' % (task, subtask)
             self.send(KQMLPerformative.from_string(msg_txt))
     # Send ready message
     self.ready()
     return None
예제 #47
0
 def respond_phosphorylation_activating(self, content):
     """Return response content to phosphorylation_activating request."""
     heading = content.head()
     m = re.match('(\w+)-(\w+)', heading)
     if m is None:
         return self.make_failure('UNKNOWN_ACTION')
     action, polarity = [s.lower() for s in m.groups()]
     target_ekb = content.gets('target')
     if target_ekb is None or target_ekb == '':
         return self.make_failure('MISSING_TARGET')
     agent = self._get_agent(target_ekb)
     logger.debug('Found agent (target): %s.' % agent.name)
     residue = content.gets('residue')
     position = content.gets('position')
     related_results = [
         s for s in self.signor_afs
         if self._matching(s, agent, residue, position, action, polarity)
         ]
     if not len(related_results):
         return self.make_failure(
             'MISSING_MECHANISM',
             "Could not find statement matching phosphorylation activating "
             "%s, %s, %s, %s." % (agent.name, residue, position,
                                  'phosphorylation')
             )
     else:
         self.send_provenance_for_stmts(
             related_results,
             "Phosphorylation at %s%s activates %s." % (
                 residue,
                 position,
                 agent.name
                 )
             )
         msg = KQMLPerformative('SUCCESS')
         msg.set('is-activating', 'TRUE')
         return msg
예제 #48
0
    def respond_phosphorylation_activating(self, content):
        """Return response content to phosphorylation_activating request."""
        if not CAN_CHECK_STATEMENTS:
            return self.make_failure(
                'NO_KNOWLEDGE_ACCESS',
                'Cannot access the database through the web api.')
        heading = content.head()
        m = re.match(r'(\w+)-(\w+)', heading)
        if m is None:
            return self.make_failure('UNKNOWN_ACTION')
        action, polarity = [s.lower() for s in m.groups()]
        target_cljson = content.get('target')
        if target_cljson is None or not len(target_cljson):
            return self.make_failure('MISSING_TARGET')
        agent = self.get_agent(target_cljson)
        # This is a bug in the BA that we can handle here
        if isinstance(agent, list):
            agent = agent[0]
        logger.debug('Found agent (target): %s.' % agent.name)
        site = content.gets('site')
        if site is None:
            residue = None
            position = None
        else:
            try:
                residue, position = site.split('-')
            except:
                return self.make_failure('INVALID_SITE')

        finder = self.msa.find_phos_activeforms(agent,
                                                residue=residue,
                                                position=position,
                                                action=action,
                                                polarity=polarity)
        stmts = finder.get_statements()

        logger.info("Found %d matching statements." % len(stmts))
        if not len(stmts):
            return self.make_failure(
                'MISSING_MECHANISM',
                "Could not find statement matching phosphorylation activating "
                "%s, %s, %s, %s." %
                (agent.name, residue, position, 'phosphorylation'))
        else:
            description = finder.describe(include_negative=False)
            # self.say(description)
            msg = "phosphorylation at %s%s activates %s." \
                  % (residue, position, agent.name)
            self.send_provenance_for_stmts(
                stmts,
                msg,
                ev_counts=finder.get_ev_totals(),
                source_counts=finder.get_source_counts())
            msg = KQMLPerformative('SUCCESS')
            msg.set('is-activating', 'TRUE')
            msg.sets('suggestion', description)
            return msg
예제 #49
0
 def register(self):
     if self.name is not None:
         perf = KQMLPerformative('register')
         perf.set('name', self.name)
         if self.group_name is not None:
             try:
                 if self.group_name.startswith('('):
                     perf.sets('group', self.group_name)
                 else:
                     perf.set('group', self.group_name)
             except IOError:
                 logger.error('bad group name: ' + self.group_name)
         self.send(perf)
예제 #50
0
 def __init__(self, argv):
     # Call the constructor of TripsModule
     super(DTDA_Module, self).__init__(argv)
     self.tasks = ['IS-DRUG-TARGET', 'FIND-TARGET-DRUG',
                   'FIND-DISEASE-TARGETS', 'FIND-TREATMENT']
     # Send subscribe messages
     for task in self.tasks:
         msg_txt =\
             '(subscribe :content (request &key :content (%s . *)))' % task
         self.send(KQMLPerformative.from_string(msg_txt))
     # Instantiate a singleton DTDA agent
     self.dtda = DTDA()
     # Send ready message
     self.ready()
     super(DTDA_Module, self).start()
예제 #51
0
 def __init__(self, argv):
     super(MEA_Module, self).__init__(argv)
     self.tasks = ["SIMULATE-MODEL"]
     parser = argparse.ArgumentParser()
     parser.add_argument("--kappa_url", help="kappa endpoint")
     args = parser.parse_args()
     if args.kappa_url:
         self.kappa_url = args.kappa_url
     # Send subscribe messages
     for task in self.tasks:
         msg_txt = "(subscribe :content (request &key :content (%s . *)))" % task
         self.send(KQMLPerformative.from_string(msg_txt))
     # Instantiate a singleton MEA agent
     self.mea = MEA()
     self.ready()
     super(MEA_Module, self).start()
예제 #52
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')
        model_id = res.get('model_id')
        # Start a SUCCESS message
        msg = KQMLPerformative('SUCCESS')
        # Add the model id
        msg.set('model-id', 'NIL' if model_id is None else str(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()
        # Here we handle no action as effectively an empty remove action
        if action['action'] in ('no_op', '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
예제 #53
0
    def read_pmc(self, pmcid):
        """Read a given PMC article.

        Parameters
        ----------
        pmcid : str
            The PMC ID of the article to read. Note that only
            articles in the open-access subset of PMC will work.
        """
        msg = KQMLPerformative('REQUEST')
        msg.set('receiver', 'READER')
        content = KQMLList('run-pmcid')
        content.sets('pmcid', pmcid)
        content.set('reply-when-done', 'true')
        msg.set('content', content)
        msg.set('reply-with', 'P-%s' % pmcid)
        self.reply_counter += 1
        self.send(msg)
예제 #54
0
 def respond_model_has_mechanism(self, content):
     """Return response content to model-has-mechanism request."""
     ekb = content.gets('description')
     model_id = self._get_model_id(content)
     try:
         res = self.mra.has_mechanism(ekb, model_id)
     except Exception as e:
         raise InvalidModelDescriptionError(e)
     # Start a SUCCESS message
     msg = KQMLPerformative('SUCCESS')
     # Add the model id
     msg.set('model-id', str(model_id))
     # Add TRUE or FALSE for has-mechanism
     has_mechanism_msg = 'TRUE' if res['has_mechanism'] else 'FALSE'
     msg.set('has-mechanism', has_mechanism_msg)
     query = res.get('query')
     if query:
         query_msg = encode_indra_stmts([query])
         msg.sets('query', query_msg)
     return msg
예제 #55
0
 def __init__(self, argv):
     # Call the constructor of TripsModule
     super(Kappa_Module, self).__init__(argv)
     self.tasks = ['KAPPA-VERSION', 'KAPPA-PARSE', 'KAPPA-START',
                   'KAPPA-STATUS', 'KAPPA-STOP']
     parser = argparse.ArgumentParser()
     parser.add_argument("--kappa_url", help="kappa endpoint")
     args = parser.parse_args()
     if args.kappa_url:
         self.kappa_url = args.kappa_url
     else:
         logger.error('No Kappa URL given.')
         sys.exit()
     # Send subscribe messages
     for task in self.tasks:
         msg_txt =\
             '(subscribe :content (request &key :content (%s . *)))' % task
         self.send(KQMLPerformative.from_string(msg_txt))
     # Instantiate a kappa runtime
     self.kappa = KappaRuntime(self.kappa_url)
     # Send ready message
     self.ready()
     super(Kappa_Module, self).start()
예제 #56
0
 def respond_confirm_relation_from_literature(self, content):
     """Confirm a protein-protein interaction given subject, object, verb"""
     try:
         subj, obj, stmt_type = self._get_query_info(content)
         finder = \
             self.msa.find_mechanism_from_input(subj, obj, None, stmt_type,
                                                ev_limit=5, persist=False,
                                                timeout=5)
         self._send_provenance_async(finder,
             'confirming that some statements match')
     except MSALookupError as mle:
         return self.make_failure(mle.args[0])
     stmts = finder.get_statements(timeout=20)
     if stmts is None:
         # TODO: Handle this more gracefully, if possible.
         return self.make_failure('MISSING_MECHANISM')
     num_stmts = len(stmts)
     self.say(finder.describe())
     resp = KQMLPerformative('SUCCESS')
     resp.set('some-relations-found', 'TRUE' if num_stmts else 'FALSE')
     resp.set('num-relations-found', str(num_stmts))
     resp.set('dump-limit', str(DUMP_LIMIT))
     return resp
예제 #57
0
 def error_reply(self, msg, comment):
     reply_msg = KQMLPerformative('error')
     reply_msg.sets('comment', comment)
     self.reply(msg, reply_msg)
예제 #58
0
    def respond_build_model(self, content):
        """Return response content to build-model request."""
        descr = content.gets('description')
        descr_format = content.gets('format')
        no_display = content.get('no-display')
        if not descr_format or descr_format == 'ekb':
            res = self.mra.build_model_from_ekb(descr)
        elif descr_format == 'indra_json':
            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.sets('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
        self.send_model_diagnoses(res)

        # 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
예제 #59
0
 def send_clean_model(self):
     msg = KQMLPerformative('request')
     content = KQMLList('clean-model')
     msg.set('content', content)
     self.send(msg)