def get_im(self, force_update=True): """Get the influence map for the model, generating it if necessary. Parameters ---------- force_update : bool Whether to generate the influence map when the function is called. If False, returns the previously generated influence map if available. Defaults to True. Returns ------- pygraphviz AGraph object containing the influence map. The influence map can be rendered as a pdf using the dot layout program as follows:: influence_map.draw('influence_map.pdf', prog='dot') """ if self._im and not force_update: return self._im if not self.model: raise Exception("Cannot get influence map if there is no model.") else: logger.info("Generating influence map") self._im = kappa.influence_map(self.model) self._im.is_multigraph = lambda: False return self._im
def make_influence_map(pysb_model, model_id): """Generate a Kappa influence map.""" try: im = kappa.influence_map(pysb_model) fname = 'model%d_im' % model_id abs_path = os.path.abspath(os.getcwd()) full_path = os.path.join(abs_path, fname + '.png') im.draw(full_path, prog='dot') except Exception: return None return full_path
def main(argv): if len(sys.argv) != 3: print "Usage: %s model_filename im_filename" % __file__ return 1 model_filename = argv[1] im_filename = argv[2] # Sanity checks on filename if not os.path.exists(model_filename): raise Exception("File '%s' doesn't exist" % model_filename) if not re.search(r'\.py$', model_filename): raise Exception("File '%s' is not a .py file" % model_filename) sys.path.insert(0, os.path.dirname(model_filename)) model_name = re.sub(r'\.py$', '', os.path.basename(model_filename)) # import it try: # FIXME if the model has the same name as some other "real" module # which we use, there will be trouble (use the imp package and import # as some safe name?) model_module = __import__(model_name) except StandardError as e: print "Error in model script:\n" raise # grab the 'model' variable from the module try: model = model_module.__dict__['model'] except KeyError: raise Exception("File '%s' isn't a model file" % model_filename) # Make the contact map im_output_filename = kappa.influence_map(model, base_filename=im_filename) # Process the influence map file to fix the extra newlines im_output_file = open(im_output_filename) im_output_file_fixed = open('%s_fixed.dot' % im_filename, 'w') for line in im_output_file.readlines(): fixed_line = re.sub('label="\n', 'label="', line) im_output_file_fixed.write(fixed_line) im_output_file.close() im_output_file_fixed.close() return 0
def get_im(self, force_update=False): """Get the influence map for the model, generating it if necessary. Parameters ---------- force_update : bool Whether to generate the influence map when the function is called. If False, returns the previously generated influence map if available. Defaults to True. Returns ------- pygraphviz AGraph object containing the influence map. The influence map can be rendered as a pdf using the dot layout program as follows:: influence_map.draw('influence_map.pdf', prog='dot') """ if self._im and not force_update: return self._im if not self.model: raise Exception("Cannot get influence map if there is no model.") def add_obs_for_agent(agent): obj_mps = list(pa.grounded_monomer_patterns(self.model, agent)) if not obj_mps: logger.debug( 'No monomer patterns found in model for agent %s, ' 'skipping' % agent) return obs_list = [] for obj_mp in obj_mps: obs_name = _monomer_pattern_label(obj_mp) + '_obs' # Add the observable obj_obs = Observable(obs_name, obj_mp, _export=False) obs_list.append(obs_name) try: self.model.add_component(obj_obs) except ComponentDuplicateNameError as e: pass return obs_list # Create observables for all statements to check, and add to model # Remove any existing observables in the model self.model.observables = ComponentSet([]) for stmt in self.statements: # Generate observables for Modification statements if isinstance(stmt, Modification): mod_condition_name = modclass_to_modtype[stmt.__class__] if isinstance(stmt, RemoveModification): mod_condition_name = modtype_to_inverse[mod_condition_name] # Add modification to substrate agent modified_sub = _add_modification_to_agent( stmt.sub, mod_condition_name, stmt.residue, stmt.position) obs_list = add_obs_for_agent(modified_sub) # Associate this statement with this observable self.stmt_to_obs[stmt] = obs_list # Generate observables for Activation/Inhibition statements elif isinstance(stmt, RegulateActivity): regulated_obj, polarity = \ _add_activity_to_agent(stmt.obj, stmt.obj_activity, stmt.is_activation) obs_list = add_obs_for_agent(regulated_obj) # Associate this statement with this observable self.stmt_to_obs[stmt] = obs_list elif isinstance(stmt, RegulateAmount): obs_list = add_obs_for_agent(stmt.obj) self.stmt_to_obs[stmt] = obs_list # Add observables for each agent for ag in self.agent_obs: obs_list = add_obs_for_agent(ag) self.agent_to_obs[ag] = obs_list logger.info("Generating influence map") self._im = kappa.influence_map(self.model) #self._im.is_multigraph = lambda: False # Now, for every rule in the model, check if there are any observables # downstream # Alternatively, for every observable in the model, get a list of rules # We'll need the dictionary to check if nodes are observables node_attributes = nx.get_node_attributes(self._im, 'shape') for rule in self.model.rules: obs_list = [] # Get successors of the rule node for neighb in self._im.neighbors(rule.name): # Check if the node is an observable if node_attributes[neighb] != 'ellipse': continue # Get the edge and check the polarity edge_sign = _get_edge_sign(self._im, (rule.name, neighb)) obs_list.append((neighb, edge_sign)) self.rule_obs_dict[rule.name] = obs_list return self._im
import pickle import itertools from pysb import kappa from indra.explanation.model_checker.pysb import remove_im_params from assemble_models import prefixed_pkl print("Loading") with open(prefixed_pkl('pysb_model'), 'rb') as f: model = pickle.load(f) print("Generating influence map") im = kappa.influence_map(model) remove_im_params(model, im) predecessors = im.predecessors_iter successors = im.successors_iter combos = list(itertools.combinations(im.nodes(), 2)) # Examine all pairs of nodes for ix, (p1, p2) in enumerate(combos): if ix % 1000 == 0: print("%d of %d" % (ix + 1, len(combos))) p1_children = set(successors(p1)) p2_children = set(successors(p2)) if p1_children == p2_children: #print("Same children") pass elif not p1_children.intersection(p2_children): #print("No shared children") pass # Some shared children, not all else:
from pysb import kappa from pysb.annotation import Citation, Context from nose.tools import assert_true from tBid_Bax_sitec import tBid_Bax_sitec m = tBid_Bax_sitec(scaling_factor=1) m.build_model0() # Run the static analysis and get the graph back through PyGraphViz # Set model conditions to those of the experiment m['Vesicles_0'].value = 1 m['Bax_0'].value = 1 im_filename = kappa.influence_map(m.model) inf_map = nx.Graph(pgv.AGraph(im_filename)) # Yethon et al. paper (2003) # ========================== yethon = Citation( """Interaction with a Membrane Surface Triggers a Reversible Conformational Change in Bax Normally Associated with Induction of Apoptosis""", """Jeremy A. Yethon, Raquel F. Epand, Brian Leber, Richard M. Epand, and David W. Andrews""", "14522999" ) # Observations from this paper, roughly in the order in which they are # mentioned: