Example #1
0
def bng_simulate(model, times, method='ode', output_dir='/tmp', cleanup=True):
    """
    Simulate a model with BNG's simulator and return the trajectories.
    Adapted from pysb.bng.run_ssa.

    Parameters
    ----------
    model : pysb.Model or string
        Model to simulate. Can be either a pysb.Model or a string representing
        BNGL model.
    times: list of floats
        Sample times.
    method: string
        'ode' or 'ssa'
    output_dir : string, optional
        Location for temporary files generated by BNG. Defaults to '/tmp'.
    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.

    """

    times = list(times)
    run_ssa_code = """
    begin actions
    generate_network({overwrite=>1});
    simulate_%s({sample_times=>%s});\n
    end actions
    """ % (method, times)

    if not isinstance(model, str):
        model = BngGenerator(model).get_content()
    bng_filename = '%d_%d_temp.bngl' % (
        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')

    try:
        working_dir = os.getcwd()
        os.chdir(output_dir)
        bng_file = open(bng_filename, 'w')
        bng_file.write(model)
        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())

        output_arr = _parse_bng_outfile(gdat_filename)
    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
Example #2
0
def sbml_translator(input_file,
                    output_file=None,
                    convention_file=None,
                    naming_conventions=None,
                    user_structures=None,
                    molecule_id=False,
                    atomize=False,
                    pathway_commons=False,
                    verbose=False):
    """
    Runs the BioNetGen sbmlTranslator binary.

    For more descriptions of the arguments, see the `sbmlTranslator
    documentation <http://bionetgen.org/index.php/SBML2BNGL>`_.

    Parameters
    ----------
    input_file : string
        SBML input filename
    output_file : string, optional
        BNGL output filename
    convention_file : string, optional
        Conventions filename
    naming_conventions : string, optional
        Naming conventions filename
    user_structures : string, optional
        User structures filename
    molecule_id : bool, optional
        Use SBML molecule IDs (True) or names (False).
        IDs are less descriptive but more BNGL friendly. Use only if the
        generated BNGL has syntactic errors
    atomize : bool, optional
        Atomize the model, i.e. attempt to infer molecular structure and
        build rules from the model (True) or just perform a flat import (False)
    pathway_commons : bool, optional
        Use pathway commons to infer molecule binding. This
        setting requires an internet connection and will query the pathway
        commons web service.
    verbose : bool, optional
        Print the SBML conversion output to the console if True

    Returns
    -------
    string
        BNGL output filename
    """
    sbmltrans_bin = os.path.join(os.path.dirname(_get_bng_path()),
                                 'bin/sbmlTranslator')
    sbmltrans_args = [sbmltrans_bin, '-i', input_file]
    if output_file is None:
        output_file = os.path.splitext(input_file)[0] + '.bngl'
    sbmltrans_args.extend(['-o', output_file])

    if convention_file:
        sbmltrans_args.extend(['-c', convention_file])

    if naming_conventions:
        sbmltrans_args.extend(['-n', naming_conventions])

    if user_structures:
        sbmltrans_args.extend(['-u', user_structures])

    if molecule_id:
        sbmltrans_args.append('-id')

    if atomize:
        sbmltrans_args.append('-a')

    if pathway_commons:
        sbmltrans_args.append('-p')

    if verbose:
        print("sbmlTranslator command:")
        print(" ".join(sbmltrans_args))

    p = subprocess.Popen(sbmltrans_args,
                         cwd=os.getcwd(),
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)

    if verbose:
        for line in iter(p.stdout.readline, b''):
            print(line, end="")
    (p_out, p_err) = p.communicate()
    if p.returncode:
        raise SbmlTranslationError(p_out.decode('utf-8') + "\n" +
                                   p_err.decode('utf-8'))

    return output_file