コード例 #1
0
ファイル: sbmlio.py プロジェクト: mdziurzynski/sbmlutils
def write_sbml(doc,
               filepath,
               validate=True,
               program_name=None,
               program_version=None,
               show_errors=True):
    """
    Write SBMLDocument to file.

    :param doc: SBMLDocument to write
    :param filepath: output file to write
    :param validate: flag for validation (True: full validation, False: no validation)
    :param program_name: Program name for SBML file
    :param program_version: Program version for SBML file
    :return:
    """
    writer = libsbml.SBMLWriter()
    if program_name:
        writer.setProgramName(program_name)
    if program_version:
        writer.setProgramVersion(program_version)
    writer.writeSBMLToFile(doc, filepath)

    # validate the model with units (only for small models)
    # This validates the written file
    if validate:
        if validate is True:
            validation.check_sbml(filepath)
        elif validate is validation.VALIDATION_NO_UNITS:
            validation.check_sbml(filepath,
                                  units_consistency=False,
                                  log_errors=True)
コード例 #2
0
ファイル: sbmlio.py プロジェクト: matthiaskoenig/sbmlutils
def write_sbml(doc, filepath, validate=True, program_name=None, program_version=None, show_errors=True):
    """
    Write SBMLDocument to file.

    :param doc: SBMLDocument to write
    :param filepath: output file to write
    :param validate: flag for validation (True: full validation, False: no validation)
    :param program_name: Program name for SBML file
    :param program_version: Program version for SBML file
    :return:
    """
    writer = libsbml.SBMLWriter()
    if program_name:
        writer.setProgramName(program_name)
    if program_version:
        writer.setProgramVersion(program_version)
    writer.writeSBMLToFile(doc, filepath)

    # validate the model with units (only for small models)
    # This validates the written file
    if validate:
        if validate is True:
            validation.check_sbml(filepath)
        elif validate is validation.VALIDATION_NO_UNITS:
            validation.check_sbml(filepath, ucheck=False, show_errors=True)
コード例 #3
0
def merge_models(model_paths, out_dir=None, merged_id="merged", validate=True):
    """ Merge models in model path.
    All models must be in the same subfolder.
    Relative paths are set in the merged models.

    Output directory must exist.

    :param model_paths: absolute paths to models
    :return:
    """
    # necessary to convert models to SBML L3V1

    # FIXME: the path should not be changed by functions (this will create problems if run concurrently)
    cur_dir = os.getcwd()
    os.chdir(out_dir)

    base_dir = None
    for model_id, path in model_paths.items():
        if not os.path.exists(path):
            logging.error('Path for SBML file does not exist: {}'.format(path))

        # get base dir of all model files from first file
        if base_dir is None:
            base_dir = os.path.dirname(path)
        else:
            new_dir = os.path.dirname(path)
            if new_dir != base_dir:
                raise ValueError('All SBML files for merging must be in same '
                                 'directory: {} != {}'.format(
                                     new_dir, base_dir))

        # convert to L3V1
        path_L3 = os.path.join(out_dir, "{}_L3.xml".format(model_id))
        doc = libsbml.readSBMLFromFile(path)
        if doc.getLevel() < SBML_LEVEL:
            doc.setLevelAndVersion(SBML_LEVEL, SBML_VERSION)
        libsbml.writeSBMLToFile(doc, path_L3)
        model_paths[model_id] = path_L3

    if validate is True:
        for path in model_paths:
            validation.check_sbml(path, name=path)

    # create comp model
    merged_doc = create_merged_doc(model_paths, merged_id=merged_id)
    if validate is True:
        validation.check_sbml(path, name=path)

    # write merged doc
    f_out = os.path.join(out_dir, '{}.xml'.format(merged_id))
    libsbml.writeSBMLToFile(merged_doc, f_out)

    os.chdir(cur_dir)
    return merged_doc
