示例#1
0
 def __init__(self, model_file, generate_network=False):
     # check cvode library paths
     if (conf.get("cvode_include") is None) or (conf.get("cvode_lib") is
                                                None):
         print(
             "CVODE include and library paths are not set, compilation won't work"
         )
     # let's load the model first
     if isinstance(model_file, str):
         # load model file
         self.model = bionetgen.bngmodel(model_file,
                                         generate_network=generate_network)
     elif isinstance(model_file, bionetgen.bngmodel):
         # loaded model
         self.model = model_file
         cd = os.getcwd()
         with tempfile.TemporaryDirectory() as tmpdirname:
             os.chdir(tmpdirname)
             self.model.actions.clear_actions()
             self.model.write_model(f"{self.model.model_name}_cpy.bngl")
             self.model = bionetgen.bngmodel(
                 f"{self.model.model_name}_cpy.bngl",
                 generate_network=generate_network,
             )
         os.chdir(cd)
     else:
         print(f"model format not recognized: {model_file}")
     # set compiler
     self.compiler = ccompiler.new_compiler()
     self.compiler.add_include_dir(conf.get("cvode_include"))
     self.compiler.add_library_dir(conf.get("cvode_lib"))
     # compile shared library
     self.compile_shared_lib()
     # setup simulator
     self.simulator = self.lib_file
示例#2
0
def test_action_loading():
    # tests a BNGL file containing all BNG actions
    all_action_model = os.path.join(
        *[tfold, "models", "actions", "all_actions.bngl"])
    m1 = bng.bngmodel(all_action_model)
    assert len(m1.actions) + len(m1.actions.before_model) == 31

    no_action_model = os.path.join(
        *[tfold, "models", "actions", "no_actions.bngl"])
    m2 = bng.bngmodel(no_action_model)
    assert len(m2.actions) == 0
示例#3
0
 def _get_pcoords(self):
     # use bng api to get the model object
     model = bionetgen.bngmodel(self.inp_file)
     obs_arr = []
     # get observable strings
     for obs in model.observables:
         obs_arr.append(str(obs))
     return obs_arr
示例#4
0
def generate_notebook(app):
    """
    Uses BNGNotebook class to write a Jupyter notebook from a
    given set of command line arguments
    """
    args = app.pargs
    if args.input is not None:
        # we want to use the template to write a custom notebok
        # TODO: Transition to BNGErrors and logging
        assert args.input.endswith(
            ".bngl"), f"File {args.input} doesn't have bngl extension!"
        try:
            app.log.debug("Loading model", f"{__file__} : notebook()")
            import bionetgen

            m = bionetgen.bngmodel(args.input)
            str(m)
        except:
            app.log.error("Failed to load model", f"{__file__} : notebook()")
            raise RuntimeError(f"Couldn't import given model: {args.input}!")
        notebook = BNGNotebook(
            app.config["bionetgen"]["notebook"]["template"],
            INPUT_ARG=args.input,
        )
    else:
        # just use the basic notebook
        notebook = BNGNotebook(app.config["bionetgen"]["notebook"]["path"])
    # find our file name
    if len(args.output) == 0:
        fname = app.config["bionetgen"]["notebook"]["name"]
    else:
        fname = args.output
    # write the notebook out
    if os.path.isdir(fname):
        if args.input is not None:
            basename = os.path.basename(args.input)
            mname = basename.replace(".bngl", "")
            fname = mname + ".ipynb"
        else:
            mname = app.config["bionetgen"]["notebook"]["name"]
            fname = os.path.join(args.output, mname)

    app.log.debug(f"Writing notebook to file: {fname}",
                  f"{__file__} : notebook()")
    notebook.write(fname)
    # open the notebook with nbopen
    # TODO: deal with stdout/err
    app.log.debug(
        f"Attempting to open notebook {fname} with nbopen",
        f"{__file__} : notebook()",
    )
    stdout = getattr(subprocess, app.config["bionetgen"]["stdout"])
    stderr = getattr(subprocess, app.config["bionetgen"]["stderr"])
    if args.open:
        command = ["nbopen", fname]
        rc, _ = run_command(command)
示例#5
0
def test_setup_simulator():
    fpath = os.path.join(tfold, "test.bngl")
    fpath = os.path.abspath(fpath)
    try:
        m = bng.bngmodel(fpath)
        librr_simulator = m.setup_simulator()
        res = librr_simulator.simulate(0, 1, 10)
    except:
        res = None
    assert res is not None
def read_model(bngl_filename, filename):
    model = None
    errors = []
    with StandardOutputErrorCapturer(level=StandardOutputErrorCapturerLevel.c,
                                     relay=False) as captured:
        try:
            model = bionetgen.bngmodel(bngl_filename)
        except Exception as exception:
            errors.append([
                '`{}` is not a valid BNGL or BGNL XML file.'.format(filename
                                                                    or ''),
                [[str(exception)]]
            ])
    return model, errors, captured.get_text()
示例#7
0
def test_bionetgen_all_model_loading():
    # tests library model loading using many models
    mpattern = os.path.join(tfold, "models") + os.sep + "*.bngl"
    models = glob.glob(mpattern)
    succ = []
    fail = []
    success = 0
    fails = 0
    for model in models:
        try:
            m = bng.bngmodel(model)
            success += 1
            mstr = str(m)
            succ.append(model)
        except:
            print("can't load model {}".format(model))
            fails += 1
            fail.append(model)
    print("succ: {}".format(success))
    print(sorted(succ))
    print("fail: {}".format(fails))
    print(sorted(fail))
    assert fails == 0
示例#8
0
 def _executable_BNGL_on_file(self):
     # IMPORTANT!
     # This assumes that the bngl file doesn't have any directives at the end!
     # we have a bngl file
     os.chdir("bngl_conf")
     # Make specific BNGL files for a) generating network and then
     # b) getting a starting  gdat file
     model = bionetgen.bngmodel(self.bngl_file)
     model.add_action("generate_network", action_args={"overwrite": 1})
     model.add_action(
         "simulate", action_args={"method": "'ssa'", "t_end": 2, "n_steps": 2}
     )
     with open("init.bngl", "w") as f:
         f.write(str(model))
     r = bionetgen.run("init.bngl", "for_init")
     shutil.copyfile(os.path.join("for_init", "init.net"), "init.net")
     header_str = ""
     for i in r[0].dtype.names:
         header_str += " " + i
     np.savetxt("init.gdat", r[0], header=header_str)
     shutil.rmtree("for_init")
     os.chdir(os.path.join(self.main_dir, self.sim_dir))
     return model
示例#9
0
import bionetgen as bng
import glob

models = glob.glob("*.bngl")
total = len(models)
succ = []
fail = []
success = 0
fails = 0
for model in models:
    try:
        m = bng.bngmodel(model)
        success += 1
        succ.append(model)
        # mname = model.replace(".bngl","")
        # with open("{}_loaded.bngl".format(mname), 'w') as f:
        #     f.write(str(m))
    except:
        print("can't do model {}".format(model))
        fails += 1
        fail.append(model)

print("succ: {}".format(success))
print(sorted(succ))
print("fail: {}".format(fails))
print(sorted(fail))
示例#10
0
def test_bionetgen_model():
    fpath = os.path.join(tfold, "test.bngl")
    fpath = os.path.abspath(fpath)
    m = bng.bngmodel(fpath)