示例#1
0
def get_kagent(agent_tuple, term_id=None):
    agent, ont_type, urls = agent_tuple
    db_refs = '|'.join('%s:%s' % (k, v) for k, v in agent.db_refs.items())
    kagent = KQMLList(term_id) if term_id else KQMLList()
    kagent.sets('name', agent.name)
    kagent.sets('ids', db_refs)
    url_parts = [
        KQMLList([':name', KQMLString(k), ':dblink',
                  KQMLString(v)]) for k, v in urls.items()
    ]
    url_list = KQMLList()
    for url_part in url_parts:
        url_list.append(url_part)
    kagent.set('id-urls', url_list)
    kagent.set('ont-type', ont_type)
    return kagent
示例#2
0
 def respond_get_all_diseases(self, content):
     """Respond to the task to list all diseases we handle."""
     reply = KQMLList('SUCCESS')
     reply.set('diseases',
               KQMLList([KQMLString(disease_name)
                         for disease_name in self.dtda.all_diseases]))
     return reply
示例#3
0
 def _cl_from_json(self, json_obj):
     if isinstance(json_obj, list):
         ret = KQMLList()
         for elem in json_obj:
             ret.append(self._cl_from_json(elem))
     elif isinstance(json_obj, dict):
         ret = KQMLList()
         for key, val in json_obj.items():
             ret.set(_key_from_string(key), self._cl_from_json(val))
     elif isinstance(json_obj, str):
         ret = KQMLString(json_obj)
     elif isinstance(json_obj, bool):
         if json_obj:
             if self.token_bools:
                 ret = KQMLToken('TRUE')
             else:
                 ret = KQMLToken('T')
         else:
             if self.token_bools:
                 ret = KQMLToken('FALSE')
             else:
                 ret = KQMLToken('NIL')
     elif isinstance(json_obj, int) or isinstance(json_obj, float):
         ret = str(json_obj)
     elif json_obj is None:
         return KQMLToken('NIL')
     else:
         raise KQMLException("Unexpected value %s of type %s."
                             % (json_obj, type(json_obj)))
     return ret
示例#4
0
    def respond_find_qca_path(self, content):
        """Response content to find-qca-path request"""
        source_arg = content.gets('SOURCE')
        target_arg = content.gets('TARGET')
        reltype_arg = content.get('RELTYPE')

        if not source_arg:
            raise ValueError("Source list is empty")
        if not target_arg:
            raise ValueError("Target list is empty")

        target = self._get_term_name(target_arg)
        source = self._get_term_name(source_arg)

        if reltype_arg is None or len(reltype_arg) == 0:
            relation_types = None
        else:
            relation_types = [str(k.data) for k in reltype_arg.data]

        results_list = self.qca.find_causal_path([source], [target],
                                                 relation_types=relation_types)
        if not results_list:
            reply = self.make_failure('NO_PATH_FOUND')
            return reply
        first_result = results_list[0]
        first_edges = first_result[1::2]
        indra_edges = [fe[0]['INDRA json'] for fe in first_edges]
        indra_edges = [json.loads(e) for e in indra_edges]
        indra_edges_str = json.dumps(indra_edges)
        ks = KQMLString(indra_edges_str)

        reply = KQMLList('SUCCESS')
        reply.set('paths', KQMLList([ks]))

        return reply
示例#5
0
def listify(possible_list):
    if isinstance(possible_list, list):
        new_list = [listify(each) for each in possible_list]
        return KQMLList(new_list)
    elif isinstance(possible_list, tuple):
        if len(possible_list) == 2:
            # assume dotted pair
            car = listify(possible_list[0])
            cdr = listify(possible_list[1])
            return KQMLList([car, KQMLToken('.'), cdr])
        else:
            # otherwise treat same as list
            new_list = [listify(each) for each in possible_list]
            return KQMLList(new_list)
    elif isinstance(possible_list, str):
        if ' ' in possible_list:
            if possible_list[0] == '(' and possible_list[-1] == ')':
                # WARNING: This is very incomplete!
                terms = possible_list[1:-1].split()
                return KQMLList([listify(t) for t in terms])
            else:
                return KQMLString(possible_list)
        else:
            return KQMLToken(possible_list)
    elif isinstance(possible_list, dict):
        return KQMLList([listify(pair) for pair in possible_list.items()])
    else:
        return KQMLToken(str(possible_list))
