def get_path_stmts(results, model, stmts): all_path_stmts = [] for drug, target, polarity, value, found_path, paths, flag in results: path_stmts = {} for path in paths: path_stmts1 = stmts_from_pysb_path(path, model, stmts) for ps in path_stmts1: path_stmts[ps.uuid] = ps all_path_stmts.append(path_stmts) return all_path_stmts
def report_paths(scored_paths, model, stmts, cell_line): """Report paths for a specific cell line.""" citations = {} citation_count = 1 ab_name = 'Total c-Jun' if cell_line == 'C32': pol = 'decreased' else: pol = 'increased' for drug in scored_paths.keys(): paths = scored_paths[drug] for path, score in paths[:1]: title = 'How does %s treatment result in %s %s' % \ (drug, pol, ab_name) title += ' in %s cells?' % cell_line print(title) print('=' * len(title)) path_stmts = stmts_from_pysb_path(path, model, stmts) sentences = [] for i, stmt in enumerate(path_stmts): if i == 0: target = stmt.agent_list()[0].name sentences.append('%s is a target of %s.' % (target, drug)) # Make citations pmids = [ev.pmid for ev in stmt.evidence if ev.pmid] cit_nums = [] for pmid in pmids: cit_num = citations.get(pmid) if cit_num is None: citations[pmid] = citation_count cit_num = citation_count citation_count += 1 cit_nums.append(cit_num) if cit_nums: cit_nums = sorted(list(set(cit_nums))) cit_str = ' [%s]' % (','.join([str(c) for c in cit_nums])) else: cit_str = '' ea = EnglishAssembler([stmt]) sentence = ea.make_model() sentence = sentence[:-1] + cit_str + '.' sentences.append(sentence) sentences[-1] = sentences[-1][:-1] + \ ', which is measured by %s.' % ab_name print(' '.join(sentences)) print() references = 'References\n==========\n' for k, v in sorted(citations.items(), key=lambda x: x[1]): references += '[%d] https://www.ncbi.nlm.nih.gov/pubmed/%s\n' % (v, k) print(references)
def export_paths(scored_paths, model, stmts): """Export paths for pathway map in JSON-like format.""" conc = 1.0 time = 10 paths = {} for cell_line in scored_paths.keys(): for drug in scored_paths[cell_line].keys(): scpaths = scored_paths[cell_line][drug] path, score = scpaths[0] label = '%s_%s_%s_%s' % (drug, time, conc, cell_line) paths[label] = {'meta': [], 'path': []} path_stmts = stmts_from_pysb_path(path, model, stmts) uuids = [stmt.uuid for stmt in path_stmts] paths[label]['path'] = uuids return paths
def make_english_path(self, mc_type, result): """Create an English description of a path.""" paths = [] if result.paths: for path in result.paths: sentences = [] if mc_type == 'signed_graph' or mc_type == 'unsigned_graph': for i in range(len(path[:-1])): sentence = path[i][0] + ' -> ' + path[i + 1][0] sentences.append((sentence, '')) else: if mc_type == 'pysb': stmts = stmts_from_pysb_path( path, self.mc_types['pysb']['model'], self.model.assembled_stmts) elif mc_type == 'pybel': stmts = stmts_from_pybel_path( path, self.mc_types['pybel']['model'], from_db=False, stmts=self.model.assembled_stmts) for stmt in stmts: if not stmt: continue if isinstance(stmt, list): stmt = stmt[0] ea = EnglishAssembler([stmt]) sentence = ea.make_model() if self.make_links: link = get_statement_queries( [stmt])[0] + '&format=html' sentences.append((sentence, link)) else: sentences.append((sentence, '')) paths.append(sentences) return paths
def check_explanation(self): if self.model is None: raise ValueError('check_explanation requires a PySB model.') if self.explain is None: raise ValueError('check_explanation requires an explanation goal.') result = {} mc = PysbModelChecker(self.model, [self.explain]) try: pr = mc.check_statement(self.explain, max_paths=0) result['has_explanation'] = pr.path_found except Exception as e: logger.error("Error checking statement for paths: %s" % str(e)) result['has_explanation'] = False # If we found a path get a path if result['has_explanation']: try: pr = mc.check_statement(self.explain, max_paths=1, max_path_length=8) path_stmts = stmts_from_pysb_path(pr.paths[0], self.model, self.statements) result['explanation_path'] = path_stmts except Exception as e: logger.error("Error getting paths for statement: %s" % str(e)) # If we don't already have an explanation, see if we can propose one else: # Get the source rules associated with the statement to explain source_rules = [] subj_mps = grounded_monomer_patterns(self.model, self.explain.agent_list()[0]) for subj_mp in subj_mps: source_rules += mc._get_input_rules(subj_mp) obs_container = mc.stmt_to_obs[self.explain] # If we've got both source rules and observable names, add dummy # nodes for the source (connected to all input rules) and the # target (connected to all observables) so we only have to deal # with a single source and a single target if source_rules and obs_container: new_edges = [('SOURCE', sr) for sr in source_rules] new_edges += [(on, 'TARGET') for on, _ in obs_container.main_nodes] im = mc.get_im() im.add_edges_from(new_edges) # Now, we know that there is no path between SOURCE and TARGET. # Instead, we consider connections among all possible pairs # of nodes in the graph and count the number of nodes in # the path between source and target: best_edge = (None, 0) for u, v in itertools.permutations(im.nodes(), 2): # Add the edge to the graph im.add_edge(u, v) # Find longest path between source and target simple_paths = list( nx.all_simple_paths(im, 'SOURCE', 'TARGET')) simple_paths.sort(key=lambda p: len(p), reverse=True) if simple_paths and len(simple_paths[0]) > best_edge[1]: best_edge = ((u, v), len(simple_paths[0])) # Now remove the edge we added before going on to the next im.remove_edge(u, v) if best_edge[0]: result['connect_rules'] = best_edge[0] u_stmt = stmt_from_rule(best_edge[0][0], self.model, self.statements) v_stmt = stmt_from_rule(best_edge[0][1], self.model, self.statements) if u_stmt and v_stmt: result['connect_stmts'] = (u_stmt, v_stmt) logger.info("Model statements: %s" % str(self.statements)) logger.info("To explain %s, try connecting %s and %s" % (self.explain, u_stmt, v_stmt)) return result
def path_to_english(path, model, stmts): path_stmts = stmts_from_pysb_path(path, model, stmts) ea = EnglishAssembler(path_stmts) return ea.make_model()