コード例 #4
0
def merge_models(model_paths, out_dir=None, merged_id="merged", validate=True):
    """ Merge models in model path.
    All models must be in the same subfolder.
    Relative paths are set in the merged models.

    Output directory must exist.

    :param model_paths: absolute paths to models
    :return:
    """
    # necessary to convert models to SBML L3V1

    # FIXME: the path should not be changed by functions (this will create problems if run concurrently)
    cur_dir = os.getcwd()
    os.chdir(out_dir)

    base_dir = None
    for model_id, path in model_paths.items():
        if not os.path.exists(path):
            logging.error('Path for SBML file does not exist: {}'.format(path))

        # get base dir of all model files from first file
        if base_dir is None:
            base_dir = os.path.dirname(path)
        else:
            new_dir = os.path.dirname(path)
            if new_dir != base_dir:
                raise ValueError('All SBML files for merging must be in same '
                                 'directory: {} != {}'.format(new_dir, base_dir))

        # convert to L3V1
        path_L3 = os.path.join(out_dir, "{}_L3.xml".format(model_id))
        doc = libsbml.readSBMLFromFile(path)
        if doc.getLevel() < SBML_LEVEL:
            doc.setLevelAndVersion(SBML_LEVEL, SBML_VERSION)
        libsbml.writeSBMLToFile(doc, path_L3)
        model_paths[model_id] = path_L3

    if validate is True:
        for path in model_paths:
            validation.check_sbml(path, name=path)

    # create comp model
    merged_doc = create_merged_doc(model_paths, merged_id=merged_id)
    if validate is True:
        validation.check_sbml(path, name=path)

    # write merged doc
    f_out = os.path.join(out_dir, '{}.xml'.format(merged_id))
    libsbml.writeSBMLToFile(merged_doc, f_out)

    os.chdir(cur_dir)
    return merged_doc
コード例 #5
0
ファイル: test_xpp.py プロジェクト: matthiaskoenig/sbmlutils
    def xpp_check(self, ode_id, Nall=0, Nerr=0, Nwarn=0):
        tmp_dir = tempfile.mkdtemp(suffix="_xpp")
        sbml_file = os.path.join(tmp_dir, "{}.xml".format(ode_id))
        xpp_file = os.path.join(xpp_dir, "{}.ode".format(ode_id))

        xpp.xpp2sbml(xpp_file=xpp_file, sbml_file=sbml_file)
        Nall_res, Nerr_res, Nwarn_res = validation.check_sbml(sbml_file, ucheck=False)
        assert Nall_res == Nall
        assert Nerr_res == Nerr
        assert Nwarn_res == Nwarn
コード例 #6
0
    def _create_sbml(self):
        """ Create the SBMLDocument.

        :return:
        :rtype:
        """
        self._init_sbml_model()
        self.interpolators = Interpolation.create_interpolators(
            self.data, self.method)
        for interpolator in self.interpolators:
            Interpolation.add_interpolator_to_model(interpolator, self.model)

        # validation of SBML document
        try:
            temp_dir = tempfile.mkdtemp()
            tmp_f = os.path.join(temp_dir, 'validated.xml')
            libsbml.writeSBMLToFile(self.doc, tmp_f)
            validation.check_sbml(tmp_f, ucheck=False)
        finally:
            shutil.rmtree(temp_dir)
コード例 #7
0
ファイル: test_xpp.py プロジェクト: AspirinCode/sbmlutils
    def xpp_check(self, ode_id, Nall=0, Nerr=0, Nwarn=0):
        tmp_dir = tempfile.mkdtemp(suffix="_xpp")
        sbml_file = os.path.join(tmp_dir, "{}.xml".format(ode_id))
        xpp_file = os.path.join(xpp_dir, "{}.ode".format(ode_id))

        xpp.xpp2sbml(xpp_file=xpp_file, sbml_file=sbml_file)
        Nall_res, Nerr_res, Nwarn_res = validation.check_sbml(sbml_file,
                                                              ucheck=False)
        assert Nall_res == Nall
        assert Nerr_res == Nerr
        assert Nwarn_res == Nwarn
コード例 #8
0
def create_sbml_report(sbml_path, out_dir, template='report.html', promote=False, validate=True):
    """ Creates the SBML report in the out_dir

    :param validate:
    :param promote:
    :param template:
    :param sbml_path:
    :param doc:
    :param out_dir:
    :return:
    :rtype:
    """
    # check if sbml_file exists
    if not os.path.exists(sbml_path):
        warnings.warn('SBML file does not exist: {}'.format(sbml_path))

    # check sbml file
    if validate:
        check_sbml(sbml_path)

    # read sbml
    doc = libsbml.readSBML(sbml_path)
    if promote:
        promote_local_variables(doc)

    # write sbml to output folder
    basename = os.path.basename(sbml_path)
    tokens = basename.split('.')
    name = '.'.join(tokens[:-1])

    f_sbml = os.path.join(out_dir, basename)
    libsbml.writeSBMLToFile(doc, f_sbml)

    # write html (unicode)
    html = _create_html(doc, basename, html_template=template)
    f_html = codecs.open(os.path.join(out_dir, '{}.html'.format(name)),
                         encoding='utf-8', mode='w')
    f_html.write(html)
    f_html.close()
