def print_gene_product_association(file_name):
    doc = libsbml.readSBMLFromFile(file_name)
    assert (isinstance(doc, libsbml.SBMLDocument))

    if doc.getNumErrors(libsbml.LIBSBML_SEV_ERROR) > 0:
        print("There were errors while reading, better to fix those first")
        doc.printErrors()
        sys.exit(1)

    model = doc.getModel()
    if model is None:
        print("document has no model, bailing")

    num_reactions = model.getNumReactions()
    print("      Model: %s" % model.getName())
    print("# reactions: %d" % num_reactions)

    for reaction in model.getListOfReactions():
        print(" Reaction: %s" % reaction.getId())
        plugin = reaction.getPlugin('fbc')
        if plugin is None:
            # not relevant for us
            continue

        if not plugin.isSetGeneProductAssociation():
            continue

        gpa = plugin.getGeneProductAssociation()

        association = gpa.getAssociation()
        print ("    Association: %s" % association.toInfix())

    print("done")
예제 #2
0
def list_ports(model_path):
    """

    :param model_path: path to sbml model
    :return:
    """
    """ List the ports in the given model.

    :return:
    """
    if not os.path.exists(model_path):
        raise IOError("SBML path does not exist.")

    doc = libsbml.readSBMLFromFile(model_path)  # type: libsbml.SBMLDocument
    model = doc.getModel()  # type: libsbml.Model
    model_comp = model.getPlugin("comp")  # type: libsbml.CompModelPlugin
    print(model_comp)
    for port in model_comp.getListOfPorts():  # type: libsbml.Port
        print("\tPort: ",
              port.getId(),
              port.getMetaId(),
              port.getIdRef(),
              port.getMetaIdRef(),
              port.getUnitRef(),
              port.getPortRef())
예제 #3
0
def renameSId (filename, oldSId, newSId, output_file): 
    if oldSId == newSId:
        print("The Ids are identical, renaming stopped.")
        return

    if not libsbml.SyntaxChecker.isValidInternalSId(newSId):
        print("The new SId '{0}' does not represent a valid SId.".format(newSId))
        return

    document = libsbml.readSBMLFromFile(filename)
    
    errors = document.getNumErrors(libsbml.LIBSBML_SEV_ERROR)
    
    if errors > 0:
        document.printErrors()
        return
    
    # find elements for old id
    element = document.getElementBySId(oldSId)
    if element == None:
        print("Found no element with SId '{0}'".format(oldSId))
        return
    
    # found element -> renaming
    element.setId(newSId)

    # update all references to this element
    allElements = document.getListOfAllElements()
    for i in range(allElements.getSize()):
        allElements.get(i).renameSIdRefs(oldSId, newSId)
    
    
    # write to file
    libsbml.writeSBMLToFile(document, output_file)
def simulate_toy_model(tend=50.0, step_size=0.1):
    # Run simulation of the hybrid model
    from simsettings import top_level_file, flattened_file, out_dir
    import os

    os.chdir(out_dir)
    df = simulate(mixed_sbml=top_level_file, tend=tend, step_size=step_size, debug=True)

    # create plots (use ids from flattened model for plotting)
    import libsbml
    flat_doc = libsbml.readSBMLFromFile(flattened_file)
    flat_model = flat_doc.getModel()
    reaction_ids = [r.getId() for r in flat_model.getListOfReactions()]
    species_ids = ["[{}]".format(s.getId()) for s in flat_model.getListOfSpecies()]

    # plot reactions
    print(reaction_ids)
    ax_r = df.plot(x='time', y=reaction_ids + ['vR3'])
    fig = ax_r.get_figure()
    fig.savefig('reactions.png')

    # plot species
    print(species_ids)
    ax_s = df.plot(x='time', y=species_ids)
    fig = ax_s.get_figure()
    fig.savefig('species.png')

    df.to_csv("simulation.csv", sep="\t")
def main (args):
  """
    Usage:  printRenderInformation <input file>
            prints a summary of the render information object.
  """
  
  if (len(args) != 2):
        print(main.__doc__)
        return 1


  inputFile = args[1];

  doc = libsbml.readSBMLFromFile(inputFile)

  print("Using libSBML: {0} supporting packages for:".format(libsbml.getLibSBMLDottedVersion()))
  for i in range (libsbml.SBMLExtensionRegistry.getNumRegisteredPackages()):
    print("\t" + libsbml.SBMLExtensionRegistry.getRegisteredPackageName(i))

  print("\nThe document is: level {0}, version {1}".format(doc.getLevel(), doc.getVersion()))
  for i in range(doc.getNumPlugins()):
      print("  doc uses package: {0}".format(doc.getPlugin(i).getElementNamespace()))
    
  print("\n")

  numErrors = doc.getNumErrors(libsbml.LIBSBML_SEV_ERROR)

  if numErrors > 0:
      print("Encountered errors while reading the file. ")
      print("Please correct the following errors and try again.")
      doc.printErrors()
      return 2

  model = doc.getModel()

  plugin = model.getPlugin("layout")

  if plugin == None or plugin.getNumLayouts() == 0:
      print("The loaded model contains no layout information, please add these first.")
      return 3

  lolPlugin = plugin.getListOfLayouts().getPlugin("render")
  if (lolPlugin != None and lolPlugin.getNumGlobalRenderInformationObjects() > 0):
      print("The loaded model contains global Render information: ")

      for  i in range ( 0, lolPlugin.getNumGlobalRenderInformationObjects()):
          info = lolPlugin.getRenderInformation(i)

          print_render_info(info)

  # add render information to the first layout
  layout = plugin.getLayout(0)

  rPlugin = layout.getPlugin("render")
  if (rPlugin != None and rPlugin.getNumLocalRenderInformationObjects() > 0):
      print("The loaded model contains local Render information. ")
      # here we would do the same as above for the local render information ...

  return 0
예제 #6
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
예제 #7
0
def validation_example():
    for p in model_paths:
        for with_units in [False, True]:
            t_start = time.time()
            print("\n*** {} ***".format(p))
            doc = libsbml.readSBMLFromFile(p)
            t_read = time.time()
            print('reading: {:.3} [s]'.format(t_read - t_start))

            doc.setConsistencyChecks(libsbml.LIBSBML_CAT_UNITS_CONSISTENCY, with_units)
            doc.checkConsistency()
            t_check = time.time()
            print('checkConsistency (units={}): {:.3} [s]'.format(with_units, t_check - t_read))
예제 #8
0
    def __init__(self, graph, sbml_filepath):
        self.path = sbml_filepath
        self.graph = graph

        # hashing for unique id
        self.md5 = data.hash_for_file(sbml_filepath)

        #  sbml model
        self.doc = libsbml.readSBMLFromFile(sbml_filepath)
        self.model = self.doc.getModel()
        self.model_id = self.model.getId()

        # transaction
        self.tx = None
예제 #9
0
def main (args):
  """Usage: setIdFromNames filename output
  """
  if len(args) != 3:
    print(main.__doc__)
    sys.exit(1)
  
  filename = args[1];
  output = args[2];
  
  # read the document
  start = time.time() * 1000;
  document = libsbml.readSBMLFromFile(filename);
  stop = time.time() * 1000;
  
  
  print ""
  print "            filename: {0}".format( filename);
  print "      read time (ms): {0}".format( stop - start);
  
  # stop in case of serious errors
  errors = document.getNumErrors(libsbml.LIBSBML_SEV_ERROR);
  if (errors > 0):
      print "            error(s): {0}".format(errors);
      document.printErrors();
      sys.exit (errors);
  
  
  # get a list of all elements, as we will need to know all identifiers
  # so that we don't create duplicates. 
  allElements = document.getListOfAllElements();
  
  # get a list of all ids
  allIds = getAllIds(allElements);
  
  # create the transformer with the ids
  trans = SetIdFromNames(allIds);
  
  # rename the identifiers (using the elements we already gathered before)
  start = time.time() * 1000;
  document.getModel().renameIDs(allElements, trans);
  stop = time.time() * 1000;
  print "    rename time (ms): {0}".format(stop - start);
  
  # write to file
  start = time.time() * 1000;
  libsbml.writeSBMLToFile(document, output);
  stop = time.time() * 1000;
  print "     write time (ms): {0}".format(stop - start);
  print "";
