def create_message(self): target = ekb_kstring_from_text(self.target) drug = ekb_kstring_from_text(self.drug) content = KQMLList('IS-DRUG-TARGET') content.set('target', target) content.set('drug', drug) return get_request(content), content
def respond_find_disease_targets(self, content): """Response content to find-disease-targets request.""" try: disease_arg = content.gets('disease') disease = get_disease(ET.fromstring(disease_arg)) except Exception as e: logger.error(e) reply = self.make_failure('INVALID_DISEASE') return reply if not trips_isa(disease.disease_type, 'ont::cancer'): reply = self.make_failure('DISEASE_NOT_FOUND') return reply logger.debug('Disease: %s' % disease.name) try: mut_protein, mut_percent, agents = \ self.dtda.get_top_mutation(disease.name) 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 (get from agents) # TODO: get fraction not percentage from DTDA (edit get_top_mutation) reply = KQMLList('SUCCESS') protein = KQMLList() protein.set('name', mut_protein) protein.set('hgnc', mut_protein) reply.set('protein', protein) reply.set('prevalence', '%.2f' % (mut_percent/100.0)) reply.set('functional-effect', 'ACTIVE') return reply
def respond_has_qca_path(self, content): """Response content to find-qca-path request.""" target_arg = content.gets('TARGET') source_arg = content.gets('SOURCE') 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] has_path = self.qca.has_path([source], [target]) reply = KQMLList('SUCCESS') reply.set('haspath', 'TRUE' if has_path else 'FALSE') return reply
def response_error(self, error): reply_content = KQMLList() for e in error: error_msg = '"%s"' %\ str(e).encode('string-escape').replace('"', '\\"') reply_content.add(error_msg) return self.format_error(reply_content.to_string())
def receive_request(self, msg, content): """Handle request messages and respond. If a "request" message is received, decode the task and the content and call the appropriate function to prepare the response. A reply_content message is then sent back. """ try: content = msg.get('content') task_str = content.head().upper() logger.info(task_str) except Exception as e: logger.error('Could not get task string from request.') logger.error(e) return self.error_reply(msg, 'Invalid task') try: if task_str == 'INDRA-TO-NL': reply_content = self.respond_indra_to_nl(content) else: return self.error_reply(msg, 'Unknown task ' + task_str) except Exception as e: logger.error('Failed to perform task.') logger.error(e) reply_content = KQMLList('FAILURE') reply_content.set('reason', 'NL_GENERATION_ERROR') return self.reply_with_content(msg, reply_content)
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)
def make_failure(self, reason=None, description=None): msg = KQMLList('FAILURE') if reason: msg.set('reason', reason) if description: msg.sets('description', description) return msg
def test_respond_choose_nonsense(): bs = BioSense_Module(testing=True) msg_content = KQMLList('CHOOSE-SENSE') msg_content.sets('ekb-term', ekb_from_text('bagel')) res = bs.respond_choose_sense(msg_content) print(res) assert res.head() == 'SUCCESS' assert res.get('agents')[0].gets('ont-type') is None
def send_null_provenance(self, stmt, for_what, reason=''): """Send out that no provenance could be found for a given Statement.""" content_fmt = ('<h4>No supporting evidence found for {statement} from ' '{cause}{reason}.</h4>') content = KQMLList('add-provenance') stmt_txt = EnglishAssembler([stmt]).make_model() content.sets('html', content_fmt.format(statement=stmt_txt, cause=for_what, reason=reason)) return self.tell(content)
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
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
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
def test_respond_get_synonyms(): bs = BioSense_Module(testing=True) msg_content = KQMLList('GET-SYNONYMS') msg_content.sets('entity', mek1_ekb) res = bs.respond_get_synonyms(msg_content) assert res.head() == 'SUCCESS' syns = res.get('synonyms') syn_strs = [s.gets(':name') for s in syns] assert 'MAP2K1' in syn_strs assert 'MEK1' in syn_strs assert 'MKK1' in syn_strs
def respond_test(self): ''' Response content to version message ''' reply_content = KQMLList() version_response = KQMLList.from_string( '' +\ '(ONT::TELL :content ' +\ ')') reply_content.add(KQMLList(version_response)) return reply_content
def test_respond_choose_sense_is_member(): bs = BioSense_Module(testing=True) msg_content = KQMLList('CHOOSE-SENSE-IS-MEMBER') msg_content.sets('ekb-term', mek1_ekb) msg_content.sets('collection', mek_ekb) print(msg_content) res = bs.respond_choose_sense_is_member(msg_content) print(res) print(res.head()) assert(res.head() == 'SUCCESS') assert(res.get('is-member') == 'TRUE')
def respond_find_target_drug(self, content): """Response content to find-target-drug request.""" try: target_arg = content.gets('target') target = self._get_agent(target_arg) except Exception: return self.make_failure('INVALID_TARGET') drug_results = self.dtda.find_target_drugs(target) drugs = self._get_drug_kqml(drug_results) reply = KQMLList('SUCCESS') reply.set('drugs', drugs) return reply
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
def send_display_model(self, diagrams): for diagram_type, resource in diagrams.items(): if not resource: continue if diagram_type == 'sbgn': content = KQMLList('display-sbgn') content.set('type', diagram_type) content.sets('graph', resource) else: content = KQMLList('display-image') content.set('type', diagram_type) content.sets('path', resource) self.tell(content)
def report_paths_graph(self, paths_list): from indra.assemblers.graph import GraphAssembler from indra.util import flatten path_stmts = [stmts_from_json(l) for l in paths_list] all_stmts = flatten(path_stmts) ga = GraphAssembler(all_stmts) ga.make_model() resource = get_img_path('qca_paths.png') ga.save_pdf(resource) content = KQMLList('display-image') content.set('type', 'simulation') content.sets('path', resource) self.tell(content)
def test_respond_choose_sense(): bs = BioSense_Module(testing=True) msg_content = KQMLList('CHOOSE-SENSE') msg_content.sets('ekb-term', mek1_ekb) res = bs.respond_choose_sense(msg_content) print(res) agents = res.get('agents') assert agents and agents.data agent = agents[0] name = agent.gets('name') assert name == 'MAP2K1' ont_type = agent.get('ont-type') assert ont_type == 'ONT::GENE'
def respond_satisfies_pattern(self, content_list): """ Response content to satisfies-pattern request """ model_token = content_list.get_keyword_arg(":model") pattern_lst = content_list.get_keyword_arg(":pattern") conditions_lst = content_list.get_keyword_arg(":conditions") try: model_str = str(model_token) model = decode_model(model_str) except Exception as e: logger.error(e) reply_content = KQMLList.from_string("(FAILURE :reason INVALID_MODEL)") return reply_content try: pattern = get_temporal_pattern(pattern_lst) except InvalidTimeUnitError as e: logger.error(e) reply_content = KQMLList.from_string("(FAILURE :reason INVALID_TIME_LIMIT)") return reply_content except Exception as e: logger.error(e) reply_content = KQMLList.from_string("(FAILURE :reason INVALID_PATTERN)") 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.error(e) msg_str = "(FAILURE :reason INVALID_CONDITIONS)" reply_content = KQMLList.from_string(msg_str) return reply_content try: sat_rate, num_sim = self.tra.check_property(model, pattern, conditions) except SimulatorError as e: logger.error(e) reply_content = KQMLList.from_string("(FAILURE :reason KAPPA_FAILURE)") return reply_content except Exception as e: logger.error(e) reply_content = KQMLList.from_string("(FAILURE :reason INVALID_PATTERN)") return reply_content reply_content = KQMLList() msg_str = "(:satisfies-rate %.1f :num-sim %d)" % (sat_rate, num_sim) reply_content.add("SUCCESS :content %s" % msg_str) return reply_content
def respond_model_get_json(self, content): """Return response content to model-get-json request.""" try: model_id = self._get_model_id(content) except Exception: model_id = None model = self.mra.get_model_by_id(model_id) if model is not None: model_msg = encode_indra_stmts(model) reply = KQMLList('SUCCESS') reply.sets('model', model_msg) else: reply = self.make_failure('MISSING_MODEL') return reply
def respond_describe_model(self, content): """Convert the model to natural language.""" # Get the model. model_id = self._get_model_id(content) model = self.mra.get_model_by_id(model_id) # Turn the model into a text description. english_assembler = EnglishAssembler(model) desc = english_assembler.make_model() # Respond to the BA. resp = KQMLList('SUCCESS') resp.sets('description', desc) return resp
def test_respond_choose_sense_what_member(): bs = BioSense_Module(testing=True) msg_content = KQMLList('CHOOSE-SENSE-WHAT-MEMBER') msg_content.sets('collection', mek_ekb) print(msg_content) res = bs.respond_choose_sense_what_member(msg_content) print(res) print(res.head()) assert(res.head() == 'SUCCESS') assert(len(res.get('members')) == 2) m1 = res.get('members')[0] m2 = res.get('members')[1] assert m1.gets('name') == 'MAP2K1', m1.gets('name') assert m2.gets('name') == 'MAP2K2', m2.gets('name')
def respond_choose_sense_category(self, content): """Return response content to choose-sense-category request.""" ekb = content.gets('ekb-term') category = content.gets('category') try: in_category = self.bs.choose_sense_category(ekb, category) except InvalidAgentError: msg = make_failure('INVALID_AGENT') except UnknownCategoryError: msg = make_failure('UNKNOWN_CATEGORY') else: msg = KQMLList('SUCCESS') msg.set('in-category', 'TRUE' if in_category else 'FALSE') return msg
def respond_start(self, arguments): ''' Response content to start message ''' if "CODE" not in arguments: response_content = self.response_error(["Missing code"]) elif "NB_PLOT" not in arguments: response_content =\ self.response_error(["Missing number of plot points"]) else: try: parameter = {} parameter["nb_plot"] = arguments["NB_PLOT"] if "MAX_TIME" in arguments: parameter["max_time"] = float(arguments["MAX_TIME"]) if "MAX_EVENTS" in arguments: parameter["max_events"] = int(arguments["MAX_EVENTS"]) request_code = arguments["CODE"] request_code = request_code[1:-1] request_code = request_code.decode('string_escape') parameter["code"] = request_code try: logger.debug(parameter) response = self.kappa.start(parameter) response_message = '(SUCCESS :id %d)' % response response_content = KQMLList.from_string(response_message) except RuntimeError as e: response_content = self.response_error(e.errors) except ValueError as e: response_content = self.response_error([str(e)]) return response_content
def respond_choose_sense_what_member(self, content): """Return response content to choose-sense-what-member request.""" # Get the collection agent ekb = content.gets('collection') try: members = self.bs.choose_sense_what_member(ekb) except InvalidCollectionError: msg = make_failure('INVALID_COLLECTION') except CollectionNotFamilyOrComplexError: msg = make_failure('COLLECTION_NOT_FAMILY_OR_COMPLEX') else: kagents = [get_kagent((m, 'ONT::PROTEIN', _get_urls(m))) for m in members] msg = KQMLList('SUCCESS') msg.set('members', KQMLList(kagents)) return msg
def respond_build_model(self, content_list): """ Response content to build-model request """ try: descr_arg = content_list.get_keyword_arg(":description") descr = descr_arg[0].to_string() descr = self.decode_description(descr) model = self.mra.build_model_from_ekb(descr) except Exception as e: raise InvalidModelDescriptionError(e) if model is None: raise InvalidModelDescriptionError self.get_context(model) self.models.append(model) model_id = len(self.models) model_enc = self.encode_model(model) try: model_diagram = self.get_model_diagram(model, model_id) except DiagramGenerationError as e: logger.error("Could not generate model diagram.") logger.error(e) model_diagram = "" except DiagramConversionError as e: logger.error("Could not save model diagram.") logger.error(e) model_diagram = "" reply_content = KQMLList.from_string( '(SUCCESS :model-id %s :model "%s" :diagram "%s")' % (model_id, model_enc, model_diagram) ) return reply_content
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)
def respond_has_mechanism(self, content_list): """ Response content to model-has-mechanism request """ try: descr_arg = content_list.get_keyword_arg(":description") descr = descr_arg[0].to_string() descr = self.decode_description(descr) except Exception as e: raise InvalidModelDescriptionError(e) model_id_arg = content_list.get_keyword_arg(":model-id") if model_id_arg is None: logger.error("Model ID missing.") raise InvalidModelIdError try: model_id_str = model_id_arg.to_string() model_id = int(model_id_str) except Exception as e: logger.error("Could not get model ID as integer.") raise InvalidModelIdError(e) if model_id < 1 or model_id > len(self.models): logger.error("Model ID does not refer to an existing model.") raise InvalidModelIdError try: has_mechanism = self.mra.has_mechanism(descr, model_id) except Exception as e: raise InvalidModelDescriptionError reply_content = KQMLList.from_string("(SUCCESS :model-id %s :has-mechanism %s)" % (model_id, has_mechanism)) return reply_content
def test_get_temporal_pattern(): pattern_msg = '(:type "transient" :entities ((:description ' + \ '%s)))' % clj_complex lst = KQMLList.from_string(pattern_msg) pattern = tra_module.get_temporal_pattern(lst) assert pattern.pattern_type == 'transient'
def test_get_molecular_condition_badvalue(): lst = KQMLList.from_string('(:type "multiple" :value "xyz" ' + ':quantity (:type "total" ' + ':entity (:description %s)))' % clj_braf) tra_module.get_molecular_condition(lst)
def test_molecular_quantity_badentity(): s = '(:type "xyz" :entity (:description "xyz"))' lst = KQMLList.from_string(s) tra_module.get_molecular_quantity_ref(lst)
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
def create_message(self): model = stmts_clj_from_text('MAP2K1 binds MAPK1') entity = agent_clj_from_text('MAPK1-MAP2K1 complex') condition_entity = agent_clj_from_text('MAP2K1') entities = KQMLList([KQMLList([':description', entity])]) pattern = KQMLList() pattern.set('entities', entities) pattern.sets('type', 'no_change') value = KQMLList() value.sets('type', 'qualitative') value.sets('value', 'high') pattern.set('value', value) content = KQMLList('SATISFIES-PATTERN') content.set('pattern', pattern) content.set('model', model) conditions = KQMLList() condition = KQMLList() condition.sets('type', 'multiple') condition.set('value', '10.0') quantity = KQMLList() quantity.sets('type', 'total') entity = KQMLList() entity.set('description', condition_entity) quantity.set('entity', entity) condition.set('quantity', quantity) conditions.append(condition) content.set('conditions', conditions) msg = get_request(content) return (msg, content)
def test_molecular_quantity_badtype(): s = '(:type "xyz" :entity (:description %s))' % clj_complex lst = KQMLList.from_string(s) tra_module.get_molecular_quantity_ref(lst)
def test_get_molecular_condition_badentity(): lst = KQMLList.from_string('(:type "exact" :value 2 ' + ':quantity (:type "total" ' + ':entity (:description "xyz")))') tra_module.get_molecular_condition(lst)
def format_error(self, message): response_content = KQMLList.from_string('(FAILURE :reason %s)' % message) return response_content
def test_molecular_quantity_qual_badval(): s = '(:type "qualitative" :value 123)' lst = KQMLList.from_string(s) tra_module.get_molecular_quantity(lst)
def test_molecular_quantity_qual(): s = '(:type "qualitative" :value "high")' lst = KQMLList.from_string(s) mq = tra_module.get_molecular_quantity(lst) assert mq.quant_type == 'qualitative' assert mq.value == 'high'
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 test_molecular_quantity_num_badval(): s = '(:type "number" :value -1)' lst = KQMLList.from_string(s) tra_module.get_molecular_quantity(lst)
def create_message(self): model = stmts_clj_from_text('MEK binds ERK') entity = agent_clj_from_text('MEK that is bound to ERK') entities = KQMLList([KQMLList([':description', entity])]) pattern = KQMLList() pattern.set('entities', entities) pattern.sets('type', 'no_change') value = KQMLList() value.sets('type', 'qualitative') value.sets('value', 'low') pattern.set('value', value) content = KQMLList('SATISFIES-PATTERN') content.set('pattern', pattern) content.set('model', model) msg = get_request(content) return (msg, content)
def test_get_molecular_entity(): me = KQMLList.from_string('(:description %s)' % clj_complex) ent = tra_module.get_molecular_entity(me) assert len(ent.bound_conditions) == 1, len(ent.bound_conditions)