示例#6
0
    def respond_find_qca_path(self, content):
        """Response content to find-qca-path request"""
        if self.qca.ndex is None:
            reply = self.make_failure('SERVICE_UNAVAILABLE')
            return reply

        source_arg = content.gets('SOURCE')
        target_arg = content.gets('TARGET')
        reltype_arg = content.get('RELTYPE')

        if not source_arg:
            raise ValueError("Source list is empty")
        if not target_arg:
            raise ValueError("Target list is empty")

        target = self._get_term_name(target_arg)
        if target is None:
            reply = self.make_failure('NO_PATH_FOUND')
            # NOTE: use the one below if it's handled by NLG
            #reply = self.make_failure('TARGET_MISSING')
            return reply

        source = self._get_term_name(source_arg)
        if source is None:
            reply = self.make_failure('NO_PATH_FOUND')
            # NOTE: use the one below if it's handled by NLG
            #reply = self.make_failure('SOURCE_MISSING')
            return reply

        if reltype_arg is None or len(reltype_arg) == 0:
            relation_types = None
        else:
            relation_types = [str(k.data) for k in reltype_arg.data]

        results_list = self.qca.find_causal_path([source], [target],
                                                 relation_types=relation_types)
        if not results_list:
            reply = self.make_failure('NO_PATH_FOUND')
            return reply
        first_result = results_list[0]
        first_edges = first_result[1::2]
        indra_edges = [fe[0]['INDRA json'] for fe in first_edges]
        indra_edges = [json.loads(e) for e in indra_edges]
        indra_edges = _fix_indra_edges(indra_edges)
        indra_edge_stmts = stmts_from_json(indra_edges)
        for stmt in indra_edge_stmts:
            txt = EnglishAssembler([stmt]).make_model()
            self.send_provenance_for_stmts(
                [stmt], "the path from %s to %s (%s)" % (source, target, txt))
        indra_edges_str = json.dumps(indra_edges)
        ks = KQMLString(indra_edges_str)

        reply = KQMLList('SUCCESS')
        reply.set('paths', KQMLList([ks]))

        return reply
示例#7
0
 def respond_indra_to_nl(self, content):
     """Return response content to build-model request."""
     stmts_json_str = content.gets('statements')
     stmts = decode_indra_stmts(stmts_json_str)
     txts = assemble_english(stmts)
     txts_kqml = [KQMLString(txt) for txt in txts]
     txts_list = KQMLList(txts_kqml)
     reply = KQMLList('OK')
     reply.set('NL', txts_list)
     return reply
示例#8
0
 def respond_model_get_upstream(self, content):
     """Return response content to model-upstream request."""
     target_arg = content.gets('target')
     target = get_target(target_arg)
     try:
         model_id = self._get_model_id(content)
     except Exception:
         model_id = 1
     upstream = self.mra.get_upstream(target, model_id)
     terms = []
     names = []
     for agent in upstream:
         term = ekb_from_agent(agent)
         if term is not None:
             names.append(KQMLString(agent.name))
             terms.append(KQMLString(term))
     reply = KQMLList('SUCCESS')
     reply.set('upstream', KQMLList(terms))
     reply.set('upstream-names', KQMLList(names))
     return reply