예제 #10
0
def main (args):
  """Usage: setIdFromNames filename output
  """
  if len(args) != 3:
    print(main.__doc__)
    sys.exit(1)
  
  filename = args[1];
  output = args[2];
  
  # read the document
  start = time.time() * 1000;
  document = libsbml.readSBMLFromFile(filename);
  stop = time.time() * 1000;
  
  
  print ""
  print "            filename: {0}".format( filename);
  print "      read time (ms): {0}".format( stop - start);
  
  # stop in case of serious errors
  errors = document.getNumErrors(libsbml.LIBSBML_SEV_ERROR);
  if (errors > 0):
      print "            error(s): {0}".format(errors);
      document.printErrors();
      sys.exit (errors);
  
  
  # get a list of all elements, as we will need to know all identifiers
  # so that we don't create duplicates. 
  allElements = document.getListOfAllElements();
  
  # get a list of all ids
  allIds = getAllIds(allElements);
  
  # create the transformer with the ids
  trans = SetIdFromNames(allIds);
  
  # rename the identifiers (using the elements we already gathered before)
  start = time.time() * 1000;
  document.getModel().renameIDs(allElements, trans);
  stop = time.time() * 1000;
  print "    rename time (ms): {0}".format(stop - start);
  
  # write to file
  start = time.time() * 1000;
  libsbml.writeSBMLToFile(document, output);
  stop = time.time() * 1000;
  print "     write time (ms): {0}".format(stop - start);
  print "";
예제 #11
0
def report(request, model_pk):
    """
    Creates the report view for the given SBML model.
    SBML has to be in the database.
    """
    sbml_model = get_object_or_404(CompModel, pk=model_pk)
    sbml_path = sbml_model.file.path     # this is the absolute path in filesystem
    
    doc = libsbml.readSBMLFromFile(str(sbml_path))
    model = doc.getModel()
    if not model:
        print 'Model could not be read.'
        raise Http404
    
    # Create the value_dictionary
    values = create_value_dictionary(model)

    # Render the template with the data
    # TODO: do the template rendering on model creation and only load the model report afterwards


    template = loader.get_template('report/report.html')
    context = RequestContext(request, {
        'doc': doc,
        'sbml_model': sbml_model,
        'model': model,
        'values': values, 
        'units': model.getListOfUnitDefinitions(),
        'units_size': model.getListOfUnitDefinitions().size(),
        'compartments': model.getListOfCompartments(),
        'compartments_size': model.getListOfCompartments().size(),
        'functions': model.getListOfFunctionDefinitions(),
        'functions_size': model.getListOfFunctionDefinitions().size(),
        'parameters': model.getListOfParameters(),
        'parameters_size': model.getListOfParameters().size(),
        'rules': model.getListOfRules(),
        'rules_size': model.getListOfRules().size(),
        'assignments': model.getListOfInitialAssignments(),
        'assignments_size': model.getListOfInitialAssignments().size(),
        'species': model.getListOfSpecies(),
        'species_size': model.getListOfSpecies().size,
        'reactions': model.getListOfReactions(),
        'reactions_size': model.getListOfReactions().size(),
        'constraints': model.getListOfConstraints(),
        'constraints_size': model.getListOfConstraints().size(),
        'events': model.getListOfEvents(),
        'events_size': model.getListOfEvents().size(),
    })
    return HttpResponse(template.render(context))
예제 #12
0
def validation_example():
    for p in model_paths:
        for with_units in [False, True]:
            t_start = time.time()
            print("\n*** {} ***".format(p))
            doc = libsbml.readSBMLFromFile(p)
            t_read = time.time()
            print('reading: {:.3} [s]'.format(t_read - t_start))

            doc.setConsistencyChecks(libsbml.LIBSBML_CAT_UNITS_CONSISTENCY,
                                     with_units)
            doc.checkConsistency()
            t_check = time.time()
            print('checkConsistency (units={}): {:.3} [s]'.format(
                with_units, t_check - t_read))
예제 #13
0
def validate_sbml_file(sbml_file, xpath_expressions=None):
    doc = libsbml.readSBMLFromFile(sbml_file)

    if doc.getNumErrors(libsbml.LIBSBML_SEV_ERROR) > 0:
        logging.error(f"file {sbml_file} had errors: " +
                      doc.getErrorLog().toString())
        return False

    elif doc.getNumErrors(libsbml.LIBSBML_SEV_WARNING) > 0:
        logging.warning(f"file {sbml_file} had warnings:  " +
                        doc.getErrorLog().toString())

    if xpath_expressions is not None:
        return xpath_expressions_exist(doc, xpath_expressions)

    return True
예제 #14
0
def test_mass_balance():
    doc = libsbml.readSBMLFromFile(data.DEMO_SBML)

    # add defaults
    fbc.add_default_flux_bounds(doc)

    import tempfile
    f = tempfile.NamedTemporaryFile('w', suffix='xml')
    libsbml.writeSBMLToFile(doc, f.name)
    f.flush()
    model = cobra.io.read_sbml_model(f.name)

    # mass/charge balance
    for r in model.reactions:
        mb = r.check_mass_balance()
        # all metabolites are balanced
        assert len(mb) == 0
예제 #15
0
def load_kinetic_model(filename, kmap=None):
    """
    Load the dynamic model present in a SBML file.
    Args:
        filename (str): SBML file.
        kmap (dict): Dictionary with the parameters that can be used in the strain
            optimization process for each reaction.{id_reaction: [param1, param2]}

    Returns: KineticModel
        Contains all information related with the dynamic model
            (reactions, kinetic equations, metabolites, compartments, etc.)
    """
    document = readSBMLFromFile(filename)
    sbmlModel = document.getModel()

    if sbmlModel is None:
        raise IOError('Failed to load model.')

    model = KineticModel(sbmlModel.getId())

    _load_compartments(sbmlModel, model)
    _load_metabolites(sbmlModel, model)
    _load_reactions(sbmlModel, model)
    _load_concentrations(sbmlModel, model)
    _load_global_parameters(sbmlModel, model)
    _load_local_parameters(sbmlModel, model)
    _load_ratelaws(sbmlModel, model)
    _load_assignment_rules(sbmlModel, model)

    # parse rates, rules and xdot expressions
    model._set_parsed_attr()

    if isinstance(kmap, str):
        aux = OrderedDict([(rId, re.findall(kmap, ratelaw))
                           for rId, ratelaw in model.ratelaws.items()])
        # aux = OrderedDict([(rId ,  [rId+"_"+x for x in re.findall("(rmax\w*)", ratelaw)])
        #                    for rId, ratelaw in model.ratelaws.items()])  # CHASSAGNOLE
        model.reacParamsFactors = OrderedDict([(rId, params)
                                               for rId, params in aux.items()
                                               if len(params) > 0])
    else:
        model.set_reactions_parameters_factors(kmap)
    return model
