def example(model_id: str) -> None: """XPP example conversion.""" # convert xpp to sbml xpp_dir = Path(__file__).parent / "xpp_example" out_dir = xpp_dir / "results" xpp_file = xpp_dir / f"{model_id}.ode" sbml_file = out_dir / f"{model_id}.xml" xpp.xpp2sbml(xpp_file=xpp_file, sbml_file=sbml_file) sbmlreport.create_report(sbml_file, output_dir=out_dir, validate=False) # test simulation r = roadrunner.RoadRunner(str(sbml_file)) s = r.simulate(start=0, end=1000, steps=100) fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(14, 7)) axes = (ax1, ax2) for ax in axes: for sid in r.timeCourseSelections[1:]: ax.plot(s["time"], s[sid], label=sid) ax2.set_yscale("log") for ax in axes: ax.set_ylabel("Value [?]") ax.set_xlabel("Time [?]") ax.legend() fig.savefig(out_dir / f"{model_id}.png", bbox_inches="tight")
def example(model_id): # convert xpp to sbml xpp_dir = "./xpp_example" out_dir = "./xpp_example/results" xpp_file = os.path.join(xpp_dir, "{}.ode".format(model_id)) sbml_file = os.path.join(out_dir, "{}.xml".format(model_id)) xpp.xpp2sbml(xpp_file=xpp_file, sbml_file=sbml_file) sbmlreport.create_report(sbml_file, target_dir=out_dir, validate=False) # test simulation r = roadrunner.RoadRunner(sbml_file) s = r.simulate(start=0, end=1000, steps=100) fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(14, 7)) axes = (ax1, ax2) for ax in axes: for sid in r.timeCourseSelections[1:]: ax.plot(s["time"], s[sid], label=sid) ax2.set_yscale("log") for ax in axes: ax.set_ylabel("Value [?]") ax.set_xlabel("Time [?]") ax.legend() fig.savefig(os.path.join(out_dir, "{}.png".format(model_id)), bbox_inches="tight")
def check_report_math_type(sbml_path: Path, math_type: str, tmp_path: Path) -> None: """Checks SBML report with given math type.""" html = sbmlreport.create_report(sbml_path=sbml_path, output_dir=tmp_path, math_type=math_type) # check the returned HTML in the variable for correctness of type assert html assert isinstance(html, str)
def test_vdp_report(self): tmpdir = tempfile.mkdtemp(suffix="_sbml_report") sbmlreport.create_report(data.VDP_SBML, tmpdir)
def test_glucose_report(self): tmpdir = tempfile.mkdtemp(suffix="_sbml_report") sbmlreport.create_report(data.GLUCOSE_SBML, tmpdir)
def test_galactose_report(self): tmpdir = tempfile.mkdtemp(suffix="_sbml_report") sbmlreport.create_report(data.GALACTOSE_SINGLECELL_SBML, tmpdir)
def test_demo_report(self): tmpdir = tempfile.mkdtemp(suffix="_sbml_report") sbmlreport.create_report(data.DEMO_SBML, tmpdir)
import os.path from sbmlutils.report import sbmlreport if __name__ == "__main__": # create the sbml report f_path = os.path.join(os.path.curdir, 'yeast_glycolysis.xml') print(f_path) sbmlreport.create_report(sbml_path=f_path, target_dir=os.path.curdir)
def create_model(modules, target_dir, filename=None, mid=None, suffix=None, annotations=None, create_report=True, validate=True): """ Create SBML model from module information. This is the entry point for creating models. The model information is provided as a list of importable python modules. If no filename is provided the filename is created from the id and suffix. Additional model annotations can be provided. :param modules: iteratable of strings of python modules :param target_dir: directory in which to create SBML file :param filename: filename to write to, if not provided mid and suffix are used :param mid: model id to use for filename :param suffix: suffix for SBML filename :param annotations: list of annotations for SBML :param create_report: boolean switch to create SBML report :param validate: validates the SBML file :return: """ # preprocess logging.info(bcolors.OKBLUE + '\n\n' + '-' * 120 + '\n' + str(modules) + '\n' + '-' * 120 + bcolors.ENDC) model_dict = Preprocess.dict_from_modules(modules) # create SBML model core_model = CoreModel.from_dict(model_dict=model_dict) logging.debug(core_model.get_info()) core_model.create_sbml() # write file if not os.path.exists(target_dir): logging.warning( "Target directory does not exist and is created: {}".format( target_dir)) os.makedirs(target_dir) if not filename: # create filename if mid is None: mid = core_model.model.getId() if suffix is not None: filename = '{}{}.xml'.format(mid, suffix) else: filename = '{}.xml'.format(mid) sbml_path = os.path.join(target_dir, filename) core_model.write_sbml(sbml_path, validate=validate) # annotate if annotations is not None: # overwrite the normal file annotator.annotate_sbml_file(sbml_path, annotations, sbml_path) # create report if create_report: logging.info("Create SBML report:'{}'".format(sbml_path)) # file is already validated, no validation on report needed sbmlreport.create_report(sbml_path=sbml_path, report_dir=target_dir, validate=False) return [model_dict, core_model, sbml_path]
""" 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)
def test_report_gz(source, tmp_path): sbmlreport.create_report(sbml_path=source, output_dir=tmp_path)
debug, show_errors = False, False # 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_report(sbml_file, target_dir=out_dir, validate=False) Nall, Nerr, Nwarn = validation.check_sbml(sbml_file, name=None, ucheck=False, log_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:
# In[1]: from sbmlutils.report import sbmlreport # ### Repressilator # The first report is for the repressilator downloaded from biomodels (https://www.ebi.ac.uk/biomodels/BIOMD0000000012). # To create a report on provides the path to the SBML file and the directory where the report should be written. As part of the model report creation the model is validated by default. In this example we deactivate the `units_consistency` checks. # # The created SBML report can be accessed from [./reports/BIOMD0000000012.html](./reports/BIOMD0000000012.html). # In[2]: # create SBML report without performing units checks sbmlreport.create_report("./models/BIOMD0000000012.xml", report_dir="./reports", units_consistency=False) # ### Platelet metabolism # In the second example we create a report for a model for Human platelet metabolism from the BiGG model database: # http://bigg.ucsd.edu/models/iAT_PLT_636 # # The created SBML report can be accessed from [./reports/iAT_PLT_636.xml.html](./reports/iAT_PLT_636.xml.html). # In[3]: # create SBML report without performing units checks sbmlreport.create_report("./models/iAT_PLT_636.xml.gz", report_dir="./reports", units_consistency=False, modeling_practice=False)
def test_report_gz(sbml_path: Path, tmp_path: Path) -> None: """Test report generation for compressed models.""" sbmlreport.create_report(sbml_path=sbml_path, output_dir=tmp_path)
from models.liver.model_liver import create_model as create_liver_model from models.kidney.model_kidney import create_model as create_kidney_model from models.body.model_body import create_model as create_body_model if __name__ == "__main__": results_path = "./models" # create tissue models create_kidney_model(results_path) create_liver_model(results_path) # create whole-body model [_, _, sbml_path] = create_body_model(results_path) print(sbml_path) assert os.path.exists(sbml_path) sbml_path_flat = "./models/codeine_body_flat.xml" import libsbml doc = libsbml.readSBMLFromFile( os.path.abspath(sbml_path)) # type: libsbml.SBMLDocument model = doc.getModel() # type: libsbml.Model ## FIXME: not working with relative paths flattenSBMLFile(os.path.abspath(sbml_path), output_path=os.path.abspath(sbml_path_flat)) # create model report sbmlreport.create_report(sbml_path_flat, "./models/")
def create_model( modules: Union[Iterable[str], Dict], output_dir: Path = None, tmp: bool = False, filename: str = None, mid: str = None, suffix: str = None, annotations: Path = None, create_report: bool = True, validate: bool = True, log_errors: bool = True, units_consistency: bool = True, modeling_practice: bool = True, internal_consistency: bool = True, sbml_level: int = SBML_LEVEL, sbml_version: int = SBML_VERSION, ) -> FactoryResult: """Create SBML model from module information. This is the entry point for creating models. The model information is provided as a list of importable python modules. If no filename is provided the filename is created from the id and suffix. Additional model annotations can be provided. :param modules: iterable of strings of python modules or CoreModel instance :param output_dir: directory in which to create SBML file :param tmp: boolean flag to create files in a temporary directory (for testing) :param filename: filename to write to with suffix, if not provided mid and suffix are used :param mid: model id to use for filename :param suffix: suffix for SBML filename :param annotations: Path to annotations file :param create_report: boolean switch to create SBML report :param validate: validates the SBML file :param log_errors: boolean flag to log errors :param units_consistency: boolean flag to check units consistency :param modeling_practice: boolean flag to check modeling practise :param internal_consistency: boolean flag to check internal consistency :param sbml_level: set SBML level for model generation :param sbml_version: set SBML version for model generation :return: FactoryResult """ if output_dir is None and tmp is False: raise TypeError( "create_model() missing 1 required argument: 'output_dir'") # preprocess logger.info(bcolors.OKBLUE + "\n\n" + "-" * 120 + "\n" + str(modules) + "\n" + "-" * 120 + bcolors.ENDC) if isinstance(modules, dict): model_dict = modules else: model_dict = Preprocess.dict_from_modules( modules, keys=CoreModel._keys) # type: ignore core_model = CoreModel.from_dict(model_dict=model_dict) logger.debug(core_model.get_info()) core_model.create_sbml(sbml_level=sbml_level, sbml_version=sbml_version) if not filename: # create filename if mid is None: mid = core_model.model.getId() if suffix is None: suffix = "" filename = f"{mid}{suffix}.xml" if tmp: output_dir = tempfile.mkdtemp() # type: ignore sbml_path = os.path.join(output_dir, filename) # type: ignore else: if isinstance(output_dir, str): output_dir = Path(output_dir) logger.warning(f"'output_dir' should be a Path: {output_dir}") if not output_dir.exists(): # type: ignore logger.warning( f"'output_dir' does not exist and is created: {output_dir}") output_dir.mkdir(parents=True) # type: ignore sbml_path = output_dir / filename # type: ignore # write sbml if core_model.doc is None: core_model.create_sbml() try: write_sbml( doc=core_model.doc, filepath=sbml_path, # type: ignore validate=validate, log_errors=log_errors, units_consistency=units_consistency, modeling_practice=modeling_practice, internal_consistency=internal_consistency, ) # annotate if annotations is not None: # overwrite the normal file annotator.annotate_sbml( source=sbml_path, annotations_path=annotations, filepath=sbml_path # type: ignore ) # create report if create_report: # file is already validated, no validation on report needed sbmlreport.create_report( sbml_path=sbml_path, output_dir=output_dir, validate=False # type: ignore ) finally: if tmp: shutil.rmtree(str(output_dir)) return FactoryResult( model_dict=model_dict, core_model=core_model, sbml_path=sbml_path, # type: ignore )
"""Writing report with distrib information.""" from pathlib import Path from sbmlutils.report import sbmlreport if __name__ == "__main__": for filename in [ "distrib_normal.xml", "distrib_all.xml", "uncertainty_distribution.xml", "uncertainty_uncertspan.xml", "uncertainty_uncertvalue.xml", ]: sbml_path = Path(__file__).parent / filename print(sbml_path) sbmlreport.create_report(sbml_path=sbml_path, output_dir=Path(__file__).parent / "results")
""" Writing report with distrib information. """ from sbmlutils.report import sbmlreport if __name__ == "__main__": for path in ["./distrib_normal.xml", "./distrib_all.xml", "./uncertainty_distribution.xml", "./uncertainty_uncertspan.xml", "./uncertainty_uncertvalue.xml"]: print(path) sbmlreport.create_report(path, target_dir="./results/")
def create_model( modules: List[str], output_dir: Path, filename: str = None, mid: str = None, suffix: str = None, annotations=None, create_report: bool = True, validate: bool = True, log_errors: bool = True, units_consistency: bool = True, modeling_practice: bool = True, internal_consistency: bool = True, ): """Create SBML model from module information. This is the entry point for creating models. The model information is provided as a list of importable python modules. If no filename is provided the filename is created from the id and suffix. Additional model annotations can be provided. :param modules: iteratable of strings of python modules :param output_dir: directory in which to create SBML file :param filename: filename to write to with suffix, if not provided mid and suffix are used :param mid: model id to use for filename :param suffix: suffix for SBML filename :param annotations: list of annotations for SBML :param create_report: boolean switch to create SBML report :param validate: validates the SBML file :return: """ # preprocess logger.info( bcolors.OKBLUE + "\n\n" + "-" * 120 + "\n" + str(modules) + "\n" + "-" * 120 + bcolors.ENDC ) model_dict = Preprocess.dict_from_modules(modules) # create SBML model core_model = CoreModel.from_dict(model_dict=model_dict) logger.debug(core_model.get_info()) core_model.create_sbml() # write file if isinstance(output_dir, str): output_dir = Path(output_dir) logger.warning(f"'output_dir' should be a Path: {output_dir}") if not output_dir.exists(): logger.warning(f"'output_dir' does not exist and is created: {output_dir}") output_dir.mkdir(parents=True) if not filename: # create filename if mid is None: mid = core_model.model.getId() if suffix is None: suffix = "" filename = f"{mid}{suffix}.xml" # write sbml sbml_path = output_dir / filename if core_model.doc is None: core_model.create_sbml() write_sbml( doc=core_model.doc, filepath=sbml_path, validate=validate, log_errors=log_errors, units_consistency=units_consistency, modeling_practice=modeling_practice, internal_consistency=internal_consistency, ) # annotate if annotations is not None: # overwrite the normal file annotator.annotate_sbml( source=sbml_path, annotations_path=annotations, filepath=sbml_path ) # create report if create_report: # file is already validated, no validation on report needed sbmlreport.create_report( sbml_path=sbml_path, output_dir=output_dir, validate=False ) return [model_dict, core_model, sbml_path]