コード例 #9
0
    def validate_file(self, sbmlpath, ucheck=True, Nall=0):
        """ Validate given SBML file.

        Helper function called by the other tests.

        :param sbmlpath:
        :param ucheck:
        :return:
        """
        Nall, Nerr, Nwarn = check_sbml(sbmlpath, ucheck=ucheck)
        self.assertIsNotNone(Nall)
        # There is an SBOfix for model framework in the develop version,
        # with the wheel steel 3 warnings
        # FIXME: update to 0 with next libsbml wheel release
        self.assertTrue(Nall in [0, 3])
コード例 #10
0
    def validate_file(self, sbmlpath, ucheck=True, Nall=0):
        """ Validate given SBML file.

        Helper function called by the other tests.

        :param sbmlpath:
        :param ucheck:
        :return:
        """
        Nall, Nerr, Nwarn = check_sbml(sbmlpath, ucheck=ucheck)
        self.assertIsNotNone(Nall)
        # There is an SBOfix for model framework in the develop version,
        # with the wheel steel 3 warnings
        # FIXME: update to 0 with next libsbml wheel release
        self.assertTrue(Nall in [0, 3])
コード例 #11
0
ファイル: test_demo.py プロジェクト: matthiaskoenig/sbmlutils
def test_check_sbml():
    Nall, Nerr, Nwarn = validation.check_sbml(data.DEMO_SBML, ucheck=True)
    assert Nall == 0
コード例 #12
0
def merge_models(
    model_paths: Dict[str, Path],
    out_dir: Path = None,
    merged_id: str = "merged",
    validate: bool = True,
) -> libsbml.SBMLDocument:
    """Merge models in model path.

    All models must exist in the same subfolder.
    Relative paths are set in the merged models.

    Output directory must exist.

    :param model_paths: absolute paths to models
    :return:
    """
    # necessary to convert models to SBML L3V1
    cur_dir = os.getcwd()
    os.chdir(out_dir)

    base_dir = None
    for model_id, path in model_paths.items():
        if path.exists():
            logging.error(f"Path for SBML file does not exist: {path}")

        # get base dir of all model files from first file
        if base_dir is None:
            base_dir = path.parent
        else:
            new_dir = path.parent
            if not new_dir != base_dir:
                raise IOError(
                    f"All SBML files for merging must be in same "
                    f"directory: {new_dir} != {base_dir}"
                )

        # convert to L3V1
        path_L3 = out_dir / f"{model_id}_L3.xml"
        doc = read_sbml(path_L3)
        if doc.getLevel() < SBML_LEVEL:
            doc.setLevelAndVersion(SBML_LEVEL, SBML_VERSION)
        write_sbml(doc, path_L3)
        model_paths[model_id] = path_L3

    if validate is True:
        for path in model_paths:
            validation.check_sbml(path, name=path)

    # create comp model
    merged_doc = create_merged_doc(
        model_paths, merged_id=merged_id
    )  # type: libsbml.SBMLDocument
    if validate is True:
        validation.check_sbml(path, name=path)

    # write merged doc
    f_out = os.path.join(out_dir, "{}.xml".format(merged_id))
    libsbml.writeSBMLToFile(merged_doc, f_out)

    os.chdir(cur_dir)
    return merged_doc
コード例 #13
0
ファイル: xpp_models.py プロジェクト: AspirinCode/sbmlutils
    # test single model
    # ode_all = ["./87762/Neuron_KATP/NeuronKATP_Stoch.ode"]
    # debug, show_errors = True, True

    for k, xpp_file in enumerate(sorted(ode_all)):

        # convert xpp to sbml
        basename = os.path.basename(xpp_file)
        sbml_file = os.path.join(out_dir, "{}.xml".format(basename))
        try:
            print('[{}]'.format(k))
            xpp.xpp2sbml(xpp_file=xpp_file, sbml_file=sbml_file, force_lower=force_lower, validate=False, debug=debug)
            success = True
            sbmlreport.create_sbml_report(sbml_file, out_dir=out_dir, validate=False)
            Nall, Nerr, Nwarn = validation.check_sbml(sbml_file, name=None, ucheck=False, show_errors=show_errors)
            valid = (Nerr == 0)
            simulates = False
            if valid:
                try:
                    simulate(sbml_file)
                    simulates = True
                except:
                    # simulation exception
                    simulates = False
                    print()
                    traceback.print_exc(file=sys.stdout)
                    print()

        except:
            print()