예제 #16
0
    def _process_top(self):
        """ Process the top model.

        Reads top model and submodels.

        :return:
        """
        logging.debug('* _process_top')
        self.doc_top = libsbml.readSBMLFromFile(self.sbml_top)
        self.model_top = self.doc_top.getModel()
        if self.model_top is None:
            warnings.warn("No top level model found.")

        self.framework_top = builder.get_framework(self.model_top)
        if self.framework_top is not builder.MODEL_FRAMEWORK_ODE:
            warnings.warn(
                "The top level model framework is not ode: {}".format(
                    self.framework_top))

        # get frameworks for submodels
        doc_comp = self.doc_top.getPlugin(builder.SBML_COMP_NAME)
        model_comp = self.model_top.getPlugin(builder.SBML_COMP_NAME)

        # models are processed in the order they are listed in the listOfSubmodels
        for submodel in model_comp.getListOfSubmodels():
            modelRef = submodel.getModelRef()

            # check if ExternalModelDefinition
            emd = doc_comp.getExternalModelDefinition(modelRef)
            if emd:
                framework = builder.get_framework(emd.getReferencedModel())
            else:
                # Lookfor ModelDefinition
                md = doc_comp.getModelDefinition(modelRef)
                if md:
                    framework = builder.get_framework(md)
                else:
                    raise ValueError(
                        "No (External)ModelDefinition for modelRef: {}".format(
                            modelRef))

            # store the submodel under the given framework
            self.submodels[framework].append(submodel)
예제 #17
0
def rename_restriced_sids(in_path,
                          out_path,
                          restricted={
                              "x": "x_",
                              "y": "y_",
                              "z": "z_",
                              "t": "t_"
                          }):
    """ Rename restriced sids from given dictionary.
    The new sids must not exist in the model!

    :param in_path: sbml in file
    :param out_path: sbml out file
    :param restricted: dictionary of replacements
    :return:
    """
    print('-' * 80)
    print('Renaming restricted ids')
    print('-' * 80)

    print('reading SBML')
    # doc = sbmlio.read_sbml(in_path)
    doc = libsbml.readSBMLFromFile(in_path)
    model = doc.getModel()

    for old_id, new_id in restricted:
        element_x = model.getElementBySId(old_id)
        if element_x is not None:
            print("Renaming: ", old_id, '->', new_id)
            element_x.setId(new_id)

            elements = model.getListOfAllElements()
            N = len(elements)
            for k, element in enumerate(elements):
                if k % int(round(N / 20)) == 0:
                    print("{:1.2f}".format(1.0 * k / N))

                # element.renameSIdRefs(oldid="old_id", newid="new_id")
                element.renameSIdRefs(old_id, new_id)

    print('writing SBML')
    # libsbml.writeSBMLToFile(doc, out_path)
    sbmlio.write_sbml(doc, out_path, validate=validation.VALIDATION_NO_UNITS)
예제 #18
0
def prepare_rbc_model(model_path, name, target_dir):
    """ Add ports to the RBC model.

    :param model_path:
    :param name:
    :param target_dir:
    :return:
    """
    doc = libsbml.readSBMLFromFile(model_path)  # type: libsbml.SBMLDocument

    # add comp package
    # sbmlns = libsbml.SBMLNamespaces(doc.getLevel(), doc.getVersion())
    # sbmlns.addPackageNamespace("comp", 1)
    doc.enablePackage("http://www.sbml.org/sbml/level3/version1/comp/version1",
                      "comp", True)
    # doc.setNamespaces(sbmlns)
    doc.setPackageRequired("comp", True)

    model = doc.getModel()
    model.setId(name)
    print(model)
    cmodel = model.getPlugin("comp")  # type: libsbml.CompModelPlugin

    def create_port(sid):
        """" Creates port for given SBase ID."""
        p = cmodel.createPort()  # type: libsbml.Port
        port_sid = f'{sid}{PORT_SUFFIX}'
        p.setId(port_sid)
        p.setName(port_sid)
        p.setMetaId(port_sid)
        p.setSBOTerm(599)  # port
        p.setIdRef(sid)
        return p

    # add ports
    cmodel = model.getPlugin("comp")  # type: libsbml.CompModelPlugin
    for sid in ['Vplasma', 'glcEXT', 'lacEXT', 'phosEXT', 'pyrEXT']:
        create_port(sid)

    output_path = os.path.join(target_dir, "{}.xml".format(name))
    libsbml.writeSBMLToFile(doc, output_path)
    return output_path
예제 #19
0
def parameters_for_sensitivity(r, model_path):
    """Get the parameter ids for the sensitivity analysis.

    This includes all constant parameters (not changed via assignments),
    excluding
    - parameters with value=0 (no effect on model, dummy parameter)
    - parameters which are physical constants, e.g., molecular weights

    :param r:
    :param model_path:
    :return:
    """
    doc = libsbml.readSBMLFromFile(model_path)  # type: libsbml.SBMLDocument
    model = doc.getModel()  # type: libsbml.Model

    # constant parameters in model
    pids_const = []
    for p in model.getListOfParameters():
        if p.getConstant() == True:
            pids_const.append(p.getId())

    # print('constant parameters:', len(pids_const))

    # filter parameters
    parameters = {}
    for pid in pids_const:
        # dose parameters
        if (pid.startswith("IVDOSE_")) or (pid.startswith("PODOSE_")):
            continue

        # physical parameters
        if (pid.startswith("Mr_")) or pid in ["R_PDB"]:
            continue

        # zero parameters
        value = r[pid]
        if np.abs(value) < 1E-8:
            continue

        parameters[pid] = value

    return parameters
예제 #20
0
def list_ports(model_path):
    """

    :param model_path: path to sbml model
    :return:
    """
    """ List the ports in the given model.

    :return:
    """
    if not os.path.exists(model_path):
        raise IOError("SBML path does not exist.")

    doc = libsbml.readSBMLFromFile(model_path)  # type: libsbml.SBMLDocument
    model = doc.getModel()  # type: libsbml.Model
    model_comp = model.getPlugin("comp")  # type: libsbml.CompModelPlugin
    print(model_comp)
    for port in model_comp.getListOfPorts():  # type: libsbml.Port
        print("\tPort: ", port.getId(), port.getMetaId(), port.getIdRef(),
              port.getMetaIdRef(), port.getUnitRef(), port.getPortRef())
예제 #21
0
    def __init__(self, submodel, source, fba_rules):
        self.source = source
        self.submodel = submodel

        # read the model
        self.fba_doc = libsbml.readSBMLFromFile(source)
        self.fba_model = self.fba_doc.getModel()
        self.cobra_model = cobra.io.read_sbml_model(source)

        # parameters to replace in top model
        self.fba_rules = self.process_fba_rules(fba_rules)

        # bounds are mappings from parameters to reactions
        #       parameter_id -> [rid1, rid2, ...]
        self.ub_parameters = defaultdict(list)
        self.lb_parameters = defaultdict(list)
        self.ub_replacements = []
        self.lb_replacements = []
        self.flat_mapping = {}
        self.process_bounds()
예제 #22
0
    def __init__(self, test_dir, current_test_case, output_dir, sbml_lvl,
                 sbml_version):
        # Inizializzo gli attributi standard della classe
        self.working_dir = test_dir
        self.current_test = osp.join(self.working_dir, current_test_case)
        self.output_dir = osp.join(self.current_test, output_dir)
        self.setting_file = osp.join(self.current_test,
                                     f"{current_test_case}-settings.txt")
        self.model = osp.join(self.current_test,
                              f"{current_test_case}-model.m")
        self.sbml = osp.join(
            self.current_test,
            f"{current_test_case}-sbml-l{sbml_lvl}v{sbml_version}.xml")
        self.test_id = current_test_case

        # Prendo il nome del modello, direttamente dall'SBML
        self.model_name = readSBMLFromFile(self.sbml).getModel().getName()

        # Prendo la configurazione di simulazione
        self.simul_conf = self.extract_simul_config()