示例#9
0
    def respond_choose_sense(self, content):
        """Return response content to choose-sense request."""
        agent_clj = content.get('agent')
        agent = self.get_agent(agent_clj)
        if not agent:
            return self.make_failure('MISSING_AGENT')
        add_agent_type(agent)

        def _get_urls(agent):
            urls = {
                k: get_identifiers_url(k, v)
                for k, v in agent.db_refs.items()
                if k not in {'TEXT', 'TYPE', 'TRIPS'}
            }
            return urls

        msg = KQMLPerformative('SUCCESS')
        msg.set('agent', self.make_cljson(agent))

        description = None
        if 'UP' in agent.db_refs:
            description = uniprot_client.get_function(agent.db_refs['UP'])
        if description:
            msg.sets('description', description)

        urls = _get_urls(agent)
        if urls:
            url_parts = [
                KQMLList([':name',
                          KQMLString(k), ':dblink',
                          KQMLString(v)]) for k, v in urls.items()
            ]
            url_list = KQMLList()
            for url_part in url_parts:
                url_list.append(url_part)
            msg.set('id-urls', url_list)

        return msg
示例#10
0
def listify(possible_list):
    """Takes in an object and returns it in KQMLList form.

    Checks if the input is a list, and if so it recurses through all entities
    in the list to further listify them. If the input is not a list but is
    instead a tuple of length 2 we make the assumption that this is a dotted
    pair and construct the KQMLList as such, otherwise we treat this larger
    tuple the same as a list. If the input is a string, we first check that it
    has a space in it (to differentiate facts, strings, and tokens). We then
    check if it is in lisp form (i.e. '(...)') and if so we split every term
    between the parens by the spaces. Otherwise we return the object as a
    KQMLString. In either case, if the string had no spaces in it we return it
    as a KQMLToken. WARNING: This may be an incomplete breakdown of strings.
    Next we check if the input was a dictionary and if so we listify the key
    value pairs, and then make a KQMLList of that overall list of pairs.
    Lastly, if the input was nothing else we return the input as a string
    turned into a KQMLToken.

    Arguments:
        possible_list {any} -- any input that you want to transform to KQML
                               ready data types

    Returns:
        KQML* -- List, String, or Token
    """
    # pylint: disable=no-else-return
    # Another pylint bug...? Normally this error is for having return
    # statements inside an else but this is showing up for return statements in
    # elif. Not something to worry about.
    if isinstance(possible_list, list):
        new_list = [listify(each) for each in possible_list]
        return KQMLList(new_list)
    elif isinstance(possible_list, tuple):
        if len(possible_list) == 2:
            car = listify(possible_list[0])
            cdr = listify(possible_list[1])
            return KQMLList([car, KQMLToken('.'), cdr])
        new_list = [listify(each) for each in possible_list]
        return KQMLList(new_list)
    elif isinstance(possible_list, str):
        if ' ' in possible_list:
            # WARNING: This may be an incomplete breakdown of strings.
            if possible_list[0] == '(' and possible_list[-1] == ')':
                terms = possible_list[1:-1].split()
                return KQMLList([listify(t) for t in terms])
            return KQMLString(possible_list)
        return KQMLToken(possible_list)
    elif isinstance(possible_list, dict):
        return KQMLList([listify(pair) for pair in possible_list.items()])
    return KQMLToken(str(possible_list))
示例#11
0
def stmts_kstring_from_text(text):
    stmts_json = stmts_json_from_text(text)
    ks = KQMLString(json.dumps(stmts_json))
    return ks
示例#12
0
def ekb_kstring_from_text(text):
    ekb_xml = ekb_from_text(text)
    ks = KQMLString(ekb_xml)
    return ks
示例#13
0
 def say(self, message):
     """Say something to the user."""
     if message:
         msg = KQMLList('say')
         msg.append(KQMLString(message))
         self.request(msg)
示例#14
0
def stmts_kstring_from_text(text):
    """Return a KQML string representation of INDRA Statements JSON from
    text."""
    stmts_json = stmts_json_from_text(text)
    ks = KQMLString(json.dumps(stmts_json))
    return ks
示例#15
0
def ekb_kstring_from_text(text):
    """Return a KQML string representation of an EKB from text."""
    ekb_xml = ekb_from_text(text)
    ks = KQMLString(ekb_xml)
    return ks