コード例 #14
0
"""
Script to check the model files.
"""

import os
from os import walk
from sbmlutils.validation import check_sbml
from sbmlutils.report import sbmlreport

# directory to write files to
directory = os.path.dirname(os.path.abspath(__file__))

xml_files = []
for (dirpath, dirnames, filenames) in walk(directory):
    xml_files.extend([name for name in filenames if name.endswith('.xml')])
    break

print(xml_files)


# perform a model validation
for sbml_file in xml_files:
    check_sbml(sbml_file)

# create the model reports

for sbml_file in xml_files:
    sbmlreport.create_sbml_report(sbml_file, directory)
コード例 #15
0
ファイル: sbmlreport.py プロジェクト: mdziurzynski/sbmlutils
def create_report(sbml_path,
                  report_dir,
                  promote=False,
                  template='report.html',
                  validate=True,
                  log_errors=True,
                  units_consistency=True,
                  modeling_practice=True):
    """ Create a HTML report for a given SBML file.

    The SBML file can be validated during report generation.
    Local parameters can be promoted during report generation.

    :param sbml_path: path to SBML file
    :param report_dir: target directory where the report is written
    :param promote: boolean flag to promote local parameters
    :param template: which template file to use for rendering
    :param validate: boolean flag if SBML file be validated (warnings and errors are logged)
    :param log_errors: boolean flag of errors should be logged
    :param units_consistency: boolean flag units consistency
    :param modeling_practice: boolean flag modeling practise

    :return:
    """
    # check paths
    if not os.path.exists(sbml_path):
        raise IOError("'sbml_path' does not exist: '{}'".format(sbml_path))
    if not os.path.exists(report_dir):
        raise IOError("'report_dir' does not exist: '{}'".format(report_dir))
    if not os.path.isdir(report_dir):
        raise IOError(
            "'report_dir' is not a directory: '{}'".format(report_dir))

    # validate SBML
    if validate:
        check_sbml(sbml_path,
                   log_errors=log_errors,
                   units_consistency=units_consistency,
                   modeling_practice=modeling_practice)

    # read SBML
    doc = libsbml.readSBML(sbml_path)

    # promote parameters
    if promote:
        utils.promote_local_variables(doc)

    # write SBML to report directory
    basename = os.path.basename(sbml_path)
    tokens = basename.split('.')
    name = '.'.join(tokens[:-1])
    f_sbml = os.path.join(report_dir, basename)
    libsbml.writeSBMLToFile(doc, f_sbml)

    # write html (unicode)
    html = _create_html(doc, basename, html_template=template)
    path_html = os.path.join(report_dir, '{}.html'.format(name))
    f_html = codecs.open(path_html, encoding='utf-8', mode='w')
    f_html.write(html)
    f_html.close()
    print("SBML report created: {}".format(path_html))
コード例 #16
0
def test_validate_sbml():
    Nall, Nerr, Nwarn = validation.check_sbml(data.GALACTOSE_SINGLECELL_SBML,
                                              ucheck=True)
    assert Nerr == 0
コード例 #17
0
def test_validate_sbml():
    Nall, Nerr, Nwarn = validation.check_sbml(data.GALACTOSE_SINGLECELL_SBML, ucheck=True)
    assert Nerr == 0
コード例 #18
0
def test_check_sbml():
    Nall, Nerr, Nwarn = validation.check_sbml(data.DEMO_SBML, ucheck=True)
    assert Nall == 0
コード例 #19
0
ファイル: test_demo.py プロジェクト: mdziurzynski/sbmlutils
def test_check_sbml():
    Nall, Nerr, Nwarn = validation.check_sbml(data.DEMO_SBML,
                                              units_consistency=True)
    assert Nall == 0
コード例 #20
0
"""
Script to check the model files.
"""

import os
from os import walk
from sbmlutils.validation import check_sbml
from sbmlutils.report import sbmlreport

# directory to write files to
directory = os.path.dirname(os.path.abspath(__file__))

xml_files = []
for (dirpath, dirnames, filenames) in walk(directory):
    xml_files.extend([name for name in filenames if name.endswith('.xml')])
    break

print(xml_files)

# perform a model validation
for sbml_file in xml_files:
    check_sbml(sbml_file)

# create the model reports

for sbml_file in xml_files:
    sbmlreport.create_report(sbml_file, directory)