예제 #23
0
def add_uncertainty_example(tmp: bool = False) -> None:
    """Add uncertainty to a model."""
    output_dir = str(Path(__file__).parent)
    doc = libsbml.readSBMLFromFile(os.path.join(
        output_dir, "e_coli_core.xml"))  # type: libsbml.SBMLDocument

    # activate distrib
    doc.enablePackage(
        "http://www.sbml.org/sbml/level3/version1/distrib/version1", "distrib",
        True)
    doc.setPackageRequired("distrib", True)

    model = doc.getModel()  # type: libsbml.Model
    model_fbc = model.getPlugin("fbc")  # type: libsbml.FbcModelPlugin

    # --------------------------------
    # [2] write gene expression data
    # --------------------------------
    gp = model_fbc.getGeneProduct(0)
    print(gp)
    gp_distrib = gp.getPlugin("distrib")  # type: libsbml.DistribSBasePlugin
    print(gp_distrib)

    if gp_distrib:
        uncertainty = gp_distrib.createUncertainty(
        )  # type: libsbml.Uncertainty

        up_mean = uncertainty.createUncertParameter(
        )  # type: libsbml.UncertParameter
        up_mean.setType(libsbml.DISTRIB_UNCERTTYPE_MEAN)
        up_mean.setValue(2.5)
    else:
        logging.error("DistribSBasePlugin not working for fbc:GeneProduct.")

    # store model with gene expression data
    if tmp:
        with tempfile.NamedTemporaryFile(suffix=".xml") as f_sbml:
            libsbml.writeSBMLToFile(doc, f_sbml.name)
    else:
        libsbml.writeSBMLToFile(
            doc, os.path.join(output_dir, "e_coli_core_expression.xml"))
예제 #24
0
    def parser(self, sbml_file, **kwargs):
        from BioModelsDAG.utils import extract_model_data

        with open("bto_lookup.json") as f:
            bto_lookup = json.load(f)

        pattern = re.compile("BTO:\d{7}")
        model_data = extract_model_data(sbml_file)
        model_data["color"] = "green"

        model = libsbml.readSBMLFromFile(sbml_file.name).getModel()
        for element in model.getListOfAllElements():
            for bto_id in pattern.findall(element.getAnnotationString()):
                if bto_id in bto_lookup:
                    yield model_data, "", {
                        "name": bto_lookup[bto_id],
                        "id": bto_id,
                        "color": "red"
                    }
                else:
                    yield model_data, "", {"name": bto_id, "color": "red"}
예제 #25
0
    def __init__(self, submodel, source, model_top=None):
        """ Creates the FBAModel.
        Processes the bounds for all reactions.
        Reads the sbml and cobra model.
        Processes the bound replacements and updates.

        :param submodel:
        :param source:
        :param flux_rules:
        """
        self.source = source
        self.submodel = submodel

        # read sbml and cobra model
        self.doc = libsbml.readSBMLFromFile(source)
        self.model = self.doc.getModel()
        self.cobra_model = cobra.io.read_sbml_model(source)

        # bounds are mappings from parameters to reactions
        #       parameter_id -> [rid1, rid2, ...]
        self.ub_parameters = defaultdict(list)
        self.lb_parameters = defaultdict(list)
        self.fba2top_bounds = None

        # reaction mapping (top <-> fba)
        self.fba2top_reactions = None
        self.top2flat_reactions = None

        # objective sense
        self._process_objective_direction()

        # bounds
        self.ub_pid2rid = None
        self.lb_pid2rid = None

        # process the top (ode) <-> fba connections (bounds & reaction replacements)
        if model_top is not None:
            self._process_bound_replacements(model_top)
            self._process_fba2top_reactions(model_top)
            self._process_top2flat_reactions(model_top)
예제 #26
0
def load_metabolic_model(model_name, species='homo_sapiens'):
    """
    Loads the metabolic model from `file_name`, returning a Model object
    """

    if model_name.endswith('_mat'):
        model = importMATLAB.load(model_name, species)
    else:
        model_dir = os.path.join(MODEL_DIR, model_name)
        model_file = [
            x for x in os.listdir(model_dir)
            if x.lower().endswith('.xml') or x.lower().endswith('.xml.gz')
        ]

        if len(model_file) == 0:
            raise Exception(
                "Invalid model - could not find .xml or .xml.gz file in " +
                model_dir)
        else:
            model_file = model_file[0]

        full_path = os.path.join(model_dir, model_file)
        sbmlDocument = libsbml.readSBMLFromFile(full_path)

        level = sbmlDocument.getLevel()

        if level == 3:
            model = importSBML3.load(model_name, sbmlDocument)
        elif level == 2:
            model = importSBML2.load(model_name, sbmlDocument)
        else:
            raise Exception("Invalid level {} for model {}".format(
                level, model_file))

        resolve_genes(model)
        convert_species(model, species)
        clean_reactions(model)
        limit_maximum_flux(model, 1000)

    return model
def validate_model(filename, name=None, validate_consistency=True, config=None):
    """ Check that a model is valid

    Args:
        filename (:obj:`str`): path to model
        name (:obj:`str`, optional): name of model for use in error messages
        validate_consistency (:obj:`str`, optional): whether to check the consistency of the model
        config (:obj:`Config`, optional): whether to fail on missing includes

    Returns:
        :obj:`tuple`:

            * nested :obj:`list` of :obj:`str`: nested list of errors (e.g., required ids missing or ids not unique)
            * nested :obj:`list` of :obj:`str`: nested list of errors (e.g., required ids missing or ids not unique)
            * :obj:`libsbml.SBMLDocument`: model
    """
    errors = []
    warnings = []
    doc = None

    if filename:
        if os.path.isfile(filename):
            doc = libsbml.readSBMLFromFile(filename)
            if validate_consistency:
                doc.checkConsistency()

            for i_error in range(doc.getNumErrors()):
                sbml_error = doc.getError(i_error)
                if sbml_error.isInfo() or sbml_error.isWarning():
                    warnings.append([sbml_error.getMessage()])
                else:
                    errors.append([sbml_error.getMessage()])

        else:
            errors.append(['`{}` is not a file.'.format(filename or '')])

    else:
        errors.append(['`filename` must be a path to a file, not `{}`.'.format(filename or '')])

    return (errors, warnings, doc)
예제 #28
0
    def __init__(self, submodel, source, model_top=None):
        """ Creates the FBAModel.
        Processes the bounds for all reactions.
        Reads the sbml and cobra model.
        Processes the bound replacements and updates.

        :param submodel:
        :param source:
        :param flux_rules:
        """
        self.source = source
        self.submodel = submodel

        # read sbml and cobra model
        self.doc = libsbml.readSBMLFromFile(source)
        self.model = self.doc.getModel()
        self.cobra_model = cobra.io.read_sbml_model(source)

        # bounds are mappings from parameters to reactions
        #       parameter_id -> [rid1, rid2, ...]
        self.ub_parameters = defaultdict(list)
        self.lb_parameters = defaultdict(list)
        self.fba2top_bounds = None

        # reaction mapping (top <-> fba)
        self.fba2top_reactions = None
        self.top2flat_reactions = None

        # objective sense
        self._process_objective_direction()

        # bounds
        self.ub_pid2rid = None
        self.lb_pid2rid = None

        # process the top (ode) <-> fba connections (bounds & reaction replacements)
        if model_top is not None:
            self._process_bound_replacements(model_top)
            self._process_fba2top_reactions(model_top)
            self._process_top2flat_reactions(model_top)
