def respond_simulate_model(self, content_list): ''' Response content to simulate-model request ''' model_str = content_list.get_keyword_arg(':model') try: #model_str = model_str.to_string() model = self.decode_model(model_str) except InvalidModelDescriptionError as e: logger.error(e) reply_content =\ KQMLList.from_string('(FAILURE :reason INVALID_MODEL)') return reply_content except Exception as e: logger.error(e) reply_content =\ KQMLList.from_string('(FAILURE :reason INVALID_MODEL)') return reply_content target_entity = content_list.get_keyword_arg(':target_entity') if target_entity is not None: target_entity = target_entity.to_string()[1:-1] else: reply_content =\ KQMLList.from_string('(FAILURE :reason MISSING_PARAMETER)') return reply_content target_pattern = content_list.get_keyword_arg(':target_pattern') if target_pattern is not None: target_pattern = target_pattern.to_string().lower() else: reply_content =\ KQMLList.from_string('(FAILURE :reason MISSING_PARAMETER)') return reply_content condition_entity = content_list.get_keyword_arg(':condition_entity') if condition_entity is not None: condition_entity = condition_entity.to_string()[1:-1] condition_type = content_list.get_keyword_arg(':condition_type') if condition_type is not None: condition_type = condition_type.to_string().lower() self.get_context(model) if condition_entity is None: target_match = self.mea.check_pattern(model, target_entity, target_pattern) else: target_match = self.mea.compare_conditions(model, target_entity, target_pattern, condition_entity, condition_type) target_match_str = 'TRUE' if target_match else 'FALSE' reply_content = KQMLList() reply_content.add('SUCCESS :content (:target_match %s)' % target_match_str) return reply_content
def respond_find_treatment(self, content_list): ''' Response content to find-treatment request ''' reply_content = KQMLList() #TODO: eliminate code duplication here disease_arg = content_list.get_keyword_arg(':disease') try: disease = self.get_disease(disease_arg) except Exception as e: logger.error(e) msg_str = '(FAILURE :reason INVALID_DISEASE)' reply_content = KQMLList.from_string(msg_str) return reply_content if disease.disease_type != 'cancer': reply_content.add('FAILURE :reason DISEASE_NOT_FOUND') return reply_content logger.debug('Disease: %s' % disease.name) try: mut_protein, mut_percent = \ self.dtda.get_top_mutation(disease.name) except DiseaseNotFoundException: reply_content.add('FAILURE :reason DISEASE_NOT_FOUND') return reply_content # TODO: get functional effect from actual mutations # TODO: add list of actual mutations to response # TODO: get fraction not percentage from DTDA reply_content.add(KQMLList.from_string( '(SUCCESS ' + ':protein (:name %s :hgnc %s) ' % (mut_protein, mut_protein) + ':prevalence %.2f ' % (mut_percent/100.0) + ':functional-effect ACTIVE)')) # Try to find a drug drug_names, chebi_ids = self.dtda.find_target_drugs(mut_protein) drug_list_str = '' for dn, ci in zip(drug_names, chebi_ids): if ci is None: drug_list_str += '(:name %s) ' % dn.encode('ascii', 'ignore') else: drug_list_str += '(:name %s :chebi_id %s) ' % (dn, ci) reply_content.add(KQMLList.from_string( '(SUCCESS :drugs (' + drug_list_str + '))')) return reply_content
def test_undo(): mm = MRA_Module(testing=True) kl = KQMLList.from_string( '(BUILD-MODEL :DESCRIPTION "<ekb><EVENT id=\\"V34357\\"><type>ONT::ACTIVATE</type><arg1 id=\\"V34353\\" role=\\":AGENT\\" /><arg2 id=\\"V34364\\" role=\\":AFFECTED\\" /></EVENT><TERM id=\\"V34364\\" dbid=\\"FA:03114|BE:RAF|NCIT:C51274|UP:Q06891\\"><features></features><type>ONT::GENE-PROTEIN</type><name>RAF</name><drum-terms><drum-term dbid=\\"FA:03114\\" match-score=\\"1.0\\" name=\\"RAF subfamily\\" /><drum-term dbid=\\"BE:RAF\\" match-score=\\"1.0\\" name=\\"RAF\\" /><drum-term dbid=\\"NCIT:C51274\\" match-score=\\"0.82857\\" name=\\"RAF1\\" /><drum-term dbid=\\"UP:Q06891\\" match-score=\\"0.65714\\" name=\\"Trans-acting factor D\\" /></drum-terms></TERM><TERM id=\\"V34353\\" dbid=\\"NCIT:C52545|HGNC:5173|NCIT:C16659|NCIT:C17382\\"><features></features><type>ONT::GENE-PROTEIN</type><name>HRAS</name><drum-terms><drum-term dbid=\\"NCIT:C52545\\" match-score=\\"1.0\\" name=\\"HRAS\\" /><drum-term dbid=\\"HGNC:5173\\" match-score=\\"1.0\\" name=\\"Harvey rat sarcoma viral oncogene homolog\\" /><drum-term dbid=\\"NCIT:C16659\\" match-score=\\"0.82857\\" name=\\"oncogene H-ras\\" /><drum-term dbid=\\"NCIT:C17382\\" match-score=\\"0.82857\\" name=\\"p21 H-ras protein\\" /></drum-terms></TERM></ekb>")' ) reply = mm.respond_build_model(kl) print(reply) kl = KQMLList.from_string( '(EXPAND-MODEL :MODEL-ID 1 :DESCRIPTION "<ekb><EVENT id=\\"V34455\\"><type>ONT::ACTIVATE</type><arg1 id=\\"V34451\\" role=\\":AGENT\\" /><arg2 id=\\"V34462\\" role=\\":AFFECTED\\" /></EVENT><TERM id=\\"V34462\\" dbid=\\"FA:03114|BE:RAF|NCIT:C51274|UP:Q06891\\"><features></features><type>ONT::GENE-PROTEIN</type><name>RAF</name><drum-terms><drum-term dbid=\\"FA:03114\\" match-score=\\"1.0\\" name=\\"RAF subfamily\\" /><drum-term dbid=\\"BE:RAF\\" match-score=\\"1.0\\" name=\\"RAF\\" /><drum-term dbid=\\"NCIT:C51274\\" match-score=\\"0.82857\\" name=\\"RAF1\\" /><drum-term dbid=\\"UP:Q06891\\" match-score=\\"0.65714\\" name=\\"Trans-acting factor D\\" /></drum-terms></TERM><TERM id=\\"V34451\\" dbid=\\"NCIT:C52549|HGNC:7989|NCIT:C16889|NCIT:C17384\\"><features></features><type>ONT::GENE-PROTEIN</type><name>NRAS</name><drum-terms><drum-term dbid=\\"NCIT:C52549\\" match-score=\\"1.0\\" name=\\"NRAS\\" /><drum-term dbid=\\"HGNC:7989\\" match-score=\\"1.0\\" name=\\"neuroblastoma RAS viral oncogene homolog\\" /><drum-term dbid=\\"NCIT:C16889\\" match-score=\\"0.82857\\" name=\\"oncogene N-RAS\\" /><drum-term dbid=\\"NCIT:C17384\\" match-score=\\"0.82857\\" name=\\"p21 N-ras protein\\" /></drum-terms></TERM></ekb>")' ) reply = mm.respond_expand_model(kl) print(reply) kl = KQMLList.from_string('(MODEL-UNDO)') reply = mm.respond_model_undo(kl) print(reply)
def test_molecular_quantity_ref2(): s = '(:type "initial" :entity (:description %s))' % clj_complex lst = KQMLList.from_string(s) mqr = tra_module.get_molecular_quantity_ref(lst) assert mqr.quant_type == 'initial' assert len(mqr.entity.bound_conditions) == 1, \ len(mqr.entity.bound_conditions)
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)
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)
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 test_get_molecular_condition_dec(): lst = KQMLList.from_string('(:type "decrease" :quantity (:type "total" ' + ':entity (:description %s)))' % clj_braf) mc = tra_module.get_molecular_condition(lst) assert mc.condition_type == 'decrease' assert mc.quantity.quant_type == 'total' assert mc.quantity.entity.name == 'BRAF'
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 get_ambiguities_msg(ambiguities): sa = [] for term_id, ambiguity in ambiguities.items(): pr = ambiguity[0]['preferred'] pr_dbids = '|'.join([ '::'.join((k, v)) for k, v in sorted(pr['refs'].items(), key=lambda x: x[0]) ]) # TODO: once available, replace with real ont type pr_type = 'ONT::PROTEIN' s1 = '(term :ont-type %s :ids "%s" :name "%s")' % \ (pr_type, pr_dbids, pr['name']) alt = ambiguity[0]['alternative'] alt_dbids = '|'.join([ '::'.join((k, v)) for k, v in sorted(alt['refs'].items(), key=lambda x: x[0]) ]) # TODO: once available, replace with real ont type alt_type = 'ONT::PROTEIN-FAMILY' s2 = '(term :ont-type %s :ids "%s" :name "%s")' % \ (alt_type, alt_dbids, alt['name']) s = '(%s :preferred %s :alternative %s)' % \ (term_id, s1, s2) sa.append(s) ambiguities_msg = KQMLList.from_string('(' + ' '.join(sa) + ')') return ambiguities_msg
def test_get_time_interval_ub(): ts = '(:upper-bound 4 :unit "hour")' lst = KQMLList.from_string(ts) ti = tra_module.get_time_interval(lst) assert ti.lb is None assert ti.ub == 4 * units.hours assert ti.get_ub_seconds() == 14400
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 respond_satisfies_pattern(self, content): """Return response content to satisfies-pattern request.""" model_indra_str = content.gets('model') pattern_lst = content.get('pattern') conditions_lst = content.get('conditions') try: model = assemble_model(model_indra_str) except Exception as e: logger.error(e) reply_content = self.make_failure('INVALID_MODEL') return reply_content try: pattern = get_temporal_pattern(pattern_lst) except InvalidTimeIntervalError as e: logger.error(e) reply_content = self.make_failure('INVALID_TIME_LIMIT') return reply_content except InvalidTemporalPatternError as e: logger.error(e) reply_content = self.make_failure('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) reply_content = self.make_failure('INVALID_CONDITIONS') return reply_content try: sat_rate, num_sim, suggestion, fig_path = \ self.tra.check_property(model, pattern, conditions) except SimulatorError as e: logger.error(e) reply_content = self.make_failure('KAPPA_FAILURE') return reply_content except Exception as e: logger.error(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: sugg = KQMLList.from_string(suggestion) content.set('suggestion', sugg) reply.set('content', content) return reply
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)
def test_get_time_interval_lb(): ts = '(:lower-bound 4 :unit "hour")' lst = KQMLList.from_string(ts) ti = tra_module.get_time_interval(lst) assert ti.lb == 4.0 * units.hours, ti.lb assert ti.ub is None assert ti.get_lb_seconds() == 14400
def respond_start(self, arguments): ''' Response content to start_sim 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_sim(parameter) response_message = '(SUCCESS :id %d)' % response response_content = KQMLList.from_string(response_message) except KappaRuntimeError 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_simulate_model(self, content_list): """ Response content to simulate-model request """ model_str = content_list.get_keyword_arg(":model") try: # model_str = model_str.to_string() model = self.decode_model(model_str) except InvalidModelDescriptionError as e: logger.error(e) reply_content = KQMLList.from_string("(FAILURE :reason INVALID_MODEL)") return reply_content except Exception as e: logger.error(e) reply_content = KQMLList.from_string("(FAILURE :reason INVALID_MODEL)") return reply_content target_entity = content_list.get_keyword_arg(":target_entity") if target_entity is not None: target_entity = target_entity.to_string()[1:-1] else: reply_content = KQMLList.from_string("(FAILURE :reason MISSING_PARAMETER)") return reply_content target_pattern = content_list.get_keyword_arg(":target_pattern") if target_pattern is not None: target_pattern = target_pattern.to_string().lower() else: reply_content = KQMLList.from_string("(FAILURE :reason MISSING_PARAMETER)") return reply_content condition_entity = content_list.get_keyword_arg(":condition_entity") if condition_entity is not None: condition_entity = condition_entity.to_string()[1:-1] condition_type = content_list.get_keyword_arg(":condition_type") if condition_type is not None: condition_type = condition_type.to_string().lower() self.get_context(model) if condition_entity is None: target_match = self.mea.check_pattern(model, target_entity, target_pattern) else: target_match = self.mea.compare_conditions( model, target_entity, target_pattern, condition_entity, condition_type ) target_match_str = "TRUE" if target_match else "FALSE" reply_content = KQMLList() reply_content.add("SUCCESS :content (:target_match %s)" % target_match_str) return reply_content
def test_get_time_interval_full(): ts = '(:lower-bound 2 :upper-bound 4 :unit "hour")' lst = KQMLList.from_string(ts) ti = tra_module.get_time_interval(lst) assert ti.lb == 2.0 * units.hour, ti.lb assert ti.ub == 4.0 * units.hour, ti.ub assert ti.get_lb_seconds() == 7200 assert ti.get_ub_seconds() == 14400
def test_get_drug_agent(): kqml_str = _load_kqml('tofacitinib.kqml') kqml = KQMLList.from_string(kqml_str) context = kqml.get('context') graph = KQMLGraph(context) agent = agent_from_term(graph, 'V34850') assert agent.name == 'TOFACITINIB', agent assert 'PUBCHEM' in agent.db_refs, agent.db_refs
def test_apply_condition_multiple(): model = _get_gk_model() lst = KQMLList.from_string('(:type "multiple" :value 2.5 ' + ':quantity (:type "total" ' + ':entity (:description %s)))' % clj_map2k1) mc = tra_module.get_molecular_condition(lst) tra.apply_condition(model, mc) assert model.parameters['MAP2K1_0'].value == 250
def test_get_molecular_condition_multiple(): lst = KQMLList.from_string('(:type "multiple" :value 2 ' + ':quantity (:type "total" ' + ':entity (:description %s)))' % clj_braf) mc = tra_module.get_molecular_condition(lst) assert mc.condition_type == 'multiple' assert mc.value == 2.0 assert mc.quantity.quant_type == 'total' assert mc.quantity.entity.name == 'BRAF'
def test_apply_condition_decrease(): model = _get_gk_model() lst = KQMLList.from_string('(:type "decrease" ' + ':quantity (:type "total" ' + ':entity (:description %s)))' % clj_map2k1) mc = tra_module.get_molecular_condition(lst) pold = model.parameters['MAP2K1_0'].value tra.apply_condition(model, mc) assert model.parameters['MAP2K1_0'].value < pold
def test_get_temporal_pattern_eventual(): pattern_msg = '(:type "eventual_value" :entities ((:description ' + \ '%s)) :value (:type "qualitative" :value "high"))' % \ clj_complex lst = KQMLList.from_string(pattern_msg) pattern = tra_module.get_temporal_pattern(lst) assert pattern.pattern_type == 'eventual_value' assert pattern.value is not None assert pattern.value.quant_type == 'qualitative' assert pattern.value.value == 'high'
def test_active_flag(): kp = KQMLList.from_string( '(INDRA-TO-NL :STATEMENTS "[{\\"obj\\": {\\"db_refs\\": {\\"TEXT\\": \\"MAP-2-K-1\\", \\"HGNC\\": \\"6840\\", \\"UP\\": \\"Q02750\\", \\"NCIT\\": \\"C17808\\"}, \\"name\\": \\"MAP2K1\\"}, \\"type\\": \\"Activation\\", \\"obj_activity\\": \\"activity\\", \\"evidence\\": [{\\"epistemics\\": {\\"section_type\\": null}, \\"source_api\\": \\"trips\\"}], \\"subj\\": {\\"activity\\": {\\"is_active\\": true, \\"activity_type\\": \\"activity\\"}, \\"db_refs\\": {\\"TEXT\\": \\"BRAF\\", \\"HGNC\\": \\"1097\\", \\"UP\\": \\"P15056\\", \\"NCIT\\": \\"C17476\\"}, \\"name\\": \\"BRAF\\"}, \\"id\\": \\"863fec09-025b-4e9b-8863-16e2601741d2\\"}]")' ) bn = BioNLG_Module(testing=True) res = bn.respond_indra_to_nl(kp) nl = res.get('NL') assert (len(nl) == 1) sentence = nl[0].string_value() assert (sentence == 'Active BRAF activates MAP2K1')
def test_get_molecular_condition_exact(): lst = KQMLList.from_string( '(:type "exact" :value (:value 0 :type "number") ' ':quantity (:type "total" ' ':entity (:description %s)))' % clj_braf) mc = tra_module.get_molecular_condition(lst) assert mc.condition_type == 'exact' assert mc.value.quant_type == 'number' assert mc.quantity.quant_type == 'total' assert mc.quantity.entity.name == 'BRAF'
def respond_version(self): ''' Response content to version message ''' response = self.kappa.version() reply_content = KQMLList.from_string( '(SUCCESS ' + ':VERSION "%s" ' % response['version'] + ':BUILD "%s")' % response['build']) logger.debug(reply_content.to_string()) return reply_content
def test_get_temporal_pattern_always(): pattern_msg = '(:type "no_change" :entities ((:description ' + \ '%s)) :value (:type "qualitative" :value "low"))' % \ clj_complex lst = KQMLList.from_string(pattern_msg) pattern = tra_module.get_temporal_pattern(lst) assert pattern.pattern_type == 'no_change' assert pattern.value is not None assert pattern.value.quant_type == 'qualitative' assert pattern.value.value == 'low'
def respond_stop(self, arguments): if "ID" not in arguments: response_content = self.response_error(["Missing simulation id"]) else: try: token = int(arguments["ID"]) status = self.kappa.stop(token) response_content = KQMLList.from_string('(SUCCESS)') except RuntimeError as e: response_content = self.response_error(e.errors) return response_content
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 respond_stop(self, arguments): if "ID" not in arguments: response_content = self.response_error(["Missing simulation id"]) else: try: token = int(arguments["ID"]) status = self.kappa.stop(token) response_content = KQMLList.from_string('(SUCCESS)') except KappaRuntimeError as e: response_content = self.response_error(e.errors) return response_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. """ 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)
def check_response_to_message(self, output): assert output.head() == 'SUCCESS', output mutex = output.get('mutex') test_res = KQMLList.from_string( '((:score 0.0 :group (TP53 CDH1)) ' '(:score 0.0 :group (CDH1 TP53)) ' '(:score 0.0 :group (GATA3 TP53 CDH1)) ' '(:score 0.0 :group (CTCF TP53 CDH1 GATA3)))') # TODO: do this without converting into string assert str(test_res) == str(mutex)
def test_apply_condition_exact(): model = _get_gk_model() lst = KQMLList.from_string( '(:type "exact" :value (:value 0 :type "number") ' ':quantity (:type "total" ' ':entity (:description %s)))' % clj_map2k1) mc = tra_module.get_molecular_condition(lst) tra.apply_condition(model, mc) assert model.parameters['MAP2K1_0'].value == 0 mc.value.value = 2000 tra.apply_condition(model, mc) assert model.parameters['MAP2K1_0'].value == 2000
def test_module(): tra = tra_module.TRA_Module(testing=True) content = KQMLList() pattern_msg = '(:type "sometime_value" :entities ((:description ' + \ '%s)) :value (:type "qualitative" :value "high"))' % \ clj_complex pattern = KQMLList.from_string(pattern_msg) content.set('pattern', pattern) model_json = _get_gk_model_indra() content.sets('model', model_json) res = tra.respond_satisfies_pattern(content) assert res[2] is not None
def from_kqml_str(self, kqml_str): """Create a networkx graph from a KQML string Parameters ---------- kqml_str : str A string representing a KQML message that is to be represented as a graph. """ # Deserialize the KQML string kl = KQMLList.from_string(kqml_str) return self.from_kqml_list(kl)
def respond_find_disease_targets(self, content_list): ''' Response content to find-disease-targets request ''' disease_arg = content_list.get_keyword_arg(':disease') try: disease = self.get_disease(disease_arg) except Exception as e: logger.error(e) msg_str = '(FAILURE :reason INVALID_DISEASE)' reply_content = KQMLList.from_string(msg_str) return reply_content if disease.disease_type != 'cancer': msg_str = '(FAILURE :reason DISEASE_NOT_FOUND)' reply_content = KQMLList.from_string(msg_str) return reply_content logger.debug('Disease: %s' % disease.name) try: mut_protein, mut_percent =\ self.dtda.get_top_mutation(disease.name) except DiseaseNotFoundException: msg_str = '(FAILURE :reason DISEASE_NOT_FOUND)' reply_content = KQMLList.from_string(msg_str) return reply_content # TODO: get functional effect from actual mutations # TODO: add list of actual mutations to response # TODO: get fraction not percentage from DTDA reply_content =\ KQMLList.from_string( '(SUCCESS ' + ':protein (:name %s :hgnc %s) ' % (mut_protein, mut_protein) + ':prevalence %.2f ' % (mut_percent/100.0) + ':functional-effect ACTIVE)') return reply_content
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_find_target_drug(self, content_list): ''' Response content to find-target-drug request ''' target_arg = content_list.get_keyword_arg(':target') target = self._get_target(target_arg) target_name = target.name drug_names, chebi_ids = self.dtda.find_target_drugs(target_name) drug_list_str = '' for dn, ci in zip(drug_names, chebi_ids): if ci is None: drug_list_str += '(:name %s) ' % dn.encode('ascii', 'ignore') else: drug_list_str += '(:name %s :chebi_id %s) ' % (dn, ci) reply_content = KQMLList.from_string( '(SUCCESS :drugs (' + drug_list_str + '))') return reply_content
def respond_expand_model(self, content_list): """ Response content to expand-model 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: model = self.mra.expand_model_from_ekb(descr, model_id) except Exception as e: raise InvalidModelDescriptionError self.get_context(model) self.models.append(model) new_model_id = len(self.models) model_enc = self.encode_model(model) try: model_diagram = self.get_model_diagram(model, new_model_id) except DiagramGenerationError: model_diagram = "" except DiagramConversionError: model_diagram = "" reply_content = KQMLList.from_string( '(SUCCESS :model-id %s :model "%s" :diagram "%s")' % (new_model_id, model_enc, model_diagram) ) return reply_content
def respond_parse(self, arguments): ''' Response content to compile message ''' if "CODE" not in arguments: reply_content = self.response_error(["Missing code"]) else: request_code = arguments["CODE"] request_code = request_code[1:-1] logger.debug('raw {0}'.format(request_code)) request_code = request_code.decode('string_escape') logger.debug('respond_parse {0}'.format(request_code)) reply_content = KQMLList() try: response = self.kappa.compile(request_code) logger.debug(response) reply_content = KQMLList.from_string('(SUCCESS)') except KappaRuntimeError as e: logger.debug(e.errors) reply_content = self.response_error(e.errors) return reply_content
def respond_parse(self, arguments): ''' Response content to parse message ''' if "CODE" not in arguments: reply_content = self.response_error(["Missing code"]) else: request_code = arguments["CODE"] request_code = request_code[1:-1] logger.debug('raw {0}'.format(request_code)) request_code = request_code.decode('string_escape') logger.debug('respond_parse {0}'.format(request_code)) reply_content = KQMLList() try: response = self.kappa.parse(request_code) logger.debug(response) reply_content = KQMLList.from_string('(SUCCESS)') except RuntimeError as e: logger.debug(e.errors) reply_content = self.response_error(e.errors) return reply_content
def get_ambiguities_msg(ambiguities): sa = [] for term_id, ambiguity in ambiguities.items(): pr = ambiguity[0]['preferred'] pr_dbids = '|'.join(['::'.join((k, v)) for k, v in sorted(pr['refs'].items(), key=lambda x: x[0])]) # TODO: once available, replace with real ont type pr_type = 'ONT::PROTEIN' s1 = '(term :ont-type %s :ids "%s" :name "%s")' % \ (pr_type, pr_dbids, pr['name']) alt = ambiguity[0]['alternative'] alt_dbids = '|'.join(['::'.join((k, v)) for k, v in sorted(alt['refs'].items(), key=lambda x: x[0])]) # TODO: once available, replace with real ont type alt_type = 'ONT::PROTEIN-FAMILY' s2 = '(term :ont-type %s :ids "%s" :name "%s")' % \ (alt_type, alt_dbids, alt['name']) s = '(%s :preferred %s :alternative %s)' % \ (term_id, s1, s2) sa.append(s) ambiguities_msg = KQMLList.from_string('(' + ' '.join(sa) + ')') return ambiguities_msg
def create_message(self): content = KQMLList.from_string(_load_kqml(self.kqml_file)) assert content.head().upper() == 'GET-INDRA-REPRESENTATION' return get_request(content), content
def respond_satisfies_pattern(self, content): """Return response content to satisfies-pattern request.""" model_indra_str = content.gets('model') pattern_lst = content.get('pattern') conditions_lst = content.get('conditions') try: stmts = decode_indra_stmts(model_indra_str) 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, 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') 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: sugg = KQMLList.from_string(suggestion) content.set('suggestion', sugg) reply.set('content', content) return reply
def format_error(self, message): response_content = KQMLList.from_string( '(FAILURE :reason %s)' % message) return response_content
def test_is_drug_target(): req = '(IS-DRUG-TARGET :DRUG "<ekb><TERM id=\\"V33937\\" dbid=\\"CHEBI:63637\\"><features></features><type>ONT::MOLECULE</type><name>VEMURAFENIB</name><drum-terms><drum-term dbid=\\"CHEBI:63637\\" match-score=\\"1.0\\" name=\\"vemurafenib\\" /></drum-terms></TERM></ekb>" :TARGET "<ekb><TERM id=\\"V33952\\" dbid=\\"HGNC:1097|NCIT:C51194|NCIT:C17476\\"><features></features><type>ONT::GENE-PROTEIN</type><name>BRAF</name><drum-terms><drum-term dbid=\\"HGNC:1097\\" match-score=\\"0.99587\\" name=\\"B-Raf proto-oncogene, serine/threonine kinase\\" /><drum-term dbid=\\"NCIT:C51194\\" match-score=\\"0.99587\\" name=\\"BRAF\\" /><drum-term dbid=\\"NCIT:C17476\\" match-score=\\"0.82444\\" name=\\"B-RAF protein kinase\\" /></drum-terms></TERM></ekb>")' req_msg = KQMLList.from_string(req) dm = DTDA_Module(testing=True) res = dm.respond_is_drug_target(req_msg) assert (res.to_string() == '(SUCCESS :is-target TRUE)')
def term_to_ekb(self, term_id): self._add_to_stack(term_id) node = self.graph.nodes[term_id] term = etree.Element('TERM', id=term_id) # Set the type of the TERM type = etree.Element('type') type.text = node['type'] term.append(type) self.type = node['type'] if node['type'].upper() == 'ONT::MACROMOLECULAR-COMPLEX': c1 = self.graph.get_matching_node(term_id, link='m-sequence') c2 = self.graph.get_matching_node(term_id, link='m-sequence1') components = etree.Element('components') if c1: self.term_to_ekb(c1) c1tag = etree.Element('component', id=c1) components.append(c1tag) if c2: self.term_to_ekb(c2) c2tag = etree.Element('component', id=c2) components.append(c2tag) term.append(components) self._pop_stack(term_id) self.ekb.append(term) return # Handle the case of the signaling pathways. # Note: It turns out this will be wiped out by TRIPS further down the # line. elif node['type'].upper() == 'ONT::SIGNALING-PATHWAY': path_subject_id = self.graph.get_matching_node(term_id, link='assoc-with') path_subject_name = self.get_term_name(path_subject_id) name_val = path_subject_name.upper() + '-SIGNALING-PATHWAY' # This is a LITTLE bit hacky: all further information should come # from this associated-with term, because the root term has no # information. self._pop_stack(term_id) term_id = path_subject_id self._add_to_stack(term_id) # Handle the case where this is just another protein. else: name_val = self.get_term_name(term_id) name = etree.Element('name') name.text = name_val term.append(name) # Now deal with DRUM content drum_node = self.graph.get_matching_node(term_id, link='drum') if drum_node: drum_kqml = KQMLList.from_string( self.graph.nodes[drum_node]['kqml']) drum_terms = etree.Element('drum-terms') for drum_term in drum_kqml[0][1:]: dt = drum_term_to_ekb(drum_term) if dt is not None: drum_terms.append(dt) term.append(drum_terms) # Deal next with modifier events mod = self.graph.get_matching_node(term_id, link='mod') activity_id = self.graph.get_matching_node(term_id, link='active') if mod or activity_id: features = etree.Element('features') if mod: if self._is_new_id(mod): self.event_to_ekb(mod) event = self.graph.nodes[mod] activity = event['type'].upper()[5:] if activity in {'ACTIVE', 'INACTIVE'}: active = etree.Element('active') if activity == 'ACTIVE': active.text = 'TRUE' else: active.text = 'FALSE' features.append(active) else: inevent = etree.Element('inevent', id=mod) features.append(inevent) if activity_id: activity = self.graph.nodes[activity_id] if activity.get('label') == 'ONT::TRUE': active = etree.Element('active') active.text = 'TRUE' features.append(active) term.append(features) self._pop_stack(term_id) self.ekb.append(term)