def generate_network(model, cleanup=True, append_stdout=False): """Run a model through BNG's generate_network function and return the content of the resulting .net file as a string""" gen = BngGenerator(model) bng_filename = '%s_%d_%d_temp.bngl' % (model.name, os.getpid(), random.randint(0, 10000)) net_filename = bng_filename.replace('.bngl', '.net') output = StringIO() try: bng_file = open(bng_filename, 'w') bng_file.write(gen.get_content()) bng_file.write(generate_network_code) bng_file.close() p = subprocess.Popen(['perl', bng_path, bng_filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (p_out, p_err) = p.communicate() if p.returncode: raise GenerateNetworkError(p_out.rstrip()+"\n"+p_err.rstrip()) net_file = open(net_filename, 'r') output.write(net_file.read()) net_file.close() if append_stdout: output.write("#\n# BioNetGen execution log follows\n# ==========") output.write(re.sub(r'(^|\n)', r'\n# ', p_out)) finally: if cleanup: for filename in [bng_filename, net_filename]: if os.access(filename, os.F_OK): os.unlink(filename) return output.getvalue()
def generate_network(model, cleanup=True, append_stdout=False): """Run a model through BNG's generate_network function and return the content of the resulting .net file as a string""" gen = BngGenerator(model) bng_filename = '%s_%d_%d_temp.bngl' % (model.name, os.getpid(), random.randint(0, 10000)) net_filename = bng_filename.replace('.bngl', '.net') output = StringIO() try: bng_file = open(bng_filename, 'w') bng_file.write(gen.get_content()) bng_file.write(generate_network_code) bng_file.close() p = subprocess.Popen(['perl', bng_path, bng_filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (p_out, p_err) = p.communicate() if p.returncode: raise GenerateNetworkError(p_out.rstrip() + "\n" + p_err.rstrip()) net_file = open(net_filename, 'r') output.write(net_file.read()) net_file.close() if append_stdout: output.write("#\n# BioNetGen execution log follows\n# ==========") output.write(re.sub(r'(^|\n)', r'\n# ', p_out)) finally: if cleanup: for filename in [bng_filename, net_filename]: if os.access(filename, os.F_OK): os.unlink(filename) return output.getvalue()
def generate_network(model, cleanup=True, append_stdout=False): """ Return the output from BNG's generate_network function given a model. The output is a BNGL model definition with additional sections 'reactions' and 'groups', and the 'species' section expanded to contain all possible species. BNG refers to this as a 'net' file. Parameters ---------- model : Model Model to pass to generate_network. cleanup : bool, optional If True (default), delete the temporary files after the simulation is finished. If False, leave them in place (in `output_dir`). Useful for debugging. append_stdout : bool, optional If True, provide BNG.pl's standard output stream as comment lines appended to the net file contents. If False (default), do not append it. """ gen = BngGenerator(model) if not model.initial_conditions: raise NoInitialConditionsError() if not model.rules: raise NoRulesError() bng_filename = '%s_%d_%d_temp.bngl' % (model.name, os.getpid(), random.randint(0, 10000)) net_filename = bng_filename.replace('.bngl', '.net') output = StringIO() try: bng_file = open(bng_filename, 'w') bng_file.write(gen.get_content()) bng_file.write(_generate_network_code) bng_file.close() p = subprocess.Popen(['perl', _get_bng_path(), bng_filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (p_out, p_err) = p.communicate() if p.returncode: raise GenerateNetworkError(p_out.rstrip() + "\n" + p_err.rstrip()) net_file = open(net_filename, 'r') output.write(net_file.read()) net_file.close() if append_stdout: output.write("#\n# BioNetGen execution log follows\n# ==========") output.write(re.sub(r'(^|\n)', r'\n# ', p_out)) finally: if cleanup: for filename in [bng_filename, net_filename]: if os.access(filename, os.F_OK): os.unlink(filename) return output.getvalue()
def run_ssa(model, t_end=10, n_steps=100, output_dir='/tmp', cleanup=True): """Run a model through BNG's SSA simulator and return the simulation data as a numpy record array. """ run_ssa_code = """ begin actions generate_network({overwrite=>1}); simulate_ssa({t_end=>%f, n_steps=>%d});\n end actions """ % (t_end, n_steps) gen = BngGenerator(model) bng_filename = '%s_%d_%d_temp.bngl' % (model.name, os.getpid(), random.randint(0, 10000)) gdat_filename = bng_filename.replace('.bngl', '.gdat') cdat_filename = bng_filename.replace('.bngl', '.cdat') net_filename = bng_filename.replace('.bngl', '.net') output = StringIO() try: #import pdb; pdb.set_trace() working_dir = os.getcwd() os.chdir(output_dir) bng_file = open(bng_filename, 'w') bng_file.write(gen.get_content()) bng_file.write(run_ssa_code) bng_file.close() p = subprocess.Popen(['perl', bng_path, bng_filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (p_out, p_err) = p.communicate() if p.returncode: raise GenerateNetworkError(p_out.rstrip() + "\n" + p_err.rstrip()) output_arr = _parse_bng_outfile(gdat_filename) #ssa_file = open(ssa_filename, 'r') #output.write(ssa_file.read()) #net_file.close() #if append_stdout: # output.write("#\n# BioNetGen execution log follows\n# ==========") # output.write(re.sub(r'(^|\n)', r'\n# ', p_out)) finally: if cleanup: for filename in [ bng_filename, gdat_filename, cdat_filename, net_filename ]: if os.access(filename, os.F_OK): os.unlink(filename) os.chdir(working_dir) return output_arr
def generate_network(model, cleanup=True, append_stdout=False): """ Return the output from BNG's generate_network function given a model. The output is a BNGL model definition with additional sections 'reactions' and 'groups', and the 'species' section expanded to contain all possible species. BNG refers to this as a 'net' file. Parameters ---------- model : Model Model to pass to generate_network. cleanup : bool, optional If True (default), delete the temporary files after the simulation is finished. If False, leave them in place (in `output_dir`). Useful for debugging. append_stdout : bool, optional If True, provide BNG.pl's standard output stream as comment lines appended to the net file contents. If False (default), do not append it. """ gen = BngGenerator(model) if not model.initial_conditions: raise NoInitialConditionsError() if not model.rules: raise NoRulesError() bng_filename = '%s_%d_%d_temp.bngl' % (model.name, os.getpid(), random.randint(0, 10000)) net_filename = bng_filename.replace('.bngl', '.net') output = StringIO() try: bng_file = open(bng_filename, 'w') bng_file.write(gen.get_content()) bng_file.write(_generate_network_code) bng_file.close() p = subprocess.Popen(['perl', _get_bng_path(), bng_filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (p_out, p_err) = p.communicate() if p.returncode: raise GenerateNetworkError(p_out.rstrip()+"\n"+p_err.rstrip()) net_file = open(net_filename, 'r') output.write(net_file.read()) net_file.close() if append_stdout: output.write("#\n# BioNetGen execution log follows\n# ==========") output.write(re.sub(r'(^|\n)', r'\n# ', p_out)) finally: if cleanup: for filename in [bng_filename, net_filename]: if os.access(filename, os.F_OK): os.unlink(filename) return output.getvalue()
def run_ssa(model, t_end=10, n_steps=100, output_dir='/tmp', cleanup=True): """Run a model through BNG's SSA simulator and return the simulation data as a numpy record array. """ run_ssa_code = """ begin actions generate_network({overwrite=>1}); simulate_ssa({t_end=>%f, n_steps=>%d});\n end actions """ % (t_end, n_steps) gen = BngGenerator(model) bng_filename = '%s_%d_%d_temp.bngl' % (model.name, os.getpid(), random.randint(0, 10000)) gdat_filename = bng_filename.replace('.bngl', '.gdat') cdat_filename = bng_filename.replace('.bngl', '.cdat') net_filename = bng_filename.replace('.bngl', '.net') output = StringIO() try: #import pdb; pdb.set_trace() working_dir = os.getcwd() os.chdir(output_dir) bng_file = open(bng_filename, 'w') bng_file.write(gen.get_content()) bng_file.write(run_ssa_code) bng_file.close() p = subprocess.Popen(['perl', bng_path, bng_filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (p_out, p_err) = p.communicate() if p.returncode: raise GenerateNetworkError(p_out.rstrip("at line")+"\n"+p_err.rstrip()) output_arr = _parse_bng_outfile(gdat_filename) #ssa_file = open(ssa_filename, 'r') #output.write(ssa_file.read()) #net_file.close() #if append_stdout: # output.write("#\n# BioNetGen execution log follows\n# ==========") # output.write(re.sub(r'(^|\n)', r'\n# ', p_out)) finally: if cleanup: for filename in [bng_filename, gdat_filename, cdat_filename, net_filename]: if os.access(filename, os.F_OK): os.unlink(filename) os.chdir(working_dir) return output_arr
def export(self): """Generate the corresponding BNGL for the PySB model associated with the exporter. A wrapper around ``pysb.generator.bng.BngGenerator``. Returns ------- string The BNGL output for the model. """ bngl_str = '' if self.docstring: bngl_str += '# ' + self.docstring.replace('\n', '\n# ') + '\n' gen = BngGenerator(self.model) bngl_str += gen.get_content() return bngl_str
def __init__(self, model=None, verbose=False, cleanup=False, output_prefix=None, output_dir=None, model_additional_species=None, model_population_maps=None): self._logger = get_logger(__name__, model=model, log_level=verbose) self._base_file_stem = 'pysb' self.cleanup = cleanup self.output_prefix = 'tmpBNG' if output_prefix is None else \ output_prefix if model: self.generator = BngGenerator( model, additional_initials=model_additional_species, population_maps=model_population_maps) self.model = self.generator.model self._check_model() else: self.generator = None self.model = None self.base_directory = tempfile.mkdtemp(prefix=self.output_prefix, dir=output_dir) self._logger.debug('{} instantiated in directory {}'.format( self.__class__, self.base_directory))
def __init__(self, model, verbose=False, cleanup=False, output_prefix=None, output_dir=None): self.verbose = verbose self.cleanup = cleanup self.output_prefix = 'tmpBNG' if output_prefix is None else \ output_prefix self.generator = BngGenerator(model) self._check_model() self.base_directory = tempfile.mkdtemp(prefix=self.output_prefix, dir=output_dir)
def run_ssa(model, t_end=10, n_steps=100, output_dir='/tmp', output_file_basename=None, cleanup=True): """ Simulate a model with BNG's SSA simulator and return the trajectories. Parameters ---------- model : Model Model to simulate. t_end : number, optional Final time point of the simulation. n_steps : int, optional Number of steps in the simulation. output_dir : string, optional Location for temporary files generated by BNG. Defaults to '/tmp'. output_file_basename : string, optional The basename for the .bngl, .gdat, .cdat, and .net files that are generated by BNG. If None (the default), creates a basename from the model name, process ID, and a random integer in the range (0, 100000). cleanup : bool, optional If True (default), delete the temporary files after the simulation is finished. If False, leave them in place (in `output_dir`). Useful for debugging. """ run_ssa_code = """ begin actions generate_network({overwrite=>1}); simulate_ssa({t_end=>%f, n_steps=>%d});\n end actions """ % (t_end, n_steps) gen = BngGenerator(model) if output_file_basename is None: output_file_basename = '%s_%d_%d_temp' % (model.name, os.getpid(), random.randint(0, 100000)) if os.path.exists(output_file_basename + '.bngl'): print "WARNING! File %s already exists!" % (output_file_basename + '.bngl') output_file_basename += '_1' bng_filename = output_file_basename + '.bngl' gdat_filename = output_file_basename + '.gdat' cdat_filename = output_file_basename + '.cdat' net_filename = output_file_basename + '.net' output = StringIO() try: working_dir = os.getcwd() os.chdir(output_dir) bng_file = open(bng_filename, 'w') bng_file.write(gen.get_content()) bng_file.write(run_ssa_code) bng_file.close() p = subprocess.Popen(['perl', _get_bng_path(), bng_filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (p_out, p_err) = p.communicate() if p.returncode: raise GenerateNetworkError(p_out.rstrip("at line")+"\n"+p_err.rstrip()) print "Wrote " + gdat_filename # FIXME output_arr = _parse_bng_outfile(gdat_filename) #ssa_file = open(ssa_filename, 'r') #output.write(ssa_file.read()) #net_file.close() #if append_stdout: # output.write("#\n# BioNetGen execution log follows\n# ==========") # output.write(re.sub(r'(^|\n)', r'\n# ', p_out)) finally: if cleanup: for filename in [bng_filename, gdat_filename, cdat_filename, net_filename]: if os.access(filename, os.F_OK): os.unlink(filename) os.chdir(working_dir) return output_arr
def run(model): gen = BngGenerator(model) return gen.get_content()
def run_ssa(model, t_end=10, n_steps=100, output_dir='/tmp', output_file_basename=None, cleanup=True): """ Simulate a model with BNG's SSA simulator and return the trajectories. Parameters ---------- model : Model Model to simulate. t_end : number, optional Final time point of the simulation. n_steps : int, optional Number of steps in the simulation. output_dir : string, optional Location for temporary files generated by BNG. Defaults to '/tmp'. output_file_basename : string, optional The basename for the .bngl, .gdat, .cdat, and .net files that are generated by BNG. If None (the default), creates a basename from the model name, process ID, and a random integer in the range (0, 100000). cleanup : bool, optional If True (default), delete the temporary files after the simulation is finished. If False, leave them in place (in `output_dir`). Useful for debugging. """ run_ssa_code = """ begin actions generate_network({overwrite=>1}); simulate_ssa({t_end=>%f, n_steps=>%d});\n end actions """ % (t_end, n_steps) gen = BngGenerator(model) if output_file_basename is None: output_file_basename = '%s_%d_%d_temp' % (model.name, os.getpid(), random.randint(0, 100000)) if os.path.exists(output_file_basename + '.bngl'): print "WARNING! File %s already exists!" % (output_file_basename + '.bngl') output_file_basename += '_1' bng_filename = output_file_basename + '.bngl' gdat_filename = output_file_basename + '.gdat' cdat_filename = output_file_basename + '.cdat' net_filename = output_file_basename + '.net' output = StringIO() try: working_dir = os.getcwd() os.chdir(output_dir) bng_file = open(bng_filename, 'w') bng_file.write(gen.get_content()) bng_file.write(run_ssa_code) bng_file.close() p = subprocess.Popen(['perl', _get_bng_path(), bng_filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (p_out, p_err) = p.communicate() if p.returncode: raise GenerateNetworkError( p_out.rstrip("at line") + "\n" + p_err.rstrip()) print "Wrote " + gdat_filename # FIXME output_arr = _parse_bng_outfile(gdat_filename) #ssa_file = open(ssa_filename, 'r') #output.write(ssa_file.read()) #net_file.close() #if append_stdout: # output.write("#\n# BioNetGen execution log follows\n# ==========") # output.write(re.sub(r'(^|\n)', r'\n# ', p_out)) finally: if cleanup: for filename in [ bng_filename, gdat_filename, cdat_filename, net_filename ]: if os.access(filename, os.F_OK): os.unlink(filename) os.chdir(working_dir) return output_arr
Compartment('membrane', parent=extracellular, dimension=2) Monomer('egf', ['R']) Monomer('egfr', ['L', 'D', 'C']) Parameter('Kf_egfr_egf', 1.2) Parameter('Kr_egfr_egf', 1.1) Rule('egfr_egf', egfr(L=None) + egf(R=None) <> egfr(L=1) % egf(R=1), Kf_egfr_egf, Kr_egfr_egf) Observable('free_egf', egf(R=None)) Observable('free_egfr', egfr(L=None)) Observable('bound', egf(R=1) % egfr(L=1)) Parameter('egf_0', 6.0) Parameter('egfr_0', 10.0) Initial(egf(R=None) ** extracellular, egf_0) Initial(egfr(L=None, D=None, C=None) ** membrane, egfr_0) if __name__ == '__main__': from pysb.generator.bng import BngGenerator gen = BngGenerator(model) print gen.get_content() print "begin actions" print " generate_network({overwrite=>1});" print "end actions"
BAX(inh=1) % MCL1(b=1), kbaxmcl1f, kbaxmcl1r) # Initial conditions Parameter('BAX_0', 1e3) Initial(BAX(t1=None, t2=None, inh=None), BAX_0) Parameter('MCL1_0', 1e2) Initial(MCL1(b=None), MCL1_0) # We must fully specify all four BAX-BAX bonds, otherwise the pattern # is too loose, match a given species multiple times (beyond the # factor of four expected due to the rotational symmetry of the # tetramer), resulting in erroneously high values. Observable('BAX4', BAX(t1=1, t2=3) % BAX(t1=4, t2=1) % BAX(t1=2, t2=4) % BAX(t1=3, t2=2)) # Same all-bonds requirement here. However since the BAX tetramer is # considered inhibited when even one subunit has an inhibitor bound, # we only need to explicitly write inh=ANY on one of the monomer # patterns. Observable('BAX4_inh', BAX(inh=ANY, t1=1, t2=3) % BAX(t1=4, t2=1) % BAX(t1=2, t2=4) % BAX(t1=3, t2=2)) if __name__ == '__main__': from pysb.generator.bng import BngGenerator gen = BngGenerator(model) print gen.get_content() print "" print "begin actions" print " generate_network({overwrite=>1});" print " simulate_ode({t_end=>21600,n_steps=>360});" # 6 hours, 1-minute steps print "end actions"