예제 #29
0
def readSBMLModel(sbml_model):
    try:
        sbml = getRoadrunnerSBML(sbml_model)
    except TypeError:
        if os.path.exists(sbml_model) and os.path.isfile(sbml_model):
            # it's a file path
            if os.path.splitext(sbml_model)[1] == '.sb':
                # it's an Antimony file
                with open(sbml_model) as f:
                    return libsbml.readSBML(antimonyConverter.antimonyToSBML(f.read()))
            elif os.path.splitext(sbml_model)[1] == '.txt':
                raise RuntimeError('File ending in ".txt" is ambiguous - pass an SBML file (.xml) or an Antimony file (.sb).')
            else:
                return libsbml.readSBMLFromFile(sbml_model)
        else:
            # check if it's Antimony source
            try:
                return libsbml.readSBML(antimonyConverter.antimonyToSBML(sbml_model))
            except:
                # it better be SBML
                # this will throw if it's not SBML
                return libsbml.readSBML(model)
def main(args):
    """Usage: stringInput filename
  """

    if len(args) != 2:
        print(main.__doc__)
        sys.exit(2)

    filename = args[1]
    document = libsbml.readSBMLFromFile(filename)

    errors = document.getNumErrors()

    print("filename: " + filename + "\n")

    if errors > 0:
        document.printErrors()
        return errors

    # Model

    m = document.getModel()

    # testing ascii input, this should work for Python 2 and 3

    ascii_name = str('new_ascii_name')
    m.setName(ascii_name)

    print(type(m.getName()))

    # testing unicode input, this should also work for Python 3 and
    # Python 2 if libSBML has been compiled with Swig version > 3.0.8

    unicode_name = u'new_unicode_name'
    m.setName(unicode_name)

    print(type(m.getName()))

    return errors
예제 #31
0
def inline_function_definitions(sbml_file, output_file=None):
    """ Inlines all function definitions in the given SBML file
    
    :param sbml_file: the sbml file to load
    :param output_file: the output file where to write the SBML to
    :return: 
    """

    doc = libsbml.readSBMLFromFile(sbml_file)
    if doc.getNumErrors(libsbml.LIBSBML_SEV_ERROR) > 0:
        logging.error("invalid SBML document " + doc.getErrorLog().toString())
        return False

    if convert_function_definitions(doc) != libsbml.LIBSBML_OPERATION_SUCCESS:
        logging.error("Conversion failed with: " +
                      doc.getErrorLog().toString())
        return False

    if output_file is None:
        output_file = sbml_file

    libsbml.writeSBMLToFile(doc, output_file)
예제 #32
0
def main (args):
  """Usage: stringInput filename
  """

  if len(args) != 2:
    print(main.__doc__)
    sys.exit(2)

  filename = args[1]
  document = libsbml.readSBMLFromFile(filename)

  errors = document.getNumErrors()

  print("filename: " + filename + "\n")

  if errors > 0:
      document.printErrors()
      return errors

  # Model
  
  m = document.getModel()

  # testing ascii input, this should work for Python 2 and 3
  
  ascii_name = str('new_ascii_name')
  m.setName(ascii_name)
  
  print(type(m.getName()))
  
  # testing unicode input, this should also work for Python 3 and
  # Python 2 if libSBML has been compiled with Swig version > 3.0.8
  
  unicode_name = u'new_unicode_name'
  m.setName(unicode_name)
  
  print(type(m.getName()))
  
  return errors
예제 #33
0
    def _process_top(self):
        """ Process the top model.

        Reads top model and submodels.

        :return:
        """
        logging.debug('* _process_top')
        self.doc_top = libsbml.readSBMLFromFile(self.sbml_top)
        self.model_top = self.doc_top.getModel()
        if self.model_top is None:
            warnings.warn("No top level model found.")

        self.framework_top = builder.get_framework(self.model_top)
        if self.framework_top is not builder.MODEL_FRAMEWORK_ODE:
            warnings.warn("The top level model framework is not ode: {}".format(self.framework_top))

        # get frameworks for submodels
        doc_comp = self.doc_top.getPlugin(builder.SBML_COMP_NAME)
        model_comp = self.model_top.getPlugin(builder.SBML_COMP_NAME)

        # models are processed in the order they are listed in the listOfSubmodels
        for submodel in model_comp.getListOfSubmodels():
            modelRef = submodel.getModelRef()

            # check if ExternalModelDefinition
            emd = doc_comp.getExternalModelDefinition(modelRef)
            if emd:
                framework = builder.get_framework(emd.getReferencedModel())
            else:
                # Lookfor ModelDefinition
                md = doc_comp.getModelDefinition(modelRef)
                if md:
                    framework = builder.get_framework(md)
                else:
                    raise ValueError("No (External)ModelDefinition for modelRef: {}".format(modelRef))

            # store the submodel under the given framework
            self.submodels[framework].append(submodel)
예제 #34
0
    def __init__(self, top_level_file):
        """ Create the simulator with the top level SBML file.

        The models are resolved to their respective simulation framework.
        The top level network must be an ode network.
        """
        self.sbml_top = top_level_file
        # read top level model
        self.doc_top = libsbml.readSBMLFromFile(self.sbml_top)
        self.model_top = self.doc_top.getModel()
        self.framework_top = self.get_framework(self.model_top)
        if self.framework_top is not MODEL_FRAMEWORK_ODE:
            warnings.warn(
                "The top level model framework is not ode: {}".format(
                    self.framework_top))

        self.submodels = defaultdict(list)
        self.rr_comp = None
        self.fba_models = []

        self._process_top_level()
        self._prepare_models()
예제 #35
0
def rename_restriced_sids(in_path, out_path,
                          restricted={"x": "x_", "y": "y_", "z": "z_", "t": "t_"}):
    """ Rename restriced sids from given dictionary.
    The new sids must not exist in the model!

    :param in_path: sbml in file
    :param out_path: sbml out file
    :param restricted: dictionary of replacements
    :return:
    """
    print('-' * 80)
    print('Renaming restricted ids')
    print('-' * 80)


    print('reading SBML')
    # doc = sbmlio.read_sbml(in_path)
    doc = libsbml.readSBMLFromFile(in_path)
    model = doc.getModel()

    for old_id, new_id in restricted:
        element_x = model.getElementBySId(old_id)
        if element_x is not None:
            print("Renaming: ", old_id, '->', new_id)
            element_x.setId(new_id)

            elements = model.getListOfAllElements()
            N = len(elements)
            for k, element in enumerate(elements):
                if k % int(round(N/20)) == 0:
                    print("{:1.2f}".format(1.0*k/N))

                # element.renameSIdRefs(oldid="old_id", newid="new_id")
                element.renameSIdRefs(old_id, new_id)

    print('writing SBML')
    # libsbml.writeSBMLToFile(doc, out_path)
    sbmlio.write_sbml(doc, out_path, validate=validation.VALIDATION_NO_UNITS)
def main (args):
  """Usage: getAllElementsWithNotes filename
  """
  if len(args) != 2:
    print(main.__doc__)
    sys.exit(1)
  
  filename = args[1];
  
  # read the document
  start = time.time() * 1000;
  document = libsbml.readSBMLFromFile(filename);
  stop = time.time() * 1000;
  
  
  print ""
  print "            filename: {0}".format( filename);
  print "      read time (ms): {0}".format( stop - start);
  
  # stop in case of serious errors
  errors = document.getNumErrors(libsbml.LIBSBML_SEV_ERROR);
  if (errors > 0):
      print "            error(s): {0}".format(errors);
      document.printErrors();
      sys.exit (errors);
  
  
  # create the filter we want to use
  filter = NotesFilter()

  # get a list of all elements with notes
  start = time.time() * 1000;
  print "    searching ......:"
  allElements = document.getListOfAllElements(filter);
  stop = time.time() * 1000;
  print "    search time (ms): {0}".format(stop - start);

  print " elements with notes: {0}".format(allElements.getSize())
예제 #37
0
def main (args):
    """Usage: getAllElementsWithNotes filename
    """
    if len(args) != 2:
        print(main.__doc__)
        sys.exit(1)

    filename = args[1];

    # read the document
    start = time.time() * 1000;
    document = libsbml.readSBMLFromFile(filename);
    stop = time.time() * 1000;


    print ""
    print "            filename: {0}".format( filename);
    print "      read time (ms): {0}".format( stop - start);

    # stop in case of serious errors
    errors = document.getNumErrors(libsbml.LIBSBML_SEV_ERROR);
    if (errors > 0):
        print "            error(s): {0}".format(errors);
        document.printErrors();
        sys.exit (errors);


    # create the filter we want to use
    filter = NotesFilter()

    # get a list of all elements with notes
    start = time.time() * 1000;
    print "    searching ......:"
    allElements = document.getListOfAllElements(filter);
    stop = time.time() * 1000;
    print "    search time (ms): {0}".format(stop - start);

    print " elements with notes: {0}".format(allElements.getSize())
예제 #38
0
def example(path):
    """
    Example FBA with demo model.

    :param path:
    :type path:
    :return:
    :rtype:
    """
    doc = libsbml.readSBMLFromFile(path)

    # add defaults
    fbc.add_default_flux_bounds(doc)

    import tempfile
    f = tempfile.NamedTemporaryFile('w', suffix='xml')
    libsbml.writeSBMLToFile(doc, f.name)
    f.flush()
    model = cobra.io.read_sbml_model(f.name)

    # mass/charge balance
    for r in model.reactions:
        mb = r.check_mass_balance()
        print(r.id, mb)
예제 #39
0
def example(path):
    """
    Example FBA with demo model.

    :param path:
    :type path:
    :return:
    :rtype:
    """
    doc = libsbml.readSBMLFromFile(path)

    # add defaults
    fbc.add_default_flux_bounds(doc)

    import tempfile
    f = tempfile.NamedTemporaryFile('w', suffix='xml')
    libsbml.writeSBMLToFile(doc, f.name)
    f.flush()
    model = cobra.io.read_sbml_model(f.name)

    # mass/charge balance
    for r in model.reactions:
        mb = r.check_mass_balance()
        print(r.id, mb)
예제 #40
0
def runSingleSBML(member_name, rpsbml_string, inSBML, isMerge, path_id):
    #open one of the rp SBML files
    input_rpsbml = rpSBML.rpSBML('inputMergeModel',
                                 libsbml.readSBMLFromFile(inSBML))
    rpsbml = rpSBML.rpSBML(member_name,
                           libsbml.readSBMLFromString(rpsbml_string))
    #read the input GEM sbml model
    #input_rpsbml = rpSBML.rpSBML('inputMergeModel', libsbml.readSBMLFromString(inSBML_string))
    #print(input_rpsbml)
    #print(input_rpsbml.model)
    rpsbml.mergeModels(input_rpsbml.model)
    rpfba = rpFBA.rpFBA(input_rpsbml)
    rpfba.allObj(path_id)
    if isMerge:
        ##### pass FBA results to the original model ####
        groups = rpfba.rpsbml.model.getPlugin('groups')
        rp_pathway = groups.getGroup(path_id)
        for member in rp_pathway.getListOfMembers():
            reacFBA = rpfba.rpsbml.model.getReaction(member.getIdRef())
            reacIN = rpsbml.model.getReaction(member.getIdRef())
            reacIN.setAnnotation(reacFBA.getAnnotation())
        return libsbml.writeSBMLToString(rpsbml.document).encode('utf-8')
    else:
        return libsbml.writeSBMLToString(input_rpsbml.document).encode('utf-8')
예제 #41
0
def set_names_as_ids(f_in, f_out=None):
    """ Sets the element as id on all elements in the model.

    :param f_in: SBML input file
    :param f_out:
    :return:
    """
    doc = libsbml.readSBMLFromFile(f_in)
    model = doc.getModel()
    model.populateAllElementIdList()
    sid_list = model.getAllElementIdList()

    for k in range(sid_list.size()):
        sid = sid_list.at(k)
        element = model.getElementBySId(sid)
        if (element is not None) and hasattr(element, 'setName'):
            print(element.getName(), '->', sid)
            element.setName(sid)

    if f_out is None:
        suffix = '_copasi'
        tokens = f_in.split('.')
        if len(tokens) > 1:
            f_out = ".".join(tokens[0:-1]) + suffix + "." + tokens[-1]
        else:
            f_out = tokens[0] + suffix

    # write to output file
    libsbml.writeSBMLToFile(doc, f_out)

    print('*' * 60)
    print('Names replaced with ids')
    print('*' * 60)
    print('f_in:\t', f_in)
    print('f_out:\t', f_out)
    print('*' * 60)
예제 #42
0
from __future__ import print_function
from os.path import join as pjoin
import libsbml

directory = './emd_files/'
in_file = pjoin(directory, 'diauxic_bounds.xml')
out_file = pjoin(directory, 'diauxic_bounds_out.xml')

doc = libsbml.readSBMLFromFile(in_file)
sbml_str = libsbml.writeSBMLToString(doc)
print(sbml_str)



예제 #43
0
from __future__ import absolute_import, print_function

import libsbml
import time

model_paths = ["rbc_top.xml"]

for p in model_paths:
    for with_units in [False, True]:
        t_start = time.time()
        print("\n*** {} ***".format(p))
        doc = libsbml.readSBMLFromFile(p)
        t_read = time.time()
        print('reading: {:.3} [s]'.format(t_read - t_start))

        doc.setConsistencyChecks(libsbml.LIBSBML_CAT_UNITS_CONSISTENCY,
                                 with_units)
        doc.checkConsistency()
        t_check = time.time()
        print('checkConsistency (units={}): {:.3} [s]'.format(
            with_units, t_check - t_read))
예제 #44
0
 def __init__(self, path):
     doc = libsbml.readSBMLFromFile(path)
     self.model = doc.getModel()
예제 #45
0
from __future__ import absolute_import, print_function

import libsbml
import time

model_paths = ["rbc_top.xml"]

for p in model_paths:
    for with_units in [False, True]:
        t_start = time.time()
        print("\n*** {} ***".format(p))
        doc = libsbml.readSBMLFromFile(p)
        t_read = time.time()
        print('reading: {:.3} [s]'.format(t_read - t_start))

        doc.setConsistencyChecks(libsbml.LIBSBML_CAT_UNITS_CONSISTENCY, with_units)
        doc.checkConsistency()
        t_check = time.time()
        print('checkConsistency (units={}): {:.3} [s]'.format(with_units, t_check - t_read))


import sys
#sys.path.append('/opt/libsbml/lib/python2.7/site-packages/libsbml/')
import libsbml

doc=libsbml.readSBMLFromFile (sys.argv[1])
doc.setLevelAndVersion(2, 4, False)
#print doc.toSBML()
f = open(sys.argv[2], 'w')
f.write(doc.toSBML())
f.close()
예제 #47
0
                # setting because it is required (if unlucky additional info required)
                # but we can't set it because we can't access the FBCModelPlugins of the ModelDefinitions
                if fbc_model is not None:
                    if not fbc_model.isSetStrict():
                        fbc_model.setStrict(False)
                else:
                    print("WARNING: This should never happen. All ModelDefinitions should have a FBCModelPlugin")

    doc.checkInternalConsistency()
    doc.printErrors()

    return doc


if __name__ == "__main__":
    import libsbml
    from os.path import join as pjoin

    directory = './emd_files/'
    top_file = pjoin(directory, 'diauxic_top.xml')

    # replace the ExternalModelDefinitions with ModelDefinitions
    doc_top = libsbml.readSBMLFromFile(top_file)
    doc_no_emd = flattenExternalModelDefinitions(doc_top)

    # write to file
    libsbml.writeSBMLToFile(doc_no_emd, pjoin(directory, 'test_emd_flat.xml'))
    print(libsbml.__version__)


def sbml_statistics(sbml_path):
    """Calculate dictionary of statistics for given SBML model

    :param sbml_path:
    :return: dict
    """
    doc = libsbml.readSBMLFromFile(sbml_path)  # type: libsbml.SBMLDocument
    model = doc.getModel()  # type: libsbml.Model
    # core
    s = {
        "level_version": "L{}V{}".format(doc.getLevel(), doc.getVersion())
    }

    if model:
        s["function_definitions"] = model.getNumFunctionDefinitions()
        s["unit_definitions"] = model.getNumUnitDefinitions()
        s["compartments"] = model.getNumCompartments()
        s["species"] = model.getNumSpecies()
        s["parameters"] = model.getNumParameters()
        s["initial_assignments"] = model.getNumInitialAssignments()
        s["rules"] = model.getNumRules()
        s["reactions"] = model.getNumReactions()
        s["constraints"] = model.getNumConstraints()
        s["events"] = model.getNumEvents()

        # kineticLaws & localParameters
        s["kinetic_laws"] = 0
        s["kinetic_laws_math"] = 0
        s["parameters_local"] = 0
        for reaction in model.getListOfReactions():  # type: libsbml.Reaction
            if reaction.isSetKineticLaw():
                s["kinetic_laws"] += 1
                klaw = reaction.getKineticLaw()  # type: libsbml.KineticLaw
                if klaw.isSetMath():
                    # math must be set and cannot be a flux_value

                    # some fbc models abuse kinetic laws via FLUX_VALUE
                    math = klaw.getMath()  # type: libsbml.ASTNode
                    formula = libsbml.formulaToL3String(math)
                    if formula != "FLUX_VALUE":
                        s["kinetic_laws_math"] += 1

                s["parameters_local"] += klaw.getNumParameters()

        # rule details
        s["rules_assignment_rules"] = 0
        s["rules_rate_rules"] = 0
        s["rules_algebraic_rules"] = 0
        for rule in model.getListOfRules():  # type: libsbml.Rule
            if rule.isAssignment():
                s["rules_assignment_rules"] += 1
            elif rule.isRate():
                s["rules_rate_rules"] += 1
            elif rule.isAlgebraic():
                s["rules_algebraic_rules"] += 1

        # event details
        s["events_trigger"] = 0
        s["events_priority"] = 0
        s["events_delay"] = 0
        s["events_event_assignments"] = 0

        for event in model.getListOfEvents():  # type: libsbml.Event
            if event.isSetTrigger():
                s["events_trigger"] += 1
            if event.isSetPriority():
                s["events_priority"] += 1
            if event.isSetDelay():
                s["events_delay"] += 1
            s["events_event_assignments"] += event.getNumEventAssignments()
        s["events_math"] = s["events_trigger"] + s["events_priority"] + s["events_delay"] + s["events_event_assignments"]

        s["math"] = s["function_definitions"] + s["initial_assignments"] + s["constraints"] + s["rules"] + s["kinetic_laws_math"] + s["events_math"]

        # FIXME: annotations & SBO terms

    return s
예제 #49
0
    for point in node.polygon_points:
        print("point: ", point)
    for code in node.polygon_codes:
        print("code: ", code)

sll.drawNetwork()

sll.writeSBMLFile("simple_local_out.xml")

print(sll.getCompartmentEdgeColor("vol1"))
print(sll.getCompartmentFillColor("vol1"))
print(sll.getCompartmentLineWidth("vol1"))

# check libsbml API

doc = libsbml.readSBMLFromFile(str(model_file))

model = doc.getModel()

numCompartments = model.getNumCompartments()

print("numCompartments: ", numCompartments)

for index in range(numCompartments):
    compartment = model.getCompartment(index)
    print("id, name: ", compartment.getId(), ", ", compartment.getElementName())


for reaction in sll._SBMLlayout__network.reactions.values():
    for curve in reaction.curves:
        print("curve role: ", curve.role, curve.role_name, curve.role_name.lower()=="substrate")
예제 #50
0
파일: odefac.py 프로젝트: lptolik/sbmlutils
 def from_file(cls, sbml_file):
     doc = libsbml.readSBMLFromFile(sbml_file)  # type: libsbml.SBMLDocument
     return cls(doc)
예제 #51
0
try:
    import libsbml
except ImportError:
    import tesbml as libsbml

doc = libsbml.readSBMLFromFile("limax_pkpd_39.xml")
for r in doc.model.reactions:  # type: libsbml.Reaction
    ud = r.getKineticLaw().getDerivedUnitDefinition()  # type: libsbml.UnitDefinition
    print(r, libsbml.UnitDefinition.printUnits(ud))
 def __init__(self, path):
     doc = libsbml.readSBMLFromFile(path)
     self.model = doc.getModel()
예제 #53
0
def test_demo_annotation():
    """ Annotate the demo network. """

    f_tmp = tempfile.NamedTemporaryFile()
    annotation.annotate_sbml_file(data.DEMO_SBML_NO_ANNOTATIONS, data.DEMO_ANNOTATIONS, f_sbml_annotated=f_tmp.name)
    f_tmp.flush()

    # document
    doc = libsbml.readSBMLFromFile(f_tmp.name)
    assert doc.getSBOTerm() == 293
    assert doc.getSBOTermID() == "SBO:0000293"
    cvterms = doc.getCVTerms()
    # check: is one cv term with 3 resources in bag
    assert len(cvterms) == 1
    assert cvterms[0].getNumResources() == 1

    # model
    model = doc.getModel()
    cvterms = model.getCVTerms()
    assert len(cvterms) == 0

    # compartments
    ce = model.getCompartment('e')
    assert ce.getSBOTerm() == 290
    assert ce.getSBOTermID() == "SBO:0000290"
    cvterms = ce.getCVTerms()
    # check: is one cv term with 3 resources in bag
    assert len(cvterms) == 1
    assert cvterms[0].getNumResources() == 3

    cm = model.getCompartment('m')
    assert cm.getSBOTerm() == 290
    assert cm.getSBOTermID() == "SBO:0000290"
    cvterms = cm.getCVTerms()
    assert len(cvterms) == 1
    assert cvterms[0].getNumResources() == 3

    cc = model.getCompartment('c')
    assert cc.getSBOTerm() == 290
    assert cc.getSBOTermID() == "SBO:0000290"
    cvterms = cm.getCVTerms()
    assert len(cvterms) == 1
    assert cvterms[0].getNumResources() == 3

    # parameters
    for p in model.parameters:
        cvterms = p.getCVTerms()
        if re.match(r"^Km_\w+$", p.id):
            assert p.getSBOTerm() == 27
            assert p.getSBOTermID() == "SBO:0000027"
            assert len(cvterms) == 1

        if re.match(r"^Keq_\w+$", p.id):
            assert p.getSBOTerm() == 281
            assert p.getSBOTermID() == "SBO:0000281"
            assert len(cvterms) == 1

        if re.match(r"^Vmax_\w+$", p.id):
            assert p.getSBOTerm() == 186
            assert p.getSBOTermID() == "SBO:0000186"
            assert len(cvterms) == 1

    # species
    for s in model.species:
        cvterms = s.getCVTerms()
        if re.match(r"^\w{1}__[ABC]$", s.id):
            assert s.getSBOTerm() == 247
            assert s.getSBOTermID() == "SBO:0000247"
            assert len(cvterms) == 1

    # reactions
    for r in model.reactions:
        cvterms = r.getCVTerms()
        if re.match(r"^b\w{1}$", r.id):
            assert r.getSBOTerm() == 185
            assert r.getSBOTermID() == "SBO:0000185"
            assert len(cvterms) == 1

        if re.match(r"^v\w{1}$", r.id):
            assert r.getSBOTerm() == 176
            assert r.getSBOTermID() == "SBO:0000176"
            assert len(cvterms) == 1
def simulate(mixed_sbml, tend=10.0, step_size=0.1, debug=False):
    """
    Performs model simulation.

    The simulator figures out based on the SBO terms in the list of submodels, which
    simulation/modelling framework to use.
    The passing of information between FBA and SSA/ODE is based on the list of replacements.

    :param mixed_sbml: comp sbml model with multiple submodels
    :param tend: end time of the simulation
    :param step_size: step size for the integration, if None variable step size will be used
    :param debug: additional information
    :return: pandas solution data frame
    """
    ###############################
    # Process FBA assignment rules
    ###############################
    # Necessary to find the assignment rules in the top model
    # These cannot be set in an hybrid approach.
    doc = libsbml.readSBMLFromFile(mixed_sbml)
    model = doc.getModel()

    def _process_mixed_assignments(model):
        """
        Find the assignment rules which assign to a variable a reaction rate.
        """
        fba_rules = {}

        for rule in model.getListOfRules():
            if not rule.isAssignment():
                continue
            variable = rule.getVariable()
            formula = rule.getFormula()
            parameter = model.getParameter(variable)
            if not parameter:
                continue
            reaction = model.getReaction(formula)
            if not reaction:
                continue
            fba_rules[reaction.getId()] = parameter.getId()
        return fba_rules

    fba_rules = _process_mixed_assignments(model)
    print('FBA rules:', fba_rules)

    # remove the FBA assignment rules from the model, so they can be set via the simulator
    for variable in fba_rules.values():
        print(variable)
        model.removeRuleByVariable(variable)
    import tempfile
    mixed_sbml_cleaned = tempfile.NamedTemporaryFile("w", suffix=".xml")
    libsbml.writeSBMLToFile(doc, mixed_sbml_cleaned.name)
    # mixed_sbml_cleaned.close()


    ###########################
    # Load ODE model
    ###########################
    # the roadrunner ode file is the flattend comp file.
    # FBA subparts do not change change any of the kinetic subparts (only connections via replaced bounds
    # and fluxes).
    # Consequently the ode part can be solved as is, only the iterative update between ode and fba has
    # to be performed
    rr_comp = roadrunner.RoadRunner(mixed_sbml_cleaned.name)
    sel = ['time'] \
        + ["".join(["[", item, "]"]) for item in rr_comp.model.getBoundarySpeciesIds()] \
        + ["".join(["[", item, "]"]) for item in rr_comp.model.getFloatingSpeciesIds()] \
        + rr_comp.model.getReactionIds() + fba_rules.values()
    rr_comp.timeCourseSelections = sel
    rr_comp.reset()

    ###########################
    # Load FBA models
    ###########################
    # via the submodels information it is decided which submodels are belonging to which
    # modeling framework (SBOTerms on submodel)
    doc = libsbml.readSBMLFromFile(mixed_sbml)
    model_frameworks = comp.get_submodel_frameworks(doc)
    model = doc.getModel()

    # get top level reaction ids
    # top_level_rids = frozenset([reaction.getId() for reaction in model.getListOfReactions()])

    # assign submodels to FBA
    fba_models = {}
    for key, value in model_frameworks.iteritems():
        if value["sbo"] == 624:
            print('FBA model')
            # get SBML file
            modelRef = value["modelRef"]
            mdoc = doc.getPlugin("comp")
            emd = mdoc.getExternalModelDefinition(modelRef)
            source = emd.getSource()
            print(source)
            fba_models[key] = {'cobra': cobra.io.read_sbml_model(source),
                               'doc': libsbml.readSBMLFromFile(source)}
        elif value['sbo'] == 62:
            print('ODE model')
            # get the sbml file
            modelRef = value["modelRef"]
            mdoc = doc.getPlugin("comp")
            emd = mdoc.getExternalModelDefinition(modelRef)
            source = emd.getSource()
            print(source)
        else:
            raise Exception("Modelling framework not supported, or not annotated on submodel: ", sbo)

    # submodels handled by FBA
    print(fba_models)

    ###########################
    # Simulation
    ###########################
    all_results = []
    all_time = []
    result = None
    time = 0.0
    while time <= tend:
        if debug:
            print("-" * 80)
            print("Time: {}".format(time))

        # --------------------------------------
        # FBA
        # --------------------------------------
        # all fba submodels are simulated
        for fba_key, fba_info in fba_models.iteritems():
            cobra_model = fba_info['cobra']
            sbml_model = fba_info['doc'].getModel()

            # TODO: calculate once (not required in loop)
            # which parameters are upper or lower bounds
            from collections import defaultdict
            ub_parameters = defaultdict(list)
            lb_parameters = defaultdict(list)
            for r in sbml_model.getListOfReactions():
                mr = r.getPlugin("fbc")
                rid = r.getId()
                if mr.isSetUpperFluxBound():
                    ub_parameters[mr.getUpperFluxBound()].append(rid)
                if mr.isSetLowerFluxBound():
                    lb_parameters[mr.getLowerFluxBound()].append(rid)
            print(ub_parameters)
            print(lb_parameters)

            # search in global parameter replacements for replacements which replace the bounds
            # of reactions
            print("* set bounds *")
            for p in model.getListOfParameters():
                pid = p.getId()
                mp = p.getPlugin("comp")
                for rep_element in mp.getListOfReplacedElements():
                    # the submodel of the replacement belongs to the current model
                    if rep_element.getSubmodelRef() == fba_key:
                        # update upper and lower bounds
                        for rid in ub_parameters.get(pid, []):
                            print(rid, ': (upper) -> ', pid)
                            cobra_reaction = cobra_model.reactions.get_by_id(rid)
                            cobra_reaction.upper_bound = rr_comp[pid]
                        for rid in lb_parameters.get(pid, []):
                            print(rid, ': (lower) -> ', pid)
                            cobra_reaction = cobra_model.reactions.get_by_id(rid)
                            cobra_reaction.lower_bound = rr_comp[pid]

            # [2] optimize
            print("* optimize *")
            # TODO: start with last solution (speed improvement)
            cobra_model.optimize()

            # [3] set fluxes in ODE part
            print("* set fba fluxes in ode *")
            # based on replacements the fluxes are written in the kinetic part
            # set solution fluxes in parameters
            for (rid, flux) in cobra_model.solution.x_dict.iteritems():
                if rid in fba_rules:
                    rr_comp[fba_rules[rid]] = flux
                    print(rid, ':', fba_rules[rid], "=", flux)
                else:
                    print(rid, "no boundary flux")

            if debug:
                print_flux_bounds(cobra_model)
                print(cobra_model.solution.status)
                print(cobra_model.solution.x_dict)
                print("-" * 80)

        # --------------------------------------
        # ODE
        # --------------------------------------
        # With the updated fluxes from the FBA the kinetic part is
        # calculated:

        # simulate (1 step)
        if step_size:
            # constant step size
            result = rr_comp.simulate(0, end=step_size, steps=1)
        else:
            # variable step size
            result = rr_comp.simulate(0, steps=1, variableStep=True)

        # store results
        all_results.append(result[1])
        # set the fba fluxes in the model)
        # TODO: the fba fluxes are not set in the full kinetic result (shown as zero)
        #   these have to be set with the mapping between comp and flattened model
        all_time.append(time)

        # store simulation values & get time step
        delta_time = result['time'][1]
        time = time + delta_time

        if debug:
            print(result)

    # create result matrix
    df = pd.DataFrame(data=all_results, columns=result.colnames)
    df.time = all_time
    print(df)
    return df