Exemple #1
0
 def test_createMergeModels(self):
     rpsbml = rpSBML.rpSBML('test', None, os.path.abspath('../cache'))
     rpsbml.genericModel('RetroPath_heterologous_pathway', 'rp_model', compXref)
     for meta in set([i for step in steps for lr in ['left', 'right'] for i in step[lr]]):
         try:
             inchi = rp_inchi[meta]
         except KeyError:
             inchi = None
         try:
             smiles = rp_smiles[meta]
         except KeyError:
             smiles = None
         rpsbml.createSpecies(meta, chemXref, None, inchi, smiles, 'MNXC3', 0, '')
     rp_pathway = rpsbml.createPathway(path_id)
     #reactions
     step_id = 0
     for stepNum in range(len(steps)):
         rpsbml.createReaction('RP_'+str(stepNum), 'B_999999', 'B__999999', steps[stepNum], reaction_smiles[stepNum], reacXref, 'testRid', 0.0, None, rpsbml.hetero_group, None)
         step_id += 1
     #other model
     document = libsbml.readSBML(os.path.join(os.path.abspath('test_models'), 'bigg_iMM904.COBRA-sbml3.xml'))
     model = document.getModel()
     rpsbml.mergeModels(model)
     inModel = libsbml.readSBML(os.path.join(os.path.abspath('test_models'), 'test_mergeModels.sbml'))
     assert self.compareModels(inModel.getModel(), model)==True
  def test_WriteL3SBML_zip(self):
    file = []
    file.append("../../../examples/sample-models/from-spec/level-3/algebraicrules.xml")
    file.append("../../../examples/sample-models/from-spec/level-3/assignmentrules.xml")
    file.append("../../../examples/sample-models/from-spec/level-3/boundarycondition.xml")
    file.append("../../../examples/sample-models/from-spec/level-3/delay.xml")
    file.append("../../../examples/sample-models/from-spec/level-3/dimerization.xml")
    file.append("../../../examples/sample-models/from-spec/level-3/enzymekinetics.xml")
    file.append("../../../examples/sample-models/from-spec/level-3/events.xml")
    file.append("../../../examples/sample-models/from-spec/level-3/functiondef.xml")
    file.append("../../../examples/sample-models/from-spec/level-3/multicomp.xml")
    file.append("../../../examples/sample-models/from-spec/level-3/overdetermined.xml")
    file.append("../../../examples/sample-models/from-spec/level-3/twodimensional.xml")
    file.append("../../../examples/sample-models/from-spec/level-3/units.xml")

    zipfile = "test.xml.zip"
    for f in file:
      d = libsbml.readSBML(f)
      self.assert_( d != None )
      if not libsbml.SBMLWriter.hasZlib():
        self.assert_( libsbml.writeSBML(d,zipfile) == 0 )
        d = None
        continue
      result = libsbml.writeSBML(d,zipfile)
      self.assertEqual( 1, result )
      dg = libsbml.readSBML(zipfile)
      self.assert_( dg != None )
      self.assert_( ( dg.toSBML() != d.toSBML() ) == False )
      d = None
      dg = None
    pass
def getTimeCourse(iModel, iFile):
    # important paths
    BioModels_path = './BioModelsDatabase_models'
    xml_path = './sedml_models/' + iModel + '/sbml_models/' + iFile + '.xml'
    sedml_path = './sedml_models/' + iModel + '/' + iModel + '.sedml'
    sbml_path = './sedml_models/' + iModel + '/sbml_models/' + iFile + '.sbml'

    # get time curse depending on type of model
    if os.path.exists(BioModels_path + '/' + iModel):
        sim_start_time, sim_end_time, sim_num_time_points, y_bound = timePointsBioModels(iModel)
        xml_model = libsbml.readSBML(xml_path)
        model_name = xml_model.getModel().getName()
    else:
        sedml_file = libsedml.readSedML(sedml_path)
        sbml_file = libsbml.readSBML(sbml_path)
        model_name = sbml_file.getModel().getName()

        for iTask in range(0, sedml_file.getNumTasks()):
            all_tasks = sedml_file.getTask(iTask)
            tsk_Id = all_tasks.getId()
            task_name = all_tasks.getName()
            task_modRef = all_tasks.getModelReference()
            task_simReference = all_tasks.getSimulationReference()

            # time courses
            try:
                all_simulations = sedml_file.getSimulation(iTask)
                sim_Id = all_simulations.getId()
            except:  # need 'except' clause if more models have same time period
                if all_simulations == None:
                    all_simulations = sedml_file.getSimulation(0)
                    sim_Id = all_simulations.getId()
            try:
                while task_simReference != sim_Id:
                    iTask = iTask + 1
                    all_simulations = sedml_file.getSimulation(iTask)
                    sim_Id = all_simulations.getId()
            except:
                iTask = 0
                while task_simReference != sim_Id:
                    all_simulations = sedml_file.getSimulation(iTask)
                    sim_Id = all_simulations.getId()
                    iTask = iTask + 1

            sim_start_time = all_simulations.getOutputStartTime()
            sim_end_time = all_simulations.getOutputEndTime()
            sim_num_time_points = all_simulations.getNumberOfPoints()

            # replace 'sim_num_time_points' by default value 100 for trajectory comparison in the end
            sim_num_time_points = 100

    return model_name, sim_start_time, sim_end_time, sim_num_time_points
def _check_biomodels_model(
        sedml_model, sbml_path, model_name, model_year, model_info):
    # only one sbml file, a benchmark model on its own.
    sedml_path = ''
    sbml_model = (libsbml.readSBML(sbml_path)).getModel()
    n_species = len(sbml_model.getListOfSpecies())
    n_reactions = len(sbml_model.getListOfReactions())

    # get the simulation times and write them to csv file
    out_start, out_end, n_timepoints, _ = \
        timePointsBioModels(sedml_model)
    if out_start is None:
        # Tf the model is not found, timePointsBioModels issues a warning.
        # We want to treat this case as a failure
        return model_info

    model_info.append({
        'name': model_name,
        'year': model_year,
        'n_species': n_species,
        'n_reactions': n_reactions,
        'long_id': (model_name, model_year, n_species, n_reactions),
        'short_id': '',
        'sbml_path': sbml_path,
        'sedml_path': sedml_path,
        'regrouped_path': '',   # to be filled later
        'start_time': out_start,
        'end_time': out_end,
        'n_timepoints': n_timepoints,
        'sedml_task': '',
    })

    return model_info
Exemple #5
0
def get_submodel_copasi(submodel_path: str,
                        model_info: pd.DataFrame):
    """
    This function loads a copasi file, if the (relative) path to the folder
    with this Copasi model is provided.
    It extracts the respective sbml file from the list and returns it alongside
    with the model, if any postprecessing of the Copasi results is necessary
    """

    # load the amici model
    if str(submodel_path) in ('', 'nan', 'NaN'):
        return None, None
    copasi_file = os.path.join(DIR_MODELS, submodel_path)

    # if the amici import did not work, we don't want to consider this model
    if 'amici_path_final' in model_info.keys():
        model_row = model_info.loc[model_info['copasi_path_final'] == submodel_path]
    elif 'amici_path' in model_info.keys():
        model_row = model_info.loc[model_info['copasi_path'] == submodel_path]
    else:
        return None, None

    id = int(model_row.index.values)

    # import the sbml model
    sbml_path = os.path.join(DIR_MODELS, model_row.loc[id, 'regrouped_path'])
    sbml_model = (libsbml.readSBML(sbml_path)).getModel()

    return copasi_file, sbml_model
Exemple #6
0
def modelica_varnames(variables, amounts, concentrations, sbml):
    doc = readSBML(sbml)
    m = doc.getModel()
    varnames = list()
    for var in variables:
        o = m.getParameter(var)
        if o is not None:
            varnames.append('Params.elmt_{0}'.format(var))
            continue
        o = m.getCompartment(var)
        if o is not None:
            varnames.append("elmt_{0}.elmt_{0}".format(var))
            continue
        o = m.getSpecies(var)
        if o is not None:
            if var in amounts:
                varnames.append('elmt_{0}.elmt_{1}_amount'.format(
                    o.getCompartment(), var))
            if var in concentrations:
                varnames.append('elmt_{0}.elmt_{1}_conc'.format(
                    o.getCompartment(), var))
            continue
        o = m.getReaction(var)
        if o is not None:
            varnames.append('Reacs.elmt_{}'.format(var))
            continue
        for r in m.GetListOfReactions():
            if r.getReactant(var) or r.getProduct(var):
                varnames.append('Reacs.elmt_{}'.format(var))
    return varnames
Exemple #7
0
def load_sbml(filename):
    """
    Load a model from a SBML file.

    Parameters
    ----------
    filename : str
        The input SBML filename.

    Returns
    -------
    model : NetworkModel or ODENetworkModel
    y0 : dict
        Initial condition.
    volume : Real or Real3, optional
        A size of the simulation volume.

    """
    import libsbml

    document = libsbml.readSBML(filename)
    document.validateSBML()
    num_errors = (document.getNumErrors(libsbml.LIBSBML_SEV_ERROR)
                  + document.getNumErrors(libsbml.LIBSBML_SEV_FATAL))
    if num_errors > 0:
        messages = "The generated document is not valid."
        messages += " {} errors were found:\n".format(num_errors)
        for i in range(document.getNumErrors(libsbml.LIBSBML_SEV_ERROR)):
            err = document.getErrorWithSeverity(i, libsbml.LIBSBML_SEV_ERROR)
            messages += "{}: {}\n".format(err.getSeverityAsString(), err.getShortMessage())
        for i in range(document.getNumErrors(libsbml.LIBSBML_SEV_FATAL)):
            err = document.getErrorWithSeverity(i, libsbml.LIBSBML_SEV_FATAL)
            messages += "{}: {}\n".format(err.getSeverityAsString(), err.getShortMessage())
        raise RuntimeError(messages)
    return import_sbml(document)
Exemple #8
0
def check_sbml(filepath,
               name=None,
               log_errors=True,
               units_consistency=True,
               modeling_practice=True,
               internal_consistency=True):
    """ Checks the given SBML filepath or string.

    :param doc: SBMLDocument to check
    :param name: identifier or path for report
    :param units_consistency: boolean flag units consistency
    :param modeling_practice: boolean flag modeling practise
    :param internal_consistency: boolean flag internal consistency
    :param log_errors: boolean flag of errors should be logged
    :return: Nall, Nerr, Nwarn (number of all warnings/errors, errors and warnings)
    """
    if name is None:
        filepath = os.path.abspath(filepath)
        if len(filepath) < 100:
            name = filepath
        else:
            name = filepath[0:99] + '...'

    doc = libsbml.readSBML(filepath)
    return check_doc(doc,
                     name=name,
                     log_errors=log_errors,
                     units_consistency=units_consistency,
                     modeling_practice=modeling_practice,
                     internal_consistency=internal_consistency)
Exemple #9
0
def load_sbml(filename):
    """
    Load a model from a SBML file.

    Parameters
    ----------
    filename : str
        The input SBML filename.

    Returns
    -------
    model : NetworkModel
    y0 : dict
        Initial condition.
    volume : Real or Real3, optional
        A size of the simulation volume.

    """
    import libsbml

    document = libsbml.readSBML(filename)
    document.validateSBML()
    num_errors = (document.getNumErrors(libsbml.LIBSBML_SEV_ERROR)
                  + document.getNumErrors(libsbml.LIBSBML_SEV_FATAL))
    if num_errors > 0:
        messages = "The generated document is not valid."
        messages += " {} errors were found:\n".format(num_errors)
        for i in range(document.getNumErrors(libsbml.LIBSBML_SEV_ERROR)):
            err = document.getErrorWithSeverity(i, libsbml.LIBSBML_SEV_ERROR)
            messages += "{}: {}\n".format(err.getSeverityAsString(), err.getShortMessage())
        for i in range(document.getNumErrors(libsbml.LIBSBML_SEV_FATAL)):
            err = document.getErrorWithSeverity(i, libsbml.LIBSBML_SEV_FATAL)
            messages += "{}: {}\n".format(err.getSeverityAsString(), err.getShortMessage())
        raise RuntimeError(messages)
    return import_sbml(document)
Exemple #10
0
def read_sbml(mn_file):
    """
    Read a SBML file and yield ASP atoms
    """
    def make_reaction(reaction):
        yield f'reaction("{reaction.getId()}").'
        if reaction.getReversible() == True:
            yield f'reversible("{reaction.getId()}").'
        for reactant in reaction.getListOfReactants():
            yield f'reactant("{reactant.getSpecies()}","{reaction.getId()}").'
        for product in reaction.getListOfProducts():
            yield f'product("{product.getSpecies()}","{reaction.getId()}").'

    document = readSBML(mn_file)

    if document.getNumErrors() > 0:
        logger.critical("Encountered the following SBML errors:")
        logger.critical(document.printErrors())
        return 1

    # level = document.getLevel()
    # version = document.getVersion()

    model = document.getModel()

    for rxn in model.getListOfReactions():
        yield from make_reaction(rxn)
def main (args):
    """Usage: evaluateCustomMath formula [model containing values]
    """
    if len(args) < 2:
      print("Usage: evaluateCustomMath formula [model containing values]")
      return 1;

    formula = args[1];
    filename = None
    if (len(args) > 2):
        filename = args[2]

    math = libsbml.parseFormula(formula);
    if (math == None):
      print("Invalid formula, aborting.");
      return 1;

    doc = None;
    if filename != None:
      doc = libsbml.readSBML(filename);
      if doc.getNumErrors(libsbml.LIBSBML_SEV_ERROR) > 0:
        print("The models contains errors, please correct them before continuing.");
        doc.printErrors();
        return 1;
      # the following maps a list of ids to their corresponding model values
      # this makes it possible to evaluate expressions involving SIds. 
      libsbml.SBMLTransforms.mapComponentValues(doc.getModel());    
    else:
      # create dummy document
      doc = libsbml.SBMLDocument(3, 1);

    result = libsbml.SBMLTransforms.evaluateASTNode(math, doc.getModel());
    print("{0} = {1}".format(formula, result));
def main(args):
    """Usage: evaluateCustomMath formula [model containing values]
    """
    if len(args) < 2:
        print("Usage: evaluateCustomMath formula [model containing values]")
        return 1

    formula = args[1]
    filename = None
    if (len(args) > 2):
        filename = args[2]

    math = libsbml.parseFormula(formula)
    if (math == None):
        print("Invalid formula, aborting.")
        return 1

    doc = None
    if filename != None:
        doc = libsbml.readSBML(filename)
        if doc.getNumErrors(libsbml.LIBSBML_SEV_ERROR) > 0:
            print(
                "The models contains errors, please correct them before continuing."
            )
            doc.printErrors()
            return 1
        # the following maps a list of ids to their corresponding model values
        # this makes it possible to evaluate expressions involving SIds.
        libsbml.SBMLTransforms.mapComponentValues(doc.getModel())
    else:
        # create dummy document
        doc = libsbml.SBMLDocument(3, 1)

    result = libsbml.SBMLTransforms.evaluateASTNode(math, doc.getModel())
    print("{0} = {1}".format(formula, result))
 def test_read_l1v1_minimal(self):
   filename = "../../sbml/test/test-data/l1v1-minimal.xml"
   d = libsbml.readSBML(filename)
   if (d == None):
     pass    
   self.assert_( d.getLevel() == 1 )
   self.assert_( d.getVersion() == 1 )
   m = d.getModel()
   self.assert_( m.getNumCompartments() == 1 )
   c = m.getCompartment(0)
   self.assert_((  "x" == c.getName() ))
   self.assert_( m.getNumSpecies() == 1 )
   s = m.getSpecies(0)
   self.assert_((  "y"  == s.getName() ))
   self.assert_((  "x"  == s.getCompartment() ))
   self.assert_( s.getInitialAmount() == 1 )
   self.assert_( s.getBoundaryCondition() == False )
   self.assert_( m.getNumReactions() == 1 )
   r = m.getReaction(0)
   self.assert_((  "r" == r.getName() ))
   self.assert_( r.getReversible() != False )
   self.assert_( r.getFast() == False )
   self.assert_( r.getNumReactants() == 1 )
   self.assert_( r.getNumProducts() == 1 )
   sr = r.getReactant(0)
   self.assert_((  "y" == sr.getSpecies() ))
   self.assert_( sr.getStoichiometry() == 1 )
   self.assert_( sr.getDenominator() == 1 )
   sr = r.getProduct(0)
   self.assert_((  "y" == sr.getSpecies() ))
   self.assert_( sr.getStoichiometry() == 1 )
   self.assert_( sr.getDenominator() == 1 )
   _dummyList = [ d ]; _dummyList[:] = []; del _dummyList
   pass  
Exemple #14
0
def template_sync_species(apps, instance):
    """
    Task parses an SBML document, then creates MetaboliteSpecies and MetaboliteExchange records
    for every species and single-reactant reaction in the model.
    """
    doc = libsbml.readSBML(instance.sbml_file.file.file.name)
    model = doc.getModel()
    # filter to only those for the updated template
    MetaboliteSpecies = apps.get_model("main", "MetaboliteSpecies")
    MetaboliteExchange = apps.get_model("main", "MetaboliteExchange")
    species_qs = MetaboliteSpecies.objects.filter(sbml_template=instance)
    exchange_qs = MetaboliteExchange.objects.filter(sbml_template=instance)
    exist_species = set(species_qs.values_list("species", flat=True))
    exist_exchange = set(exchange_qs.values_list("exchange_name", flat=True))
    # creating any records not in the database
    for species in map(lambda s: s.getId(), model.getListOfSpecies()):
        if species not in exist_species:
            MetaboliteSpecies.objects.get_or_create(sbml_template=instance,
                                                    species=species)
        else:
            exist_species.discard(species)
    reactions = map(lambda r: (r.getId(), r.getListOfReactants()),
                    model.getListOfReactions())
    for reaction, reactants in reactions:
        if len(reactants) == 1 and reaction not in exist_exchange:
            MetaboliteExchange.objects.get_or_create(
                sbml_template=instance,
                exchange_name=reaction,
                reactant_name=reactants[0].getSpecies(),
            )
        else:
            exist_exchange.discard(reaction)
    # removing any records in the database not in the template document
    species_qs.filter(species__in=exist_species).delete()
    exchange_qs.filter(exchange_name__in=exist_exchange).delete()
Exemple #15
0
    def loadSBML( self, aSBMLDocument ):

        if type( aSBMLDocument ) == str:
            self.theSBMLDocument = libsbml.readSBML( aSBMLDocument )
        elif type( self.theSBMLDocument ) == file:
            self.theSBMLDocument = libsbml.readSBMLFromString( aSBMLDocument.read() )
        else:
            self.theSBMLDocument = aSBMLDocument
            
        if self.theSBMLDocument.getLevel() != 2:
            self.theSBMLDocument.setLevel( 2 )
            
        aXMLNamespaceList = self.theSBMLDocument.getNamespaces()
        anURI = aXMLNamespaceList.getURI( ECELL_XML_NAMESPACE_PREFIX )
        if anURI != ECELL_XML_NAMESPACE_URI:
            if anURI == '':
                aXMLNamespaceList.add( ECELL_XML_NAMESPACE_PREFIX, \
                                       ECELL_XML_NAMESPACE_URI )
            else:
                raise SBMLConvertError, 'Wrong URI [%s] is already assinged to xmlns:%s. Remove or correct it by yourself' % ( anURI, ECELL_XML_NAMESPACE_PREFIX )

        if self.theSBMLDocument.getNumFatals() > 0:
            fatalerrorList = []
            for i in range( self.theSBMLDocument.getNumFatals() ):
                fatalerrorList.append( self.theSBMLDocument.getFatal( i ).getMessage() )
                
            self.theSBMLDocument = None
            raise SBMLConvertError, \
                  'This SBML document is invalid:\n %s' \
                  % ( ', '.join( fatalerrorList ) )

        if not self.theSBMLDocument.getModel():
            self.theSBMLDocument.createModel()

        self.__createIdDict()
Exemple #16
0
 def test_writeSBML(self):
     rpsbml = rpSBML.rpSBML('test', None, os.path.abspath('../cache'))
     rpsbml.genericModel('RetroPath_heterologous_pathway', 'rp_model', compXref)
     rpsbml.modelName = 'test_writeSBML'
     rpsbml.writeSBML(os.path.abspath('test_models'))
     inModel = libsbml.readSBML(os.path.join(os.path.abspath('test_models'), 'test_writeSBML.sbml'))
     assert self.compareModels(inModel.getModel(), rpsbml.model)==True
Exemple #17
0
def _adapt_sbml_file(sbml_file):
    # create temporary filename for an adapted sbml file for Copasi
    temp = sbml_file.split('.')
    temp_file_name = temp[0] + '_deleteme.xml'

    # get the sbml model, adapt it for Copasi
    sbml_model = (libsbml.readSBML(sbml_file)).getModel()
    sbml_model_name = sbml_model.getName()
    if sbml_model_name == '':
        sbml_model_name = (sbml_file.split('.')[0]).split('/')[-1]
        sbml_model.setName(sbml_model_name)
    output_table = []
    for compartment in sbml_model.getListOfCompartments():
        # Copasi prioritizes species names over IDs
        # We have to remove them to user IDs as identifiers in Copasi
        compartment.unsetName()

    for species in sbml_model.getListOfSpecies():
        # Copasi prioritizes species names over IDs
        # We have to remove them to user IDs as identifiers in Copasi
        species.unsetMetaId()
        species.unsetName()
        output_table.append((species.getCompartment(), species.getId()))

    # save changed sbml files and the accompaniying sedml file
    libsbml.writeSBMLToFile(sbml_model.getSBMLDocument(), temp_file_name)
    return temp_file_name, sbml_model_name, output_table
def getSimTable(iModel, iFile):
    # important paths
    sbml_path = './sedml_models/' + iModel + '/sbml_models/' + iFile + '.sbml'
    biomodels_path = './sedml_models/' + iModel + '/sbml_models/' + iFile + '.xml'

    # check for type of model and open sbml/xml file
    if os.path.exists(sbml_path):
        sbml_file = libsbml.readSBML(sbml_path)
    elif os.path.exists(biomodels_path):
        sbml_file = libsbml.readSBML(biomodels_path)
    else:
        print('Something with the paths went wrong!')
        sys.exit()

    # get compartments
    num_comp = sbml_file.getModel().getNumCompartments()
    comp_and_type = []
    for iComp in range(0, num_comp):
        if not sbml_file.getModel().getCompartment(iComp).getName() == '':
            comp_and_type.append([sbml_file.getModel().getCompartment(iComp).getId(), sbml_file.getModel().getCompartment(iComp).getName()])
        else:
            comp_and_type.append([sbml_file.getModel().getCompartment(iComp).getId(), sbml_file.getModel().getCompartment(iComp).getId()])

    # get species that use one of the compartments above
    num_spec = sbml_file.getModel().getNumSpecies()
    spec_and_type = []
    for iSpec in range(0, num_spec):
        spec_comp = sbml_file.getModel().getSpecies(iSpec).getCompartment()
        for iComp in range(0, len(comp_and_type)):
            if spec_comp == comp_and_type[iComp][0]:
                if not sbml_file.getModel().getSpecies(iSpec).getName() == '':
                    spec_and_type.append([comp_and_type[iComp][1], sbml_file.getModel().getSpecies(iSpec).getName(), 'Concentration'])
                else:
                    spec_and_type.append([comp_and_type[iComp][1], sbml_file.getModel().getSpecies(iSpec).getId(), 'Concentration'])
    '''
    # get parameters that are not constant
    num_par = sbml_file.getModel().getNumParameters()
    par_and_type = []
    for iPar in range(0, num_par):
        par_constant = sbml_file.getModel().getParameter(iPar).getConstant()
        if par_constant == False:
            if not sbml_file.getModel().getParameter(iPar).getName() == '':
                par_and_type.append([sbml_file.getModel().getParameter(iPar).getName(), 'Value'])
            else:
                par_and_type.append([sbml_file.getModel().getParameter(iPar).getId(), 'Value'])
    '''
    return spec_and_type#, par_and_type
Exemple #19
0
def ParseSBMLFile(filePath):
    """
    Parameters
    ----------
    filePath : string
        File path of the SBML model to be parsed
		

    Returns
    -------
    ModelData
        An object containing the model's components and their properties.

    """
    doc = libsbml.readSBML(filePath)

    assert (doc.getNumErrors() == 0)

    model = doc.getModel()

    modelData = sbmltoodepy.dataclasses.ModelData()
    #    outputFile = open(outputPath, "w")

    #    outputFile.write("Parameters"+ "\n")
    for i in range(model.getNumParameters()):
        newParameter = ParseParameterAssignment(i, model.getParameter(i))
        modelData.parameters[newParameter.Id] = newParameter
#    outputFile.write("Compartments" + "\n")
    for i in range(model.getNumCompartments()):
        newCompartment = ParseCompartment(i, model.getCompartment(i))
        modelData.compartments[newCompartment.Id] = newCompartment
#    outputFile.write("Species"+ "\n")
    for i in range(model.getNumSpecies()):
        newSpecies = ParseSpecies(i, model.getSpecies(i))
        modelData.species[newSpecies.Id] = newSpecies
#    outputFile.write("Functions" + "\n")
    for i in range(model.getNumFunctionDefinitions()):
        newFunction = ParseFunction(i, model.getFunctionDefinition(i))
        modelData.functions[newFunction.Id] = newFunction
#    outputFile.write("Rules"+ "\n")
    for i in range(model.getNumRules()):
        newRule = ParseRule(i, model.getRule(i))
        if type(newRule) == sbmltoodepy.dataclasses.AssignmentRuleData:
            modelData.assignmentRules[newRule.Id] = newRule
        elif type(newRule) == sbmltoodepy.dataclasses.RateRuleData:
            modelData.rateRules[newRule.Id] = newRule


#    outputFile.write("Reactions"+ "\n")
    for i in range(model.getNumReactions()):
        newReaction = ParseReaction(i, model.getReaction(i))
        modelData.reactions[newReaction.Id] = newReaction

    for i in range(model.getNumInitialAssignments()):
        newAssignment = ParseInitialAssignment(i,
                                               model.getInitialAssignment(i))
        modelData.initialAssignments[newAssignment.Id] = newAssignment
    #print(model.getNumSpecies())
    return modelData
def _check_sedml_submodels(sedml_file, sbml_files,
                           model_name, model_year, model_info):
    """Checks which sbml models of one sedml group belong together"""
    sedml_path = os.path.abspath(sedml_file)
    sedml_doc = libsedml.readSedML(sedml_file)
    sedml_task_models = [task.getModelReference() for task in sedml_doc.getListOfTasks()]

    for sbml_file in sbml_files:
        # we want to find a simulation task for this SBML model
        # first, get the name of the file (identifier in SED-ML)
        sbml_path = os.path.abspath(sbml_file)
        sbml_file_short = (sbml_file.split('/')[-1]).split('.')[0]

        # Find the first task for this model (and warn if no task was found)
        try:
            task_number = sedml_task_models.index(sbml_file_short)
        except ValueError:
            print('SBML file not found in list of tasks: ' + sbml_file_short)
            return model_info

        # get the corresponding simulation setting
        current_sim = sedml_doc.getSimulation(sedml_doc.getTask(
            task_number).getSimulationReference())
        # remember simulation settings
        # out_start = current_sim.getOutputStartTime()
        out_end = current_sim.getOutputEndTime()
        # n_timepoints = current_sim.getNumberOfPoints()

        # get info about the SBML file
        sbml_model = libsbml.readSBML(sbml_file).getModel()
        if sbml_model is None:
            # check for SBML model
            print(f'No sbml model found for file {sbml_file}, '
                  f'in model name f{model_name}, '
                  f'model year {model_year}')
            return model_info
        n_species = len(sbml_model.getListOfSpecies())
        n_reactions = len(sbml_model.getListOfReactions())

        # add model information to the list
        model_info.append({
            'name': model_name,
            'year': model_year,
            'n_species': n_species,
            'n_reactions': n_reactions,
            'sbml_path': sbml_path,
            'sedml_path': sedml_path,
            'regrouped_path': '',   # to be filled later
            'start_time': 0,        # will only use t_end to have a rough timeframe
            'end_time': out_end,
            'n_timepoints': 101,    # will only use t_end to have a rough timeframe
            'long_id': (model_name, model_year, n_species, n_reactions),
            'short_id': '',
            'sedml_task': task_number,
        })

    return model_info
Exemple #21
0
 def test_createUnit(self):
     rpsbml = rpSBML.rpSBML('test', None, os.path.abspath('../cache'))
     rpsbml.createModel('RetroPath_heterologous_pathway', 'rp_model')
     unitDef = rpsbml.createUnitDefinition('mmol_per_gDW_per_hr')
     rpsbml.createUnit(unitDef, libsbml.UNIT_KIND_MOLE, 1, -3, 1)
     rpsbml.createUnit(unitDef, libsbml.UNIT_KIND_GRAM, 1, 0, 1)
     rpsbml.createUnit(unitDef, libsbml.UNIT_KIND_SECOND, 1, 0, 3600)
     inModel = libsbml.readSBML(os.path.join(os.path.abspath('test_models'), 'test_createUnit.sbml'))
     assert self.compareModels(inModel.getModel(), rpsbml.model)==True
Exemple #22
0
 def load( self, filepath ):
     self.filepath = filepath
     try:
         self.sbml = libsbml.readSBML( self.filepath )
     except Exception as e:
         logging.error( 'Failed to load %s' % self.filepath )
         logging.error( '\tError was %s' % e )
         quit( -1 )
     logging.info( "SBML is loaded" )
Exemple #23
0
 def parseSBML(self):
     if not hasattr(self, '_sbml_document'):
         # self.sbml_file = ForeignKey
         # self.sbml_file.file = FileField on Attachment
         # self.sbml_file.file.file = File object on FileField
         # self.sbml_file.file.file.name = path to file
         import libsbml
         self._sbml_document = libsbml.readSBML(self.sbml_file.file.file.name)
     return self._sbml_document
Exemple #24
0
 def __init__(self, path, rprefix='', rsuffix='', cprefix='', csuffix=''):
     super(SBMLParser, self).__init__()
     self.sbml_document = libsbml.readSBML(path)
     if self.sbml_document.getNumErrors() > 0:
         raise Exception, "libsbml function getNumErrors return value greater 0!"
     self.model = self.sbml_document.getModel()
     self.rprefix = rprefix
     self.rsuffix = rsuffix
     self.cprefix = cprefix
     self.csuffix = csuffix
Exemple #25
0
    def main( filename ):

        sbmlDocument = libsbml.readSBML( filename )
        aSBMLIdManager = sbmlsupport.SBMLIdManager( sbmlDocument )

        print aSBMLIdManager.compartmentDict
        print aSBMLIdManager.speciesDict
        print aSBMLIdManager.parameterDict
        print aSBMLIdManager.reactionDict
        print aSBMLIdManager.ruleDict
Exemple #26
0
    def main(filename):

        sbmlDocument = libsbml.readSBML(filename)
        aSBMLIdManager = sbmlsupport.SBMLIdManager(sbmlDocument)

        print aSBMLIdManager.compartmentDict
        print aSBMLIdManager.speciesDict
        print aSBMLIdManager.parameterDict
        print aSBMLIdManager.reactionDict
        print aSBMLIdManager.ruleDict
Exemple #27
0
def add_boundary_species(candidates):
    asansm_sbml = "fbc/iPAE1146_Amino_sugar_and_nucleotide_sugar_metabolism_fbc_squeezed.xml"
    pm_sbml = "fbc/iPAE1146_Pyrimidine_metabolism_fbc_squeezed.xml"
    lb_sbml = "fbc/iPAE1146_Lipopolysaccharide_biosynthesis_fbc_squeezed.xml"
    combined_sbml = "fbc/iPAE1146_Combined_Subsystems_fbc_squeezed.xml"

    asansm_libsbml_doc = libsbml.readSBML(asansm_sbml)
    asansm_libsbml = asansm_libsbml_doc.getModel()
    set_boundary_species(
        asansm_libsbml,
        candidates["Amino sugar and nucleotide sugar metabolism"])
    libsbml.writeSBMLToFile(
        asansm_libsbml_doc,
        "xml/iPAE1146_Amino_sugar_and_nucleotide_sugar_metabolism_fbc_squeezed_with_boundaries.xml"
    )

    pm_libsbml_doc = libsbml.readSBML(pm_sbml)
    pm_libsbml = pm_libsbml_doc.getModel()
    set_boundary_species(pm_libsbml, candidates["Pyrimidine metabolism"])
    libsbml.writeSBMLToFile(
        pm_libsbml_doc,
        "xml/iPAE1146_Pyrimidine_metabolism_fbc_squeezed_with_boundaries.xml")

    lb_libsbml_doc = libsbml.readSBML(lb_sbml)
    lb_libsbml = lb_libsbml_doc.getModel()
    set_boundary_species(lb_libsbml,
                         candidates["Lipopolysaccharide biosynthesis"])
    libsbml.writeSBMLToFile(
        lb_libsbml_doc,
        "xml/iPAE1146_Lipopolysaccharide_biosynthesis_fbc_squeezed_with_boundaries.xml"
    )

    combined_libsbml_doc = libsbml.readSBML(combined_sbml)
    combined_libsbml = combined_libsbml_doc.getModel()
    boundary_species = set()
    for candidate_list in candidates.values():
        for species in candidate_list:
            boundary_species.add(species)
    set_boundary_species(combined_libsbml, candidates["Combined"])
    libsbml.writeSBMLToFile(
        combined_libsbml_doc,
        "xml/iPAE1146_Combined_Subsystems_fbc_squeezed_with_boundaries.xml")
def _get_active_objective_from_fbc(sbml):
    """ Read the active objective from fbc model. """
    obj_coefs = {}
    doc = readSBML(sbml)
    if doc.getPlugin("fbc") != None:
        model_sbml = doc.getModel()
        mplugin = model_sbml.getPlugin("fbc")
        # read the active objective
        objective = mplugin.getActiveObjective()
        for fluxobj in objective.getListOfFluxObjectives():
            obj_coefs[fluxobj.getReaction()] = fluxobj.getCoefficient()
    return obj_coefs
Exemple #29
0
def read_gene_associations_from_fbc(sbml):
    """ Reading all the GeneAssociations from FBC. """
    doc = libsbml.readSBML(sbml)

    if doc.getPlugin("fbc") is not None:
        model_sbml = doc.getModel()
        mplugin = model_sbml.getPlugin("fbc")
        for ga in mplugin.getListOfGeneAssociations():

            ass = ga.getAssociation()
            infix = ass.toInfix()  # get the rule string for cobray
            print(infix, ':', ass.toSBML())
Exemple #30
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)
Exemple #31
0
def main(argc, argv):
    test_dir = os.path.join(argv[1], argv[2])
    out_dir = os.path.join(argv[3], argv[2])
    settings = os.path.join(argv[1], argv[2],
                            "{}-settings.txt".format(argv[2]))
    model = os.path.join(argv[1], argv[2], "{}-model.m".format(argv[2]))
    sbml = os.path.join(
        argv[1], argv[2],
        "{0}-sbml-l{1}v{2}.xml".format(argv[2], argv[4], argv[5]))

    print(test_dir, sbml, out_dir)

    doc = readSBML(sbml)
    m = doc.getModel()
    modelica_id = m.getIdAttribute()

    with open(model, 'r') as fp:
        mcont = fp.read().splitlines()
    for line in mcont:
        if line.startswith('testType'):
            if 'TimeCourse' not in line:
                exit(1)
        if line.startswith('packagesPresent'):
            if line.replace(" ", "") != 'packagesPresent:':
                exit(1)
    with open(settings, 'r') as fp:
        scont = fp.read().splitlines()
    start = scont[0].replace(" ", "").split(":")[1]
    horizon = scont[1].replace(" ", "").split(":")[1]
    step_size = str(
        float(horizon) / float(scont[2].replace(" ", "").split(":")[1]))
    variables = scont[3].replace(" ", "").split(":")[1].split(",")
    if type(variables) is str:
        variables = [variables]
    amnt = scont[6].replace(" ", "").split(":")[1].split(",")
    if type(amnt) is str:
        amnt = [amnt]
    conc = scont[7].replace(" ", "").split(":")[1].split(",")
    if type(conc) is str:
        conc = [conc]

    print(
        os.system('{0} {1} {2} --log {3}'.format(sbml2modelica, sbml, out_dir,
                                                 log_file)))
    compile_modelica(out_dir, modelica_id, start, horizon, step_size)
    simulate(out_dir, modelica_id)
    #print modelica_varnames(variables, amnt, conc, sbml)
    save_results(out_dir, modelica_id, argv[2], variables,
                 modelica_varnames(variables, amnt, conc, sbml),
                 float(step_size))
Exemple #32
0
    def __init__(self, sbml, reaction_index, species_index, enzymes_index,
                 substrateIndexs, state):
        '''
            In the end the full calculation has to be possible solely 
            based on the given SBML.
        '''
        # necessary to have the species/reaction/enzymes to index mapping for lookup
        # and mapping between ids and indices
        # this will later be created from the sbml
        self.r_index = reaction_index
        self.s_index = species_index
        self.e_index = enzymes_index
        self.substrateIndexs = substrateIndexs
        self.s_acp_index = 570
        # handle Acetyl-Carrier Protein

        doc = readSBML(sbml)
        self.model = doc.getModel()
        self.protein_reactions = self.find_protein_reactions()

        # set reused attributes from state dict
        # the complete information should be parsed from the SBML
        # TODO: step by step reduce the state dependency.
        for key in [
                # in SBML
                'fbaReactionCatalysisMatrix',
                'fbaReactionBounds',
                'fbaEnzymeBounds',
                # get the right reactions (TODO: code type in SBML)
                'fbaReactionIndexs_metabolicConversion',
                'fbaReactionIndexs_metaboliteInternalExchange',
                'fbaReactionIndexs_biomassExchange',
                'fbaReactionIndexs_biomassProduction',
                'fbaReactionIndexs_metaboliteExternalExchange',
                'fbaReactionIndexs_metaboliteInternalLimitedExchange',
                'compartmentIndexs_cytosol',
                'compartmentIndexs_extracellular',

                # substrate for reactions (in SBML)
                'substrateIndexs_externalExchangedMetabolites',
                'substrateIndexs_internalExchangedLimitedMetabolites',
                'substrateIndexs_limitableProteins',
        ]:
            setattr(self, key, state[key])

        # self.Nr = self.fbaReactionBounds.shape[0]  # 504 reactions (lower and upper for every necessary)
        self.Nr = len(self.model.getListOfReactions())
        # TODO: set as parameter and read
        self.stepSizeSec = 1
Exemple #33
0
def main(args):
    """Usage: replaceOneFD filename functionDefinitionId reactionId outfile
    """
    if (len(args) != 5):
        print(
            "Usage: replaceOneFD filename functionDefinitionId reactionId outfile"
        )
        return 1

    filename = args[1]
    outFile = args[4]
    functionDefinitionId = args[2]
    reactionId = args[3]
    document = libsbml.readSBML(filename)

    if (document.getNumErrors(libsbml.LIBSBML_SEV_ERROR) > 0):
        print(
            "The models contains errors, please correct them before continuing."
        )
        document.printErrors()
        return 1

    model = document.getModel()
    functionDefinition = model.getFunctionDefinition(functionDefinitionId)
    if (functionDefinition == None):
        print()
        print("No functiondefinition with the given id can be found.")
        return 1

    reaction = model.getReaction(reactionId)
    if (reaction == None):
        print()
        print("No reaction with the given id can be found.")
        return 1

    if (reaction.isSetKineticLaw() == False
            or reaction.getKineticLaw().isSetMath() == False):
        print()
        print("The reaction has no math set. ")
        return 1

    # Until here it was all setup, all we needed was an ASTNode, in which we wanted to
    # replace calls to a function definition, with the function definitions content.
    #
    libsbml.SBMLTransforms.replaceFD(reaction.getKineticLaw().getMath(),
                                     functionDefinition)

    # finally write to file
    libsbml.writeSBML(document, outFile)
Exemple #34
0
 def test_createSpecies(self):
     rpsbml = rpSBML.rpSBML('test', None, os.path.abspath('../cache'))
     rpsbml.genericModel('RetroPath_heterologous_pathway', 'rp_model', compXref)
     for meta in set([i for step in steps for lr in ['left', 'right'] for i in step[lr]]):
         try:
             inchi = rp_inchi[meta]
         except KeyError:
             inchi = None
         try:
             smiles = rp_smiles[meta]
         except KeyError:
             smiles = None
         rpsbml.createSpecies(meta, chemXref, None, inchi, smiles, 'MNXC3', 0, '')
     inModel = libsbml.readSBML(os.path.join(os.path.abspath('test_models'), 'test_createSpecies.sbml'))
     assert self.compareModels(inModel.getModel(), rpsbml.model)==True
Exemple #35
0
    def init(self):
        assert self.sbml_file_path, "SBML file not set"
        self.document = readSBML(self.sbml_file_path);
        if os.path.exists(self.filter_filename):
            with open(self.filter_filename, "r") as filter_file:
                self.filter_list = [x.split("\t")[0].strip() for x in filter_file.read().lower().splitlines()]
        else:
            self.filter_list = []

        # errors = self.document.getNumErrors();
        # if (errors > 0):
        #    _log.error(str(errors))
        #    raise ("Encountered the following SBML errors:" + str(errors))

        self.model = self.document.getModel();
Exemple #36
0
    def test_sbml_export_conversion(self):
        try:
            import libsbml
        except ImportError:
            return

        tmp = tempfile.NamedTemporaryFile(delete=False)
        model = create_robust_model()
        path = export_SBML(model, filename=tmp.name)
        document = libsbml.readSBML(path)
        if document.getNumErrors() > 0:
            error_id = document.getError(0).getErrorId()
            file_errors = [
                libsbml.XMLFileUnreadable, libsbml.XMLFileOperationError
            ]
            assert error_id not in file_errors
def check_sbml(filepath, name=None, ucheck=True, show_errors=True):
    """ Checks the given SBML file path or String for validation errors.

    :param filepath: path of SBML file
    :param ucheck: boolen if unit checks should be performed
    :return: number of errors
    """
    # FIXME: check if this is also working for SBML strings
    if name is None:
        if len(filepath) < 100:
            name = filepath
        else:
            name = filepath[0:99] + '...'

    doc = libsbml.readSBML(filepath)
    return check_doc(doc, name=name, ucheck=ucheck, show_errors=show_errors)
def annotate_sbml_file(f_sbml, f_annotations, f_sbml_annotated):
    """
    Annotate a given SBML file with the provided annotations.

    :param f_sbml: SBML to annotation
    :param f_annotations: csv file with annotations
    :param f_sbml_annotated: annotated file
    """
    # read SBML model
    doc = libsbml.readSBML(f_sbml)

    # read annotations
    annotations = ModelAnnotator.annotations_from_file(f_annotations)
    doc = annotate_sbml_doc(doc, annotations)

    # Save
    libsbml.writeSBMLToFile(doc, f_sbml_annotated)
Exemple #39
0
    def loadSBML(self, aSBMLDocument):

        if type(aSBMLDocument) == str:
            self.theSBMLDocument = libsbml.readSBML(aSBMLDocument)
        elif type(aSBMLDocument) == file:
            self.theSBMLDocument = libsbml.readSBMLFromString(aSBMLDocument.read())
        else:
            self.theSBMLDocument = aSBMLDocument

        if self.theSBMLDocument.getLevel() != 2:
            self.theSBMLDocument.setLevel(2)

        if self.theSBMLDocument.getNumFatals() > 0:
            fatalerrorList = []
            for i in range(self.theSBMLDocument.getNumFatals()):
                fatalerrorList.append(self.theSBMLDocument.getFatal(i))

            self.theSBMLDocument = None
            raise SBMLConvertError, "This SBML document is invalid: %s" % (", ".join(fatalerrorList))
def main (args):
    """Usage: replaceOneFD filename functionDefinitionId reactionId outfile
    """
    if (len(args) != 5):
      print("Usage: replaceOneFD filename functionDefinitionId reactionId outfile");
      return 1;

    filename = args[1];
    outFile = args[4];
    functionDefinitionId = args[2];
    reactionId = args[3];
    document = libsbml.readSBML(filename);

    if (document.getNumErrors(libsbml.LIBSBML_SEV_ERROR)  > 0):
      print("The models contains errors, please correct them before continuing.");
      document.printErrors();
      return 1;

    model = document.getModel();
    functionDefinition = model.getFunctionDefinition(functionDefinitionId);
    if (functionDefinition == None):
      print();
      print("No functiondefinition with the given id can be found.");
      return 1;

    reaction = model.getReaction(reactionId);
    if (reaction == None):
      print();
      print("No reaction with the given id can be found.");
      return 1;

    if (reaction.isSetKineticLaw() == False or reaction.getKineticLaw().isSetMath()== False):
      print();
      print("The reaction has no math set. ");
      return 1;

    # Until here it was all setup, all we needed was an ASTNode, in which we wanted to 
    # replace calls to a function definition, with the function definitions content. 
    #
    libsbml.SBMLTransforms.replaceFD(reaction.getKineticLaw().getMath(), functionDefinition);

    # finally write to file
    libsbml.writeSBML(document, outFile);
Exemple #41
0
def load_cobra_model(path, notifications):
    """Load a COBRA model with meta information from an SBML document."""
    doc = libsbml.readSBML(path)
    fbc = doc.getPlugin("fbc")
    sbml_ver = doc.getLevel(), doc.getVersion(), fbc if fbc is None else \
        fbc.getVersion()
    with catch_warnings(record=True) as warnings:
        simplefilter("always")
        try:
            model = read_sbml_model(path)
        except Exception as err:
            notifications['errors'].append(str(err))
            model = None
            validate = True
        else:
            validate = False
        notifications['warnings'].extend([str(w.message) for w in warnings])
    if validate:
        run_sbml_validation(doc, notifications)
    return model, sbml_ver
def main (args):
  """Usage: addCustomValidator filename
  """
  if len(args) != 2:
    print(main.__doc__)
    sys.exit(1)

  # read the file name
  document = libsbml.readSBML(args[1]);

  # add a custom validator
  document.addValidator(MyCustomValidator());
  
  # check consistency like before
  numErrors = document.checkConsistency();

  # print errors and warnings
  document.printErrors();

  # return number of errors
  return numErrors;
def main (args):
    """Usage: printNotes filename
    """
    if (len(args) != 3):
      print("Usage: inlineInitialAssignments filename outFile");
      return 1;

    filename = args[1];
    outFile = args[2];

    document = libsbml.readSBML(filename);

    if (document.getNumErrors(libsbml.LIBSBML_SEV_ERROR) > 0):
      print("The models contains errors, please correct them before continuing.");
      document.printErrors();
      return 1;

    model = document.getModel();

    libsbml.SBMLTransforms.expandInitialAssignments(model);

    libsbml.writeSBML(document, outFile);
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()
def to_SBML_l2v1(from_name, to_name):
    """
    Convert an SBML file to level 2, version 1 using lisbml.

    from_name  Name of file to read SBML from.
    to_name    File to output SBML to.
    """
    doc = libsbml.readSBML(os.path.abspath(from_name))
    if isinstance(doc, int):
        logger.critical('Fatal Errors reading SBML from file %s!' % from_name)
        _print_sbml_fatals(doc)
    errors = doc.setLevel(2)
    if errors:
        logger.critical('Fatal Errors converting %f to level 2!' % from_name)
        _print_sbml_fatals(doc)
    errors = doc.setVersion(1)
    if errors:
        logger.critical('Fatal Errors converting %f to level 2, version 1!'
                        % from_name)
        _print_sbml_fatals(doc)
    success = libsbml.writeSBML(doc, to_name)
    if not success:
        logger.critical('Error writing to %s' % to_name)
  def validate(self, file):
    if not os.path.exists(file):
      print("[Error] %s : No such file." % (infile))
      self.numinvalid += 1
      return

    start    = time.time()
    sbmlDoc  = libsbml.readSBML(file)
    stop     = time.time()
    timeRead = (stop - start)*1000
    errors   = sbmlDoc.getNumErrors()
    
    seriousErrors = False

    numReadErr  = 0
    numReadWarn = 0
    errMsgRead  = ""

    if errors > 0:
      
      for i in range(errors):
        severity = sbmlDoc.getError(i).getSeverity()
        if (severity == libsbml.LIBSBML_SEV_ERROR) or (severity == libsbml.LIBSBML_SEV_FATAL):
          seriousErrors = True
          numReadErr += 1
        else:
          numReadWarn += 1

        errMsgRead = sbmlDoc.getErrorLog().toString()

    # If serious errors are encountered while reading an SBML document, it
    # does not make sense to go on and do full consistency checking because
    # the model may be nonsense in the first place.

    numCCErr  = 0
    numCCWarn = 0
    errMsgCC  = ""
    skipCC    = False;
    timeCC    = 0.0

    if seriousErrors:
      skipCC = True;
      errMsgRead += "Further consistency checking and validation aborted."
      self.numinvalid += 1;    
    else:
      sbmlDoc.setConsistencyChecks(libsbml.LIBSBML_CAT_UNITS_CONSISTENCY, self.ucheck)
      start    = time.time()
      failures = sbmlDoc.checkConsistency()
      stop     = time.time()
      timeCC   = (stop - start)*1000
  
 
      if failures > 0:

        isinvalid = False;
        for i in range(failures):
          severity = sbmlDoc.getError(i).getSeverity()
          if (severity == libsbml.LIBSBML_SEV_ERROR) or (severity == libsbml.LIBSBML_SEV_FATAL):
            numCCErr += 1
            isinvalid = True;
          else:
            numCCWarn += 1

        if isinvalid:
          self.numinvalid += 1;    

        errMsgCC = sbmlDoc.getErrorLog().toString()

    #
    # print results
    #
        
    print("                 filename : %s" % (file))
    print("         file size (byte) : %d" % (os.path.getsize(file)))
    print("           read time (ms) : %f" % (timeRead))

    if not skipCC :
      print( "        c-check time (ms) : %f" % (timeCC))
    else:
      print( "        c-check time (ms) : skipped")

    print( "      validation error(s) : %d" % (numReadErr  + numCCErr))
    if not skipCC :
      print( "    (consistency error(s)): %d" % (numCCErr))
    else:
      print( "    (consistency error(s)): skipped")

    print( "    validation warning(s) : %d" % (numReadWarn + numCCWarn))
    if not skipCC :
      print( "  (consistency warning(s)): %d" % (numCCWarn))
    else:
      print( "  (consistency warning(s)): skipped")

    if errMsgRead or errMsgCC: 
      print()
      print( "===== validation error/warning messages =====\n")
      if errMsgRead : 
        print( errMsgRead)
      if errMsgCC : 
        print( "*** consistency check ***\n")
        print( errMsgCC)
Exemple #47
0
def _writeSBMLToDBModel(conn, database_path, sbml_input_path, use_species_name_attribute, print_warnings):
    c = conn.cursor()
    # read file
    if not os.path.exists(sbml_input_path):
        raise Exception("[Error] {0} : no such file.\n".format(sbml_input_path))
    # try to parse SBML document
    try:
        document = libsbml.readSBML(sbml_input_path)
    except libsbml.SBMLError as e:
        raise Exception("[Error] writeSBMLToDBModel; {0} : File not readable by method libsbml.readSBML(), aborting model import.\n {1}".format(sbml_input_path, e.value))
    # check SBML level
    if not (document.getLevel() == 3 and document.getVersion() == 1) and print_warnings:
        print("[Warning] writeSBMLToDBModel; {0} : SBML file has level {0}.{1}. This tool was written for SBML Level 3.1.\n".format(document.getLevel(), document.getVersion()))
    # check if qualitative model
    if not document.getPkgRequired("qual") and print_warnings:
        print("[Warning] writeSBMLToDBModel; {0} : \"qual\"-package is not set as required for this SBML file.\n".format(sbml_input_path))
    # check model consistency (document.checkConsistency() is called automatically by libsbml.readSBML)
    errors = document.getNumErrors()
    seriousErrors = False
    if errors > 0:
        for i in range(errors):
            severity = document.getError(i).getSeverity()
            if (severity == libsbml.LIBSBML_SEV_ERROR) or (severity == libsbml.LIBSBML_SEV_FATAL):
                seriousErrors = True
        if seriousErrors:
            raise Exception("[Error] writeSBMLToDBModel; {0} : SBML file invalid or inconsistant (fatal errors), aborting model import.\n Error Log from libSBML:\n{1}".format(sbml_input_path, document.getErrorLog().toString()))
        elif print_warnings:
            print("[Warning] writeSBMLToDBModel; {0} : SBML file inconsistancies (non-fatal errors).\n Error Log from libSBML:\n{1}".format(sbml_input_path, document.getErrorLog().toString()))

    # create a model object
    model = document.getModel()
    # get a QualModelPlugin object plugged into the model object (enables qualSBML interface).
    mplugin = model.getPlugin("qual")


    # Selection and checks of species names to be used for the TREMPPI database:
    # Since the SBML exporter tool (db2sbmp.py) does not work with component names with underscores "_" and the QualitativeSpecies:Name attribute is not guaranteed to be unique,
    # the existance and uniqueness of the names to be used internally by TREMPPI has to be checked.
    species_id_name_dict = {}   # dictionary with {SBML QS:Id:(Name for TREMPPI)} pairs for database inserts. Unmodified Id is still used by the function internally, since SBML FunctionTerms use QS:Id as species identifiers.
    species_modNames = []       # Names (SBML QS:Name or SBML QS:Id) without underscores
    # for all qualitativeSpecies
    for qs in mplugin.getListOfQualitativeSpecies():
        # if name attribute should be used, remove name underscores and fill Id:name dictionary
        if use_species_name_attribute and qs.isSetName():
            species_modNames.append(re.sub('_+', '', qs.getName()))
            species_id_name_dict.update({qs.getId():re.sub('_+', '', qs.getName())})
        # if names should be used but are not all set, throw an exception
        elif use_species_name_attribute:
            raise Exception("[Error] writeSBMLToDBModel; {0} : SBML Qualitative species name attributes are not set for all species, aborting model import.\n\tTry using species Ids instead by setting use_species_name_attributes=False.".format(sbml_input_path))
        # if Ids should be used, remove Id underscores and fill Id:(Id without underscores) dictionary
        else:
            species_modNames.append(re.sub('_+', '', qs.getId()))
            species_id_name_dict.update({qs.getId():re.sub('_+', '', qs.getId())})
    # if selected names are not unique, throw an exception
    if use_species_name_attribute and len(set(species_modNames)) != len(species_modNames):
        raise Exception("[Error] writeSBMLToDBModel; {0} : SBML Qualitative species name attributes are not unique without underscores, aborting model import.\n\tTry using species Ids instead by setting use_species_name_attributes=False.".format(sbml_input_path))
    elif len(set(species_modNames)) != len(species_modNames):
        raise Exception("[Error] writeSBMLToDBModel; {0} : SBML Qualitative species Id attributes are not unique without underscores, aborting model import.\n\tTry using species names instead by setting use_species_name_attributes=True.".format(sbml_input_path))

    # Check if maximum activity level is set for each species in SBML. If not, a boolean model is assumed.
    # Also fill two dictionaries with MaxActivity by Name and Id
    MA_is_set = True
    species_Id_maxActivity_dict = {}        # used by function computeThresholds
    species_Name_maxActivity_dict = {}      # used to order Name - MaxActivity pairs by Name (necessary if Id attributes are not alphabetically ordered or the qual. species name attribute is used)
    for qs in mplugin.getListOfQualitativeSpecies():
        # Use Name or Id as component name
        if use_species_name_attribute:
            Name = re.sub('_+', '', qs.getName())
        else:
            Name = re.sub('_+', '', qs.getId())
        # Use maxLevel or 1 as MaxActivity
        if qs.isSetMaxLevel():
            MaxActivity = qs.getMaxLevel()
        else:
            MaxActivity = 1
            MA_is_set = False
        species_Id_maxActivity_dict.update({qs.getId():MaxActivity})
        species_Name_maxActivity_dict.update({Name:MaxActivity})

    if not MA_is_set and print_warnings:
        print("[Warning] writeSBMLToDBModel; {0} : Maximum activity level not set in SBML file for at least one species. Assuming max. level = 1.\n".format(sbml_input_path))

    # Table Components
    c.execute('CREATE TABLE Components (Name TEXT, MaxActivity INTEGER)')
    # fill table Components in alphabetical order
    for Name in sorted(species_Name_maxActivity_dict.keys()):
        c.execute('INSERT INTO Components VALUES (?,?)', (Name, species_Name_maxActivity_dict[Name]))

    # Create temporary table Regulations, needs to be ordered later.
    c.execute('CREATE TABLE TmpRegulations (Source TEXT, Target TEXT, Threshold INTEGER)')

    # Fill table Regulations and extract regulatory contexts and target values from qualSBML transitions
    input_transition_effect_is_OK = True    # qualitative models should have specific input and output transition effect values
    output_transition_effect_is_OK = True
    context_list = []       # list for regulatory context string representations (e.g. 'K_raf_01')
    target_value_list = []  # list for corresponding context target values
    # for each qualSBML transition t:
    for t in mplugin.getListOfTransitions():

        # sources and targets of this transition (2 lists of RefID strings == Qalitative species names == TREMPPI component names)
        target_list = []
        source_list = []
        target_name_list = []
        source_name_list = []

        # get targets for table Regulations, order by target name
        for output in t.getListOfOutputs():
            target_list.append(output.getQualitativeSpecies())  # returns RefID (Qual. species Id)
            if use_species_name_attribute:
                target_name_list.append(species_id_name_dict[output.getQualitativeSpecies()])
            else:
                target_name_list.append(re.sub('_+', '', output.getQualitativeSpecies()))
            if output.getTransitionEffect() != 1:               # logical/multivalued models should have "assignmentLevel" == 1 (see qualSBML doc.)
                output_transition_effect_is_OK = False
        # order target list by internal TREMPPI names
        target_list = [target for target_name, target in sorted(zip(target_name_list, target_list))]

        # get sources for table Regulations, order by source name
        for input in t.getListOfInputs():
            source_list.append(input.getQualitativeSpecies())   # returns RefID (Qual. species Id)
            if use_species_name_attribute:
                source_name_list.append(species_id_name_dict[input.getQualitativeSpecies()])
            else:
                source_name_list.append(re.sub('_+', '', input.getQualitativeSpecies()))
            if input.getTransitionEffect() != 0:                # logical/multivalued models should have "none" == 0 (see qualSBML doc.)
                input_transition_effect_is_OK = False
        # order source list by internal TREMPPI names
        source_list = [source for source_name, source in sorted(zip(source_name_list, source_list))]

        # dictionary for storage of thresholds for each source species in this transition
        source_threshold_dict = {s:[] for s in source_list}     # e.g. {raf:[1,3], rafB:[1]}

        # find thresholds of sources for the TREMPPI regulations which are encoded in this qualSBML transition's function terms
        for f in t.getListOfFunctionTerms():
            # get the ASTNode tree of the SBML mathML definition of the function term
            # getMath() returns the top ASTNode of the tree
            math_AST = f.getMath()
            try:
                # source_threshold_dict is progressively filled/updated with information from each SBML FunctionTerm element
                computeThresholds(math_AST, source_threshold_dict, species_Id_maxActivity_dict)
            except ParseASTError as e:
                raise Exception("[Error] writeSBMLToDBModel;  {0} : Couldn't compute Thresholds for FunctionTerm of target {1} (SBML document, line {2}). Aborting model import. \n{3}".format(sbml_input_path, target_list[0], f.getLine(), e.value))

        # fill table TmpRegulations with regulations from this libsbml.Transition
        for target in target_list:
            for source in source_list:
                for threshold in source_threshold_dict[source]:
                    c.execute('INSERT INTO TmpRegulations VALUES (?,?,?)', (species_id_name_dict[source], species_id_name_dict[target], threshold))

        # create regulatory context definitions and evaluate libsbml.FunctionTerm math for context threshold states
        for target in target_list:
            # build a list of lists, where each sublist contains 0 and all thresholds for one input/source species
            thresholds_list_with_lower_zeros = [[0] + source_threshold_dict[s] for s in source_list]
            # create a list of all possible source threshold state combinations for this transition
            # e.g. CompA thresholds = [1], CompB thresholds = [1,2] -> context_threshold_states = [ [0,0], [0,1], [0,2], [1,0], [1,1], [1,2] ]
            context_threshold_states = list(itertools.product(*thresholds_list_with_lower_zeros))
            # for each context threshold state
            for cts in context_threshold_states:
                # get the target name to be used for this TREMPPI context definition (name attribute or Id without underscores)
                target_db_name = species_id_name_dict[target]
                # build the TREMPPI regulatory context definition (e.g. K_Raf_01) and append to context list
                context = 'K_{0}_{1}'.format(target_db_name, ''.join([str(t) for t in cts]))
                context_list.append(context)
                # get the target value for this context:
                # initialize the target value with the libsbml.Transition.DefaultTerm resultLevel
                target_value = t.getDefaultTerm().getResultLevel()
                # create a dictionary with pairs source:(source threshold state) for this context threshold state (cts)
                source_ts_dict = {source:threshold_state for (source, threshold_state) in zip(source_list, cts)}
                # Call evaluateContext for each FunctionTerm until a function evaluates to true for this context or all FunctionTerms have been evaluated.
                # If a FunctionTerm evaluates to true, use its result level as the target value for this context.
                # If none evaluates to true, keep the DefaultTerm result level as the target value.
                for ft in t.getListOfFunctionTerms():
                    try:
                        if evaluateContext(source_ts_dict, ft.getMath()):
                            target_value = ft.getResultLevel()
                            break
                    except ParseASTError as e:
                        raise Exception("[Error] writeSBMLToDBModel; {0} : Couldn't evaluate context for FunctionTerm of target {1}. \n{2}".format(sbml_input_path, target_list[0], e.value))
                # store the target values in order of regulatory contexts
                target_value_list.append(target_value)

    # warn if transition effect attributes were set to unexpected values
    if not output_transition_effect_is_OK and print_warnings:
        print("[Warning] writeSBMLToDBModel; {0} : At least one Transition output species has the transitionEffect attribute set to 'production' (0). Should be 'assignment level' (1) for logical/multi-valued models.\n".format(sbml_input_path))

    if not input_transition_effect_is_OK and print_warnings:
        print("[Warning] writeSBMLToDBModel; {0} : At least one Transition input species has the transitionEffect attribute set to 'consumption' (1). Should be 'none' (0) for logical/multi-valued models.\n".format(sbml_input_path))

    # Create final table Regulations, ordered by Target(1), Source(2), Threshold(3) and discard temporary table
    c.execute('CREATE TABLE Regulations (Source TEXT, Target TEXT, Threshold INTEGER)')
    c.execute('INSERT INTO Regulations SELECT * FROM TmpRegulations ORDER BY Target, Source, Threshold')
    c.execute('DROP TABLE TmpRegulations')

    # Table Parametrizations
    # build string for definition of column names (context names)
    column_def_string = ' INTEGER, '.join(sorted(context_list)) + ' INTEGER'
    # build string for context target values, ordered by context names
    target_value_string = ', '.join([str(t) for c, t in sorted(zip(context_list, target_value_list))])
    # create table and insert target values
    c.execute('CREATE TABLE Parametrizations ({0})'.format(column_def_string))
    c.execute('INSERT INTO Parametrizations VALUES ({0})'.format(target_value_string))
    # commit database changes
    conn.commit()

    #end writeSBMLToDBModel



## Example models

# SBML to DB import example 1: Cortical Area Development
#writeSBMLToDBModel("./data/databases/modelDB.sqlite", "./data/sbml/CorticalAreaDevelopment_cellCollective_boolean.sbml")
#writeSBMLToDBModel("./data/databases/modelDB.sqlite", "./data/sbml/CorticalAreaDevelopment_cellCollective_boolean.sbml", use_species_name_attribute=True)

# SBML to DB import example 2: Mammalian Cellcycle
#writeSBMLToDBModel("./data/databases/modelDB.sqlite", "./data/sbml/MammalianCellCycle_cellCollective_boolean.sbml")
#writeSBMLToDBModel("./data/databases/modelDB.sqlite", "./data/sbml/MammalianCellCycle_cellCollective_boolean.sbml", use_species_name_attribute=True)

# SBML to DB import example 3: Notch Pathway
#writeSBMLToDBModel("./data/databases/modelDB.sqlite", "./data/sbml/NotchPathway_ginsim_multiValued.sbml", use_species_name_attribute=False)
# The notch Pathway model does not have Species name Attributes set, as such running the tool with this line will fail and throw an exception.
#writeSBMLToDBModel("./data/databases/modelDB.sqlite", "./data/sbml/NotchPathway_ginsim_multiValued.sbml", use_species_name_attribute=True)

# read from last output file of the export function "writeDBModelToSBML"
#writeSBMLToDBModel("./data/databases/modelDB2.sqlite", "./data/sbml/db2sbml_output.sbml")
def parse_SBML(cursor):
    sys.stderr.write("Parsing the SBML model file ... ")
    fname = '../data/thermodynamics/yeast_4.02.xml'
    if (not os.path.exists(fname)):
        sys.stderr.write("Please download the yeast SBML from http://www.comp-sys-bio.org/yeastnet/ and place in at: %s\n" % fname)
        sys.exit(-1)
    yeast_SBML = libsbml.readSBML(fname)
    yeast_model = yeast_SBML.getModel()
    
    cursor.execute("DROP TABLE IF EXISTS yeast_reaction")
    cursor.execute("CREATE TABLE yeast_reaction (reaction_id TEXT, name TEXT)")
    
    cursor.execute("DROP INDEX IF EXISTS yeast_reaction_idx")
    cursor.execute("CREATE UNIQUE INDEX yeast_reaction_idx ON yeast_reaction (reaction_id);")

    cursor.execute("DROP TABLE IF EXISTS yeast_reaction2species")
    cursor.execute("CREATE TABLE yeast_reaction2species (reaction_id TEXT, species_id TEXT, stoichiometry REAL)")

    cursor.execute("DROP INDEX IF EXISTS yeast_reaction2species_idx1")
    cursor.execute("CREATE INDEX yeast_reaction2species_idx1 ON yeast_reaction2species (reaction_id);")
    
    cursor.execute("DROP INDEX IF EXISTS yeast_reaction2species_idx2")
    cursor.execute("CREATE INDEX yeast_reaction2species_idx2 ON yeast_reaction2species (species_id);")
    for reaction in yeast_model.getListOfReactions():
        cursor.execute("INSERT INTO yeast_reaction VALUES(?,?)", [reaction.getId(), reaction.getName()])
        for sp_ref in reaction.getListOfReactants():
            cursor.execute("INSERT INTO yeast_reaction2species VALUES(?,?,?)", \
                           [reaction.getId(), sp_ref.getSpecies(), -sp_ref.getStoichiometry()])
        for sp_ref in reaction.getListOfProducts():
            cursor.execute("INSERT INTO yeast_reaction2species VALUES(?,?,?)", \
                           [reaction.getId(), sp_ref.getSpecies(), sp_ref.getStoichiometry()])
    
    cursor.execute("DROP TABLE IF EXISTS yeast_species")
    cursor.execute("CREATE TABLE yeast_species (species_id TEXT, name TEXT, compartment_id TEXT, species_type_id TEXT)")
    cursor.execute("DROP INDEX IF EXISTS yeast_species_idx")
    cursor.execute("CREATE UNIQUE INDEX yeast_species_idx ON yeast_species (species_id);")
    for species in yeast_model.getListOfSpecies():
        cursor.execute("INSERT INTO yeast_species VALUES(?,?,?,?)", \
                       [species.getId(), species.getName(), species.getCompartment(), species.getSpeciesType()])

    cursor.execute("DROP TABLE IF EXISTS yeast_species_type")
    cursor.execute("CREATE TABLE yeast_species_type (species_type_id TEXT, name TEXT, ann_name TEXT, ann_value TEXT)")
    cursor.execute("DROP INDEX IF EXISTS yeast_species_type_idx")
    cursor.execute("CREATE INDEX yeast_species_type_idx ON yeast_species_type (species_type_id);")

    cursor.execute("DROP TABLE IF EXISTS yeast_species_type2chebi")
    cursor.execute("CREATE TABLE yeast_species_type2chebi (species_type_id TEXT, chebi_id INT)")
    cursor.execute("DROP INDEX IF EXISTS yeast_species_type2chebi_idx1")
    cursor.execute("CREATE UNIQUE INDEX yeast_species_type2chebi_idx1 ON yeast_species_type2chebi (species_type_id);")
    cursor.execute("DROP INDEX IF EXISTS yeast_species_type2chebi_idx2")
    cursor.execute("CREATE INDEX yeast_species_type2chebi_idx2 ON yeast_species_type2chebi (chebi_id);")
    for type in yeast_model.getListOfSpeciesTypes():
        for (name, value) in parse_MIRIAM_annotation(type.getAnnotation()):
            cursor.execute("INSERT INTO yeast_species_type VALUES(?,?,?,?)", \
                           [type.getId(), type.getName(), name, value])
            if (name == 'obo.chebi'):
                for chebi_id in re.findall('CHEBI%3A(\d+)', value):
                    cursor.execute("INSERT INTO yeast_species_type2chebi VALUES(?,?)", \
                                   [type.getId(), chebi_id])
    
    cursor.execute("DROP TABLE IF EXISTS yeast_compartment")
    cursor.execute("CREATE TABLE yeast_compartment (compartment_id TEXT, name TEXT)")
    cursor.execute("DROP INDEX IF EXISTS yeast_compartment_idx")
    cursor.execute("CREATE UNIQUE INDEX yeast_compartment_idx ON yeast_compartment (compartment_id);")
    for compartment in yeast_model.getListOfCompartments():
        cursor.execute("INSERT INTO yeast_compartment VALUES(?,?)", \
                       [compartment.getId(), compartment.getName()])
    
            
    sys.stderr.write("[DONE]\n")
 def setUp(self):
   filename = "../../sbml/annotation/test/test-data/annotationL3.xml"
   self.d = libsbml.readSBML(filename)
   self.m = self.d.getModel()
   self.c = self.m.getCompartment(0)
   pass  
Exemple #50
0
def mooseReadSBML(filepath, loadpath, solver="ee"):
    global foundLibSBML_
    if not foundLibSBML_:
        print('No python-libsbml found.' 
            '\nThis module can be installed by following command in terminal:'
            '\n\t easy_install python-libsbml'
            '\n\t apt-get install python-libsbml'
            )
        return None

    if not os.path.isfile(filepath):
        print('%s is not found ' % filepath)
        return None

    with open(filepath, "r") as filep:
        filep = open(filepath, "r")
        document = libsbml.readSBML(filepath)
        tobecontinue = False
        tobecontinue = validateModel(document)
        if tobecontinue:
            level = document.getLevel()
            version = document.getVersion()
            print(("\n" + "File: " + filepath + " (Level " +
                   str(level) + ", version " + str(version) + ")"))
            model = document.getModel()
            if (model is None):
                print("No model present.")
                return moose.element('/')
            else:
                print((" model: " + str(model)))
                print(("functionDefinitions: " +
                       str(model.getNumFunctionDefinitions())))
                print(("    unitDefinitions: " +
                       str(model.getNumUnitDefinitions())))
                print(("   compartmentTypes: " +
                       str(model.getNumCompartmentTypes())))
                print(("        specieTypes: " +
                       str(model.getNumSpeciesTypes())))
                print(("       compartments: " +
                       str(model.getNumCompartments())))
                print(("            species: " +
                       str(model.getNumSpecies())))
                print(("         parameters: " +
                       str(model.getNumParameters())))
                print((" initialAssignments: " +
                       str(model.getNumInitialAssignments())))
                print(("              rules: " +
                       str(model.getNumRules())))
                print(("        constraints: " +
                       str(model.getNumConstraints())))
                print(("          reactions: " +
                       str(model.getNumReactions())))
                print(("             events: " +
                       str(model.getNumEvents())))
                print("\n")

                if (model.getNumCompartments() == 0):
                    return moose.element('/')
                else:
                    baseId = moose.Neutral(loadpath)
                    basePath = baseId
                    # All the model will be created under model as
                    # a thumbrule
                    basePath = moose.Neutral(baseId.path + '/model')
                    # Map Compartment's SBML id as key and value is
                    # list of[ Moose ID and SpatialDimensions ]
                    global comptSbmlidMooseIdMap
                    global warning
                    warning = " "
                    global msg
                    msg = " "
                    comptSbmlidMooseIdMap = {}
                    #print(("modelPath:" + basePath.path))
                    globparameterIdValue = {}
                    modelAnnotaInfo = {}
                    mapParameter(model, globparameterIdValue)
                    errorFlag = createCompartment(
                        basePath, model, comptSbmlidMooseIdMap)
                    if errorFlag:
                        specInfoMap = {}
                        errorFlag,warning = createSpecies(
                            basePath, model, comptSbmlidMooseIdMap, specInfoMap, modelAnnotaInfo)
                        #print(errorFlag,warning)
                        
                        if errorFlag:
                            errorFlag = createRules(
                                model, specInfoMap, globparameterIdValue)
                            if errorFlag:
                                errorFlag, msg = createReaction(
                                    model, specInfoMap, modelAnnotaInfo, globparameterIdValue)
                        getModelAnnotation(
                            model, baseId, basePath)
                        
                    if not errorFlag:
                        print(msg)
                        # Any time in the middle if SBML does not read then I
                        # delete everything from model level This is important
                        # as while reading in GUI the model will show up untill
                        # built which is not correct print "Deleted rest of the
                        # model"
                        moose.delete(basePath)
                        basePath = moose.Shell('/')
            return basePath
        else:
            print("Validation failed while reading the model.")
            return moose.element('/')
Exemple #51
0
        def get_substr_term(s):
            term = self._get_substrate_term(s)
            term = term[:term.rfind(')') + 1]
            term = 'sqrt(%s)' % term
            return term

        text = ' * '.join([get_substr_term(s)
                           for s in misc.get_participants(reaction)])
        return '(%s)' % text


class KineticizerRP(Kineticizer):
    ''' mass action implementation '''
    _kinetic_law_sbo = 531


    def _get_denominator(self, reaction, mode):
        return '(1)'


if __name__ == '__main__':

    d = libsbml.readSBML(sys.argv[1])
    m = d.getModel()

    sbtab = libSBtab.Table.KineticDataTable()
    sbtab.fromTSVFile(sys.argv[2])

    KineticizerRP(m, sbtab, mode='cat')
    print('<?xml version="1.0" encoding="UTF-8"?>\n' + d.toSBML())

def write_left_nullspace_to_file(M, filepath, species_names):  # pass rownames of corresponding S as species_names
    M_df = pd.DataFrame([[round(x, 4) for x in line] for line in M], columns=species_names)
    with open(filepath, "w") as outfile:
        outfile.write(M_df.to_csv(sep="\t"))


def write_eigenvalues_to_file(model, filepath, species_names):
    M_df = pd.DataFrame([model.getFullEigenValues()], columns=species_names)
    with open(filepath, "w") as outfile:
        outfile.write(M_df.to_csv(sep="\t"))


# We start with the smallest subsystem: Amino Sugar and Nucleotide Sugar Metabolism
asansm_libsbml_doc = libsbml.readSBML(asansm_sbml)
asansm_libsbml = asansm_libsbml_doc.getModel()
asansm_model = te.loadSBMLModel(asansm_sbml)
S_asansm = asansm_model.getFullStoichiometryMatrix()
S_asansm.colnames = get_reaction_names(asansm_libsbml.getListOfReactions(), S_asansm.colnames)
S_asansm.rownames = get_metabolite_names(asansm_libsbml.getListOfSpecies(), S_asansm.rownames)
asansm_right_nullspace = Matrix(S_asansm).nullspace()
asansm_left_nullspace = Matrix(S_asansm.T).nullspace()
asansm_rank = Matrix(S_asansm).rank()

# Next subsystem: Pyrimidine Metabolism
# This one is a little special because Matrix().nullspace computes an empty right nullspace here, but there is one!
# So we do it the pedestrian way...
pm_libsbml_doc = libsbml.readSBML(pm_sbml)
pm_libsbml = pm_libsbml_doc.getModel()
pm_model = te.loadSBMLModel(pm_sbml)
 def setUp(self):
   filename = "../../sbml/annotation/test/test-data/annotation.xml"
   self.d = libsbml.readSBML(filename)
   self.m = self.d.getModel()
   pass  
Exemple #54
0
def convert(filename, modelName = None, gillespy_model=None):
    try: 
        import libsbml
    except ImportError:
        raise ImportError('libsbml is required to convert SBML files for GillesPy.')
        
    
    document = libsbml.readSBML(filename)

    errors = []

    errorCount = document.getNumErrors()
    if errorCount > 0:
        for i in range(errorCount):
            error = document.getError(i)
            converterCode = 0
            converterCode = -10

            errors.append(["SBML {0}, code {1}, line {2}: {3}".format(error.getSeverityAsString(), error.getErrorId(), error.getLine(), error.getMessage()), converterCode])

    if min([code for error, code in errors] + [0]) < 0:
        return None, errors

    model = document.getModel()
    numOfTabs = 0

    if modelName == None:
        modelName = model.getName()
    
    if gillespy_model==None:
        gillespy_model = gillespy.Model(name = modelName)

    gillespy_model.units = "concentration"

    for i in range(model.getNumSpecies()):
        species = model.getSpecies(i)

        if species.getId() == 'EmptySet':
            errors.append(["EmptySet species detected in model on line {0}. EmptySet is not an explicit species in gillespy".format(species.getLine()), 0])
            continue

        name = species.getId()

        if species.isSetInitialAmount():
            value = species.getInitialAmount()
        elif species.isSetInitialConcentration():
            value = species.getInitialConcentration()
        else:
            rule = model.getRule(species.getId())

            if rule:
                msg = ""

                if rule.isAssignment():
                    msg = "assignment "
                elif rule.isRate():
                    msg = "rate "
                elif rule.isAlgebraic():
                    msg = "algebraic "

                msg += "rule"

                errors.append(["Species '{0}' does not have any initial conditions. Associated {1} '{2}' found, but {1}s are not supported in gillespy. Assuming initial condition 0".format(species.getId(), msg, rule.getId()), 0])
            else:
                errors.append(["Species '{0}' does not have any initial conditions or rules. Assuming initial condition 0".format(species.getId()), 0])

            value = 0

        if value < 0.0:
            errors.append(["Species '{0}' has negative initial condition ({1}). gillespy does not support negative initial conditions. Assuming initial condition 0".format(species.getId(), value), -5])
            value = 0

        gillespySpecies = gillespy.Species(name = name, initial_value = value)
        gillespy_model.add_species([gillespySpecies])

    for i in range(model.getNumParameters()):
        parameter=model.getParameter(i)
        name=parameter.getId()
        value=parameter.getValue()

        gillespyParameter = gillespy.Parameter(name = name, expression = value)
        gillespy_model.add_parameter([gillespyParameter])

    for i in range(model.getNumCompartments()):
        compartment=model.getCompartment(i)
        name=compartment.getId()
        value=compartment.getSize()

        gillespyParameter = gillespy.Parameter(name = name, expression = value)
        gillespy_model.add_parameter([gillespyParameter])

    #local parameters
    for i in range(model.getNumReactions()):
        reaction = model.getReaction(i)
        kineticLaw = reaction.getKineticLaw()

        for j in range(kineticLaw.getNumParameters()):
            parameter = kineticLaw.getParameter(j)
            name = parameter.getId()
            value = parameter.getValue()
            gillespyParameter = gillespy.Parameter(name = name, expression = value)
            gillespy_model.add_parameter([gillespyParameter])

    #reactions
    for i in range(model.getNumReactions()):
        reaction = model.getReaction(i)
        name = reaction.getId()
        
        reactants = {}
        products = {}

        for j in range(reaction.getNumReactants()):
            species = reaction.getReactant(j)

            if species.getSpecies() == "EmptySet":
                errors.append(["EmptySet species detected as reactant in reaction '{0}' on line {1}. EmptySet is not an explicit species in gillespy".format(reaction.getId(), species.getLine()), 0])
            else:
                reactants[species.getSpecies()] = species.getStoichiometry()

        #get products
        for j in range(reaction.getNumProducts()):
            species=reaction.getProduct(j)

            if species.getSpecies() == "EmptySet":
                errors.append(["EmptySet species detected as product in reaction '{0}' on line {1}. EmptySet is not an explicit species in gillespy".format(reaction.getId(), species.getLine()), 0])
            else:
                products[species.getSpecies()] = species.getStoichiometry()

        #propensity
        kineticLaw = reaction.getKineticLaw()
        propensity = kineticLaw.getFormula()

        gillespyReaction = gillespy.Reaction(name = name, reactants = reactants, products = products, propensity_function = propensity)

        gillespy_model.add_reaction([gillespyReaction])

    for i in range(model.getNumRules()):
        rule = model.getRule(i)

        t = []

        if rule.isCompartmentVolume():
            t.append('compartment')
        if rule.isParameter():
            t.append('parameter')
        elif rule.isAssignment():
            t.append('assignment')
        elif rule.isRate():
            t.append('rate')
        elif rule.isAlgebraic():
            t.append('algebraic')

        if len(t) > 0:
            t[0] = t[0].capitalize()

            msg = ", ".join(t)
            msg += " rule"
        else:
            msg = "Rule"

        errors.append(["{0} '{1}' found on line '{2}' with equation '{3}'. gillespy does not support SBML Rules".format(msg, rule.getId(), rule.getLine(), libsbml.formulaToString(rule.getMath())), -5])

    for i in range(model.getNumCompartments()):
        compartment = model.getCompartment(i)

        errors.append(["Compartment '{0}' found on line '{1}' with volume '{2}' and dimension '{3}'. gillespy assumes a single well-mixed, reaction volume".format(compartment.getId(), compartment.getLine(), compartment.getVolume(), compartment.getSpatialDimensions()), -5])

    for i in range(model.getNumConstraints()):
        constraint = model.getConstraint(i)

        errors.append(["Constraint '{0}' found on line '{1}' with equation '{2}'. gillespy does not support SBML Constraints".format(constraint.getId(), constraint.getLine(), libsbml.formulaToString(constraint.getMath())), -5])

    for i in range(model.getNumEvents()):
        event = model.getEvent(i)

        errors.append(["Event '{0}' found on line '{1}' with trigger equation '{2}'. gillespy does not support SBML Events".format(event.getId(), event.getLine(), libsbml.formulaToString(event.getTrigger().getMath())), -5])

    for i in range(model.getNumFunctionDefinitions()):
        function = model.getFunctionDefinition(i)

        errors.append(["Function '{0}' found on line '{1}' with equation '{2}'. gillespy does not support SBML Function Definitions".format(function.getId(), function.getLine(), libsbml.formulaToString(function.getMath())), -5])

    return gillespy_model, errors
Exemple #55
0
	def mooseReadSBML(filepath,loadpath,solver="ee"):
		try:
			filep = open(filepath, "r")
			document = libsbml.readSBML(filepath)
			num_errors = document.getNumErrors()
			if ( num_errors > 0 ):
				print("Encountered the following SBML errors:" );
				document.printErrors();
				return moose.element('/');
			else:
				level = document.getLevel();
				version = document.getVersion();
				print(("\n" + "File: " + filepath + " (Level " + str(level) + ", version " + str(version) + ")" ));
				model = document.getModel();
				if (model == None):
					print("No model present." );
					return moose.element('/');
				else:
					print((" model: " +str(model)));
					print(("functionDefinitions: " + str(model.getNumFunctionDefinitions()) ));
					print(("    unitDefinitions: " + str(model.getNumUnitDefinitions()) ));
					print(("   compartmentTypes: " + str(model.getNumCompartmentTypes()) ));
					print(("        specieTypes: " + str(model.getNumSpeciesTypes()) ));
					print(("       compartments: " + str(model.getNumCompartments()) ));
					print(("            species: " + str(model.getNumSpecies()) ));
					print(("         parameters: " + str(model.getNumParameters()) ));
					print((" initialAssignments: " + str(model.getNumInitialAssignments()) ));
					print(("              rules: " + str(model.getNumRules()) ));
					print(("        constraints: " + str(model.getNumConstraints()) ));
					print(("          reactions: " + str(model.getNumReactions()) ));
					print(("             events: " + str(model.getNumEvents()) ));
					print("\n");

					if (model.getNumCompartments() == 0):
						return moose.element('/')
					else:
						baseId = moose.Neutral(loadpath)
						#All the model will be created under model as a thumbrule
						basePath = moose.Neutral(baseId.path+'/model')
						#Map Compartment's SBML id as key and value is list of[ Moose ID and SpatialDimensions ]
						global comptSbmlidMooseIdMap
						global warning
						warning = " "
						comptSbmlidMooseIdMap = {}
						print(("modelPath:" + basePath.path))
						globparameterIdValue = {}
						modelAnnotaInfo = {}
						mapParameter(model,globparameterIdValue)
						errorFlag = createCompartment(basePath,model,comptSbmlidMooseIdMap)
						if errorFlag:
							specInfoMap = {}
							errorFlag = createSpecies(basePath,model,comptSbmlidMooseIdMap,specInfoMap,modelAnnotaInfo)
							if errorFlag:
								errorFlag = createRules(model,specInfoMap,globparameterIdValue)
								if errorFlag:
									errorFlag,msg = createReaction(model,specInfoMap,modelAnnotaInfo,globparameterIdValue)
							getModelAnnotation(model,baseId,basePath)
						
						if not errorFlag:
							print(msg)
							#Any time in the middle if SBML does not read then I delete everything from model level
							#This is important as while reading in GUI the model will show up untill built which is not correct
							#print "Deleted rest of the model"
							moose.delete(basePath)
					return baseId;


		except IOError:
			print("File " ,filepath ," does not exist.")
			return moose.element('/')
 def test_read_l1v1_rules(self):
   filename = "../../sbml/test/test-data/l1v1-rules.xml"
   d = libsbml.readSBML(filename)
   if (d == None):
     pass    
   self.assert_( d.getLevel() == 1 )
   self.assert_( d.getVersion() == 1 )
   m = d.getModel()
   self.assert_( m.getNumCompartments() == 1 )
   c = m.getCompartment(0)
   self.assert_((  "cell" == c.getName() ))
   self.assert_( c.getVolume() == 1 )
   self.assert_( m.getNumSpecies() == 6 )
   s = m.getSpecies(0)
   self.assert_((  "s1"    == s.getName() ))
   self.assert_((  "cell"  == s.getCompartment() ))
   self.assert_( s.getInitialAmount() == 4 )
   self.assert_( s.getBoundaryCondition() == False )
   s = m.getSpecies(1)
   self.assert_((  "s2"    == s.getName() ))
   self.assert_((  "cell"  == s.getCompartment() ))
   self.assert_( s.getInitialAmount() == 2 )
   self.assert_( s.getBoundaryCondition() == False )
   s = m.getSpecies(2)
   self.assert_((  "x0"    == s.getName() ))
   self.assert_((  "cell"  == s.getCompartment() ))
   self.assert_( s.getInitialAmount() == 1 )
   self.assert_( s.getBoundaryCondition() == False )
   s = m.getSpecies(3)
   self.assert_((  "x1"    == s.getName() ))
   self.assert_((  "cell"  == s.getCompartment() ))
   self.assert_( s.getInitialAmount() == 0 )
   self.assert_( s.getBoundaryCondition() == False )
   s = m.getSpecies(4)
   self.assert_((  "x2"    == s.getName() ))
   self.assert_((  "cell"  == s.getCompartment() ))
   self.assert_( s.getInitialAmount() == 1 )
   self.assert_( s.getBoundaryCondition() == False )
   s = m.getSpecies(5)
   self.assert_((  "x3"    == s.getName() ))
   self.assert_((  "cell"  == s.getCompartment() ))
   self.assert_( s.getInitialAmount() == 0 )
   self.assert_( s.getBoundaryCondition() == False )
   self.assert_( m.getNumParameters() == 7 )
   p = m.getParameter(0)
   self.assert_((  "k1" == p.getName() ))
   self.assert_( p.getValue() == 1.2 )
   p = m.getParameter(1)
   self.assert_((  "k2" == p.getName() ))
   self.assert_( p.getValue() == 1000 )
   p = m.getParameter(2)
   self.assert_((  "k3" == p.getName() ))
   self.assert_( p.getValue() == 3000 )
   p = m.getParameter(3)
   self.assert_((  "k4" == p.getName() ))
   self.assert_( p.getValue() == 4.5 )
   self.assert_( m.getNumRules() == 4 )
   pr = m.getRule(0)
   self.assert_((  "t" == pr.getVariable() ))
   self.assert_((  "s1 + s2" == pr.getFormula() ))
   ud = pr.getDerivedUnitDefinition()
   self.assert_( ud.getNumUnits() == 2 )
   self.assert_( ud.getUnit(0).getKind() == libsbml.UNIT_KIND_MOLE )
   self.assert_( ud.getUnit(0).getExponent() == 1 )
   self.assert_( ud.getUnit(1).getKind() == libsbml.UNIT_KIND_LITRE )
   self.assert_( ud.getUnit(1).getExponent() == -1 )
   self.assert_( pr.containsUndeclaredUnits() == False )
   pr = m.getRule(1)
   self.assert_((  "k" == pr.getVariable() ))
   self.assert_((  "k3/k2" == pr.getFormula() ))
   ud = pr.getDerivedUnitDefinition()
   self.assert_( ud.getNumUnits() == 0 )
   self.assert_( pr.containsUndeclaredUnits() == True )
   scr = m.getRule(2)
   self.assert_((  "x2" == scr.getVariable() ))
   self.assert_((  "k * (s1+s2)/(1 + k)" == scr.getFormula() ))
   scr = m.getRule(3)
   self.assert_((  "x3" == scr.getVariable() ))
   self.assert_((  "p*(t - s2)" == scr.getFormula() ))
   self.assert_( m.getNumReactions() == 2 )
   r = m.getReaction(0)
   self.assert_((  "j1" == r.getName() ))
   self.assert_( r.getReversible() != False )
   self.assert_( r.getFast() == False )
   r = m.getReaction(1)
   self.assert_((  "j3" == r.getName() ))
   self.assert_( r.getReversible() != False )
   self.assert_( r.getFast() == False )
   r = m.getReaction(0)
   self.assert_( r.getNumReactants() == 1 )
   self.assert_( r.getNumProducts() == 1 )
   sr = r.getReactant(0)
   self.assert_((  "x0" == sr.getSpecies() ))
   self.assert_( sr.getStoichiometry() == 1 )
   self.assert_( sr.getDenominator() == 1 )
   sr = r.getProduct(0)
   self.assert_((  "s1" == sr.getSpecies() ))
   self.assert_( sr.getStoichiometry() == 1 )
   self.assert_( sr.getDenominator() == 1 )
   kl = r.getKineticLaw()
   self.assert_((  "k1 * x0" == kl.getFormula() ))
   r = m.getReaction(1)
   self.assert_( r.getNumReactants() == 1 )
   self.assert_( r.getNumProducts() == 1 )
   sr = r.getReactant(0)
   self.assert_((  "s2" == sr.getSpecies() ))
   self.assert_( sr.getStoichiometry() == 1 )
   self.assert_( sr.getDenominator() == 1 )
   sr = r.getProduct(0)
   self.assert_((  "x1" == sr.getSpecies() ))
   self.assert_( sr.getStoichiometry() == 1 )
   self.assert_( sr.getDenominator() == 1 )
   kl = r.getKineticLaw()
   self.assert_((  "k4 * s2" == kl.getFormula() ))
   _dummyList = [ d ]; _dummyList[:] = []; del _dummyList
   pass  
Exemple #57
0
def create_cobra_model_from_sbml_file(sbml_filename, old_sbml=False, legacy_metabolite=False,
                                      print_time=False, use_hyphens=False):
    """convert an SBML XML file into a cobra.Model object.  Supports
    SBML Level 2 Versions 1 and 4.  The function will detect if the SBML fbc package is used in the file
    and run the converter if the fbc package is used.

    sbml_filename: String.

    old_sbml:  Boolean. Set to True if the XML file has metabolite
    formula appended to metabolite names.  This was a poorly designed
    artifact that persists in some models.

    legacy_metabolite: Boolean.  If True then assume that the metabolite id has
    the compartment id appended after an underscore (e.g. _c for cytosol).  This
    has not been implemented but will be soon.

    print_time: deprecated

    use_hyphens:   Boolean.  If True, double underscores (__) in an SBML ID will be converted to hyphens

    """
    __default_lower_bound = -1000
    __default_upper_bound = 1000
    __default_objective_coefficient = 0
     # Ensure that the file exists
    if not isfile(sbml_filename):
        raise IOError('Your SBML file is not found: %s'%sbml_filename)
    #Expressions to change SBML Ids to Palsson Lab Ids
    metabolite_re = re.compile('^M_')
    reaction_re = re.compile('^R_')
    compartment_re = re.compile('^C_')
    if print_time:
        warn("print_time is deprecated")
    model_doc = readSBML(sbml_filename)
    if (model_doc.getPlugin("fbc") != None):
        from libsbml import ConversionProperties, LIBSBML_OPERATION_SUCCESS
        conversion_properties = ConversionProperties()
        conversion_properties.addOption("convert fbc to cobra", True, "Convert FBC model to Cobra model")
        result = model_doc.convert(conversion_properties)
        if result != LIBSBML_OPERATION_SUCCESS:
            raise(Exception("Conversion of SBML+fbc to COBRA failed"))
    sbml_model = model_doc.getModel()
    sbml_model_id = sbml_model.getId()
    sbml_species = sbml_model.getListOfSpecies()
    sbml_reactions = sbml_model.getListOfReactions()
    sbml_compartments = sbml_model.getListOfCompartments()
    compartment_dict = dict([(compartment_re.split(x.getId())[-1], x.getName())
                             for x in sbml_compartments])
    if legacy_metabolite:
        #Deal with the palsson lab appending the compartment id to the metabolite id
        new_dict = {}
        for the_id, the_name in compartment_dict.items():
            if the_name == '':
                new_dict[the_id[0].lower()] = the_id
            else:
                new_dict[the_id] = the_name
        compartment_dict = new_dict
        legacy_compartment_converter = dict([(v,k)
                                             for k, v in compartment_dict.items()])

    cobra_model = Model(sbml_model_id)
    metabolites = []
    metabolite_dict = {}
    #Convert sbml_metabolites to cobra.Metabolites
    for sbml_metabolite in sbml_species:
        #Skip sbml boundary species
        if sbml_metabolite.getBoundaryCondition():
            continue

        if (old_sbml or legacy_metabolite) and \
               sbml_metabolite.getId().endswith('_b'):
            #Deal with incorrect sbml from bigg.ucsd.edu
            continue
        tmp_metabolite = Metabolite()
        metabolite_id = tmp_metabolite.id = sbml_metabolite.getId()
        tmp_metabolite.compartment = compartment_re.split(sbml_metabolite.getCompartment())[-1]
        if legacy_metabolite:
            if tmp_metabolite.compartment not in compartment_dict:
                tmp_metabolite.compartment = legacy_compartment_converter[tmp_metabolite.compartment]
            tmp_metabolite.id = parse_legacy_id(tmp_metabolite.id, tmp_metabolite.compartment,
                                                use_hyphens=use_hyphens)
        if use_hyphens:
            tmp_metabolite.id = metabolite_re.split(tmp_metabolite.id)[-1].replace('__','-')
        else:
            #Just in case the SBML ids are ill-formed and use -
            tmp_metabolite.id = metabolite_re.split(tmp_metabolite.id)[-1].replace('-','__')
        tmp_metabolite.name = sbml_metabolite.getName()
        tmp_formula = ''
        tmp_metabolite.notes = parse_legacy_sbml_notes(sbml_metabolite.getNotesString())
        if sbml_metabolite.isSetCharge():
            tmp_metabolite.charge = sbml_metabolite.getCharge()
        if "CHARGE" in tmp_metabolite.notes:
            note_charge = tmp_metabolite.notes["CHARGE"][0]
            try:
                note_charge = float(note_charge)
                if note_charge == int(note_charge):
                    note_charge = int(note_charge)
            except:
                warn("charge of %s is not a number (%s)" % (tmp_metabolite.id, str(note_charge)))
            else:
                if tmp_metabolite.charge is None or tmp_metabolite.charge == note_charge:
                    tmp_metabolite.notes.pop("CHARGE")
                else:  # tmp_metabolite.charge != note_charge
                    msg = "different charges specified for %s (%d and %d)"
                    msg = msg % (tmp_metabolite.id, tmp_metabolite.charge, note_charge)
                    warn(msg)
                    # Chances are a 0 note charge was written by mistake. We
                    # will default to the note_charge in this case.
                    if tmp_metabolite.charge == 0:
                        tmp_metabolite.charge = note_charge

        for the_key in tmp_metabolite.notes.keys():
            if the_key.lower() == 'formula':
                tmp_formula = tmp_metabolite.notes.pop(the_key)[0]
                break
        if tmp_formula == '' and old_sbml:
            tmp_formula = tmp_metabolite.name.split('_')[-1]
            tmp_metabolite.name = tmp_metabolite.name[:-len(tmp_formula)-1]
        tmp_metabolite.formula = tmp_formula
        metabolite_dict.update({metabolite_id: tmp_metabolite})
        metabolites.append(tmp_metabolite)
    cobra_model.add_metabolites(metabolites)

    #Construct the vectors and matrices for holding connectivity and numerical info
    #to feed to the cobra toolbox.
    #Always assume steady state simulations so b is set to 0
    cobra_reaction_list = []
    for sbml_reaction in sbml_reactions:
        if use_hyphens:
            #Change the ids to match conventions used by the Palsson lab.
            reaction = Reaction(reaction_re.split(sbml_reaction.getId())[-1].replace('__','-'))
        else:
            #Just in case the SBML ids are ill-formed and use -
            reaction = Reaction(reaction_re.split(sbml_reaction.getId())[-1].replace('-','__'))
        cobra_reaction_list.append(reaction)
        #reaction.exchange_reaction = 0
        reaction.name = sbml_reaction.getName()
        cobra_metabolites = {}
        #Use the cobra.Metabolite class here
        for sbml_metabolite in sbml_reaction.getListOfReactants():
            tmp_metabolite_id = sbml_metabolite.getSpecies()
            #This deals with boundary metabolites
            if tmp_metabolite_id in metabolite_dict:
                tmp_metabolite = metabolite_dict[tmp_metabolite_id]
                cobra_metabolites[tmp_metabolite] = -sbml_metabolite.getStoichiometry()
        for sbml_metabolite in sbml_reaction.getListOfProducts():
            tmp_metabolite_id = sbml_metabolite.getSpecies()
            #This deals with boundary metabolites
            if tmp_metabolite_id in metabolite_dict:
                tmp_metabolite = metabolite_dict[tmp_metabolite_id]
                # Handle the case where the metabolite was specified both
                # as a reactant and as a product.
                if tmp_metabolite in cobra_metabolites:
                    warn("%s appears as a reactant and product %s" %
                         (tmp_metabolite_id, reaction.id))
                    cobra_metabolites[tmp_metabolite] += sbml_metabolite.getStoichiometry()
                    # if the combined stoichiometry is 0, remove the metabolite
                    if cobra_metabolites[tmp_metabolite] == 0:
                        cobra_metabolites.pop(tmp_metabolite)
                else:
                    cobra_metabolites[tmp_metabolite] = sbml_metabolite.getStoichiometry()
        # check for nan
        for met, v in iteritems(cobra_metabolites):
            if isnan(v) or isinf(v):
                warn("invalid value %s for metabolite '%s' in reaction '%s'" %
                     (str(v), met.id, reaction.id))
        reaction.add_metabolites(cobra_metabolites)
        #Parse the kinetic law info here.
        parameter_dict = {}
        #If lower and upper bounds are specified in the Kinetic Law then
        #they override the sbml reversible attribute.  If they are not
        #specified then the bounds are determined by getReversible.
        if not sbml_reaction.getKineticLaw():
            
            if sbml_reaction.getReversible():
                parameter_dict['lower_bound'] = __default_lower_bound
                parameter_dict['upper_bound'] = __default_upper_bound
            else:
                #Assume that irreversible reactions only proceed from left to right.
                parameter_dict['lower_bound'] = 0
                parameter_dict['upper_bound'] = __default_upper_bound
                
            parameter_dict['objective_coefficient'] = __default_objective_coefficient
        else:
            for sbml_parameter in sbml_reaction.getKineticLaw().getListOfParameters():
                parameter_dict[sbml_parameter.getId().lower()] = sbml_parameter.getValue()

        if 'lower_bound' in parameter_dict:
            reaction.lower_bound = parameter_dict['lower_bound']
        elif 'lower bound' in parameter_dict:
            reaction.lower_bound = parameter_dict['lower bound']
        elif sbml_reaction.getReversible():
            reaction.lower_bound = __default_lower_bound
        else:
            reaction.lower_bound = 0

        if 'upper_bound' in parameter_dict:
            reaction.upper_bound = parameter_dict['upper_bound']
        elif 'upper bound' in parameter_dict:
            reaction.upper_bound = parameter_dict['upper bound']
        else:
            reaction.upper_bound = __default_upper_bound

        if 'objective_coefficient' in parameter_dict:
            reaction.objective_coefficient = parameter_dict['objective_coefficient']
        elif 'objective coefficient' in parameter_dict:
            reaction.objective_coefficient = parameter_dict['objective coefficient']
        else:
            reaction.objective_coefficient = __default_objective_coefficient

        # ensure values are not set to nan or inf
        if isnan(reaction.lower_bound) or isinf(reaction.lower_bound):
            reaction.lower_bound = __default_lower_bound
        if isnan(reaction.upper_bound) or isinf(reaction.upper_bound):
            reaction.upper_bound = __default_upper_bound

        reaction_note_dict = parse_legacy_sbml_notes(sbml_reaction.getNotesString())
        #Parse the reaction notes.
        #POTENTIAL BUG: DEALING WITH LEGACY 'SBML' THAT IS NOT IN A
        #STANDARD FORMAT
        #TODO: READ IN OTHER NOTES AND GIVE THEM A reaction_ prefix.
        #TODO: Make sure genes get added as objects
        if 'GENE ASSOCIATION' in reaction_note_dict:
            rule = reaction_note_dict['GENE ASSOCIATION'][0]
            try:
                rule.encode('ascii')
            except (UnicodeEncodeError, UnicodeDecodeError):
                warn("gene_reaction_rule '%s' is not ascii compliant" % rule)
            if rule.startswith("&quot;") and rule.endswith("&quot;"):
                rule = rule[6:-6]
            reaction.gene_reaction_rule = rule
            if 'GENE LIST' in reaction_note_dict:
                reaction.systematic_names = reaction_note_dict['GENE LIST'][0]
            elif 'GENES' in reaction_note_dict and \
                     reaction_note_dict['GENES'] != ['']:
                reaction.systematic_names = reaction_note_dict['GENES'][0]
            elif 'LOCUS' in reaction_note_dict:
                gene_id_to_object = dict([(x.id, x) for x in reaction._genes])
                for the_row in reaction_note_dict['LOCUS']:
                    tmp_row_dict = {}
                    the_row = 'LOCUS:' + the_row.lstrip('_').rstrip('#')
                    for the_item in the_row.split('#'):
                        k, v = the_item.split(':')
                        tmp_row_dict[k] = v
                    tmp_locus_id = tmp_row_dict['LOCUS']
                    if 'TRANSCRIPT' in tmp_row_dict:
                        tmp_locus_id = tmp_locus_id + '.' + tmp_row_dict['TRANSCRIPT']
                    
                    if 'ABBREVIATION' in tmp_row_dict:
                        gene_id_to_object[tmp_locus_id].name = tmp_row_dict['ABBREVIATION']

        if 'SUBSYSTEM' in reaction_note_dict:
            reaction.subsystem = reaction_note_dict.pop('SUBSYSTEM')[0]

        reaction.notes = reaction_note_dict


    #Now, add all of the reactions to the model.
    cobra_model.id = sbml_model.getId()
    #Populate the compartment list - This will be done based on cobra.Metabolites
    #in cobra.Reactions in the future.
    cobra_model.compartments = compartment_dict

    cobra_model.add_reactions(cobra_reaction_list)
        #cobra_model.update_rules()
    return cobra_model
 def test_read_l1v1_branch(self):
   filename = "../../sbml/test/test-data/l1v1-branch.xml"
   d = libsbml.readSBML(filename)
   if (d == None):
     pass    
   self.assert_( d.getLevel() == 1 )
   self.assert_( d.getVersion() == 1 )
   m = d.getModel()
   self.assert_((  "Branch" == m.getName() ))
   self.assert_( m.getNumCompartments() == 1 )
   c = m.getCompartment(0)
   self.assert_((  "compartmentOne" == c.getName() ))
   self.assert_( c.getVolume() == 1 )
   ud = c.getDerivedUnitDefinition()
   self.assert_( ud.getNumUnits() == 1 )
   self.assert_( ud.getUnit(0).getKind() == libsbml.UNIT_KIND_LITRE )
   self.assert_( m.getNumSpecies() == 4 )
   s = m.getSpecies(0)
   self.assert_((  "S1"              == s.getName() ))
   self.assert_((  "compartmentOne"  == s.getCompartment() ))
   self.assert_( s.getInitialAmount() == 0 )
   self.assert_( s.getBoundaryCondition() == False )
   ud = s.getDerivedUnitDefinition()
   self.assert_( ud.getNumUnits() == 2 )
   self.assert_( ud.getUnit(0).getKind() == libsbml.UNIT_KIND_MOLE )
   self.assert_( ud.getUnit(0).getExponent() == 1 )
   self.assert_( ud.getUnit(1).getKind() == libsbml.UNIT_KIND_LITRE )
   self.assert_( ud.getUnit(1).getExponent() == -1 )
   s = m.getSpecies(1)
   self.assert_((  "X0"              == s.getName() ))
   self.assert_((  "compartmentOne"  == s.getCompartment() ))
   self.assert_( s.getInitialAmount() == 0 )
   self.assert_( s.getBoundaryCondition() == True )
   s = m.getSpecies(2)
   self.assert_((  "X1"              == s.getName() ))
   self.assert_((  "compartmentOne"  == s.getCompartment() ))
   self.assert_( s.getInitialAmount() == 0 )
   self.assert_( s.getBoundaryCondition() == True )
   s = m.getSpecies(3)
   self.assert_((  "X2"              == s.getName() ))
   self.assert_((  "compartmentOne"  == s.getCompartment() ))
   self.assert_( s.getInitialAmount() == 0 )
   self.assert_( s.getBoundaryCondition() == True )
   self.assert_( m.getNumReactions() == 3 )
   r = m.getReaction(0)
   self.assert_((  "reaction_1" == r.getName() ))
   self.assert_( r.getReversible() == False )
   self.assert_( r.getFast() == False )
   ud = r.getKineticLaw().getDerivedUnitDefinition()
   self.assert_( ud.getNumUnits() == 2 )
   self.assert_( ud.getUnit(0).getKind() == libsbml.UNIT_KIND_MOLE )
   self.assert_( ud.getUnit(0).getExponent() == 1 )
   self.assert_( ud.getUnit(1).getKind() == libsbml.UNIT_KIND_LITRE )
   self.assert_( ud.getUnit(1).getExponent() == -1 )
   self.assert_( r.getKineticLaw().containsUndeclaredUnits() == True )
   r = m.getReaction(1)
   self.assert_((  "reaction_2" == r.getName() ))
   self.assert_( r.getReversible() == False )
   self.assert_( r.getFast() == False )
   r = m.getReaction(2)
   self.assert_((  "reaction_3" == r.getName() ))
   self.assert_( r.getReversible() == False )
   self.assert_( r.getFast() == False )
   r = m.getReaction(0)
   self.assert_( r.getNumReactants() == 1 )
   self.assert_( r.getNumProducts() == 1 )
   sr = r.getReactant(0)
   self.assert_((  "X0" == sr.getSpecies() ))
   self.assert_( sr.getStoichiometry() == 1 )
   self.assert_( sr.getDenominator() == 1 )
   sr = r.getProduct(0)
   self.assert_((  "S1" == sr.getSpecies() ))
   self.assert_( sr.getStoichiometry() == 1 )
   self.assert_( sr.getDenominator() == 1 )
   kl = r.getKineticLaw()
   self.assert_((  "k1 * X0" == kl.getFormula() ))
   self.assert_( kl.getNumParameters() == 1 )
   p = kl.getParameter(0)
   self.assert_((  "k1" == p.getName() ))
   self.assert_( p.getValue() == 0 )
   r = m.getReaction(1)
   self.assert_( r.getNumReactants() == 1 )
   self.assert_( r.getNumProducts() == 1 )
   sr = r.getReactant(0)
   self.assert_((  "S1" == sr.getSpecies() ))
   self.assert_( sr.getStoichiometry() == 1 )
   self.assert_( sr.getDenominator() == 1 )
   sr = r.getProduct(0)
   self.assert_((  "X1" == sr.getSpecies() ))
   self.assert_( sr.getStoichiometry() == 1 )
   self.assert_( sr.getDenominator() == 1 )
   kl = r.getKineticLaw()
   self.assert_((  "k2 * S1" == kl.getFormula() ))
   self.assert_( kl.getNumParameters() == 1 )
   p = kl.getParameter(0)
   self.assert_((  "k2" == p.getName() ))
   self.assert_( p.getValue() == 0 )
   r = m.getReaction(2)
   self.assert_( r.getNumReactants() == 1 )
   self.assert_( r.getNumProducts() == 1 )
   sr = r.getReactant(0)
   self.assert_((  "S1" == sr.getSpecies() ))
   self.assert_( sr.getStoichiometry() == 1 )
   self.assert_( sr.getDenominator() == 1 )
   sr = r.getProduct(0)
   self.assert_((  "X2" == sr.getSpecies() ))
   self.assert_( sr.getStoichiometry() == 1 )
   self.assert_( sr.getDenominator() == 1 )
   kl = r.getKineticLaw()
   self.assert_((  "k3 * S1" == kl.getFormula() ))
   self.assert_( kl.getNumParameters() == 1 )
   p = kl.getParameter(0)
   self.assert_((  "k3" == p.getName() ))
   self.assert_( p.getValue() == 0 )
   _dummyList = [ d ]; _dummyList[:] = []; del _dummyList
   pass  
Exemple #59
0
def create_cobra_model_from_sbml_file(sbml_filename, old_sbml=False, legacy_metabolite=False,
                                      print_time=False, use_hyphens=False):
    """convert an SBML XML file into a cobra.Model object.  Supports
    SBML Level 2 Versions 1 and 4

    sbml_filename: String.
    
    old_sbml:  Boolean. Set to True if the XML file has metabolite
    formula appended to metabolite names.  This was a poorly designed
    artifact that persists in some models.

    legacy_metabolite: Boolean.  If True then assume that the metabolite id has
    the compartment id appended after an underscore (e.g. _c for cytosol).  This
    has not been implemented but will be soon.

    print_time:  Boolean.  Print the time requirements for different sections

    use_hyphens:   Boolean.  If True, double underscores (__) in an SBML ID will be converted to hyphens

	
    """
     # Ensure that the file exists
    if not isfile(sbml_filename):
        raise IOError('Your SBML file is not found: %s'%sbml_filename)
    #Expressions to change SBML Ids to Palsson Lab Ids
    metabolite_re = re.compile('^M_')
    reaction_re = re.compile('^R_')
    compartment_re = re.compile('^C_')
    if print_time:
        start_time = time()
    model_doc = readSBML(sbml_filename)
    if print_time:
       print 'Loading %s took %1.2f seconds'%(sbml_filename,
                                              time()-start_time)
                                             
     
    sbml_model = model_doc.getModel()
    sbml_model_id = sbml_model.getId()
    sbml_species = sbml_model.getListOfSpecies()
    sbml_reactions = sbml_model.getListOfReactions()
    sbml_compartments = sbml_model.getListOfCompartments()
    compartment_dict = dict([(compartment_re.split(x.getId())[-1], x.getName())
                             for x in sbml_compartments])
    if legacy_metabolite:
        #Deal with the palsson lab appending the compartment id to the metabolite id
        new_dict = {}
        for the_id, the_name in compartment_dict.items():
            if the_name == '':
                new_dict[the_id[0].lower()] = the_id
            else:
                new_dict[the_id] = the_name
        compartment_dict = new_dict
        legacy_compartment_converter = dict([(v,k)
                                             for k, v in compartment_dict.items()])
    if print_time:
        start_time = time()
    metabolite_dict = {}
    #Convert sbml_metabolites to cobra.Metabolites
    for sbml_metabolite in sbml_species:
        #Skip sbml boundary species
        if sbml_metabolite.getBoundaryCondition():
            continue

        if (old_sbml or legacy_metabolite) and \
               sbml_metabolite.getId().endswith('_b'):
            #Deal with incorrect sbml from bigg.ucsd.edu
            continue
        tmp_metabolite = Metabolite()
        metabolite_id = tmp_metabolite.id = sbml_metabolite.getId()
        tmp_metabolite.compartment = compartment_re.split(sbml_metabolite.getCompartment())[-1]
        if legacy_metabolite:
            if tmp_metabolite.compartment not in compartment_dict:
                tmp_metabolite.compartment = legacy_compartment_converter[tmp_metabolite.compartment]
            tmp_metabolite.id = parse_legacy_id(tmp_metabolite.id, tmp_metabolite.compartment,
                                                use_hyphens=use_hyphens)
        if use_hyphens:
            tmp_metabolite.id = metabolite_re.split(tmp_metabolite.id)[-1].replace('__','-')
        else:
            #Just in case the SBML ids are ill-formed and use -
            tmp_metabolite.id = metabolite_re.split(tmp_metabolite.id)[-1].replace('-','__')
        tmp_metabolite.name = sbml_metabolite.getName()
        tmp_formula = ''
        tmp_metabolite.charge = sbml_metabolite.getCharge()
        tmp_metabolite.notes = parse_legacy_sbml_notes(sbml_metabolite.getNotesString())
        for the_key in tmp_metabolite.notes.keys():
            if the_key.lower() == 'formula':
                tmp_formula = tmp_metabolite.notes.pop(the_key)[0]
                break
        if tmp_formula == '' and old_sbml:
            tmp_formula = tmp_metabolite.name.split('_')[-1]
            tmp_metabolite.name = tmp_metabolite.name[:-len(tmp_formula)-1]
        tmp_metabolite.formula = Formula(tmp_formula)
        metabolite_dict.update({metabolite_id: tmp_metabolite})
    if print_time:
       print 'Parsing %s took %1.2f seconds'%('metabolites',
                                              time()-start_time)


    if print_time:
        start_time = time()
    #Construct the vectors and matrices for holding connectivity and numerical info
    #to feed to the cobra toolbox.
    #Always assume steady state simulations so b is set to 0
    cobra_reaction_list = []
    for sbml_reaction in sbml_reactions:
        if use_hyphens:
            #Change the ids to match conventions used by the Palsson lab.
            reaction = Reaction(reaction_re.split(sbml_reaction.getId())[-1].replace('__','-'))
        else:
            #Just in case the SBML ids are ill-formed and use -
            reaction = Reaction(reaction_re.split(sbml_reaction.getId())[-1].replace('-','__'))
        cobra_reaction_list.append(reaction)
        reaction.exchange_reaction = 0
        reaction.name = sbml_reaction.getName()
        cobra_metabolites = {}
        #Use the cobra.Metabolite class here
        for sbml_metabolite in sbml_reaction.getListOfReactants():
            tmp_metabolite_id = sbml_metabolite.getSpecies()
            #This deals with boundary metabolites
            if tmp_metabolite_id in metabolite_dict:
                tmp_metabolite = deepcopy(metabolite_dict[tmp_metabolite_id])
                cobra_metabolites[tmp_metabolite] = -sbml_metabolite.getStoichiometry()
            else:
                reaction.boundary = 'system_boundary'
        for sbml_metabolite in sbml_reaction.getListOfProducts():
            tmp_metabolite_id = sbml_metabolite.getSpecies()
            #This deals with boundary metabolites
            if tmp_metabolite_id in metabolite_dict:
                tmp_metabolite = deepcopy(metabolite_dict[tmp_metabolite_id])
                cobra_metabolites[tmp_metabolite] = sbml_metabolite.getStoichiometry()
            else:
                reaction.boundary = 'system_boundary'

        #Parse the kinetic law info here.
        parameter_dict = {}
        #            if isinstance(the_reaction.getKineticLaw(), NoneType):
        if not sbml_reaction.getKineticLaw():
            parameter_dict['lower_bound'] = -1000 
            parameter_dict['upper_bound'] = 1000 
            parameter_dict['objective_coefficient'] = 0 
        else:
            for sbml_parameter in sbml_reaction.getKineticLaw().getListOfParameters():
                parameter_dict[sbml_parameter.getId().lower()] = sbml_parameter.getValue()

        if 'lower_bound' in parameter_dict:
            the_key = 'lower_bound'
        elif 'lower bound' in parameter_dict:
            the_key = 'lower bound'
        reaction.lower_bound = parameter_dict[the_key]
        if 'upper_bound' in parameter_dict:
            the_key = 'upper_bound'
        elif 'upper bound' in parameter_dict:
            the_key = 'upper bound'
        reaction.upper_bound = parameter_dict[the_key]
        if 'objective_coefficient' in parameter_dict:
            the_key = 'objective_coefficient'
        elif 'objective coefficient' in parameter_dict:
            the_key = 'objective coefficient'
        reaction.objective_coefficient = parameter_dict[the_key]
        reaction_note_dict = parse_legacy_sbml_notes(sbml_reaction.getNotesString())
        #Parse the reaction notes.
        #POTENTIAL BUG: DEALING WITH LEGACY 'SBML' THAT IS NOT IN A
        #STANDARD FORMAT
        #TODO: READ IN OTHER NOTES AND GIVE THEM A reaction_ prefix.
        #TODO: Make sure genes get added as objects
        if reaction_note_dict.has_key('GENE ASSOCIATION'):
            reaction.gene_reaction_rule = reaction_note_dict['GENE ASSOCIATION'][0]
            reaction.parse_gene_association() 
            if reaction_note_dict.has_key('GENE LIST'):
                reaction.systematic_names = reaction_note_dict['GENE LIST'][0]
            elif reaction_note_dict.has_key('GENES') and \
                     reaction_note_dict['GENES'] != ['']:
                reaction.systematic_names = reaction_note_dict['GENES'][0]
            elif reaction_note_dict.has_key('LOCUS'):
                gene_id_to_object = dict([(x.id, x) for x in reaction._genes])
                for the_row in reaction_note_dict['LOCUS']:
                    tmp_row_dict = {}
                    the_row = 'LOCUS:' + the_row.lstrip('_').rstrip('#')
                    for the_item in the_row.split('#'):
                        try:
                            k, v = the_item.split(':')
                            tmp_row_dict[k] = v
                        except ValueError, e:
                            print the_item
                            raise e
                    tmp_locus_id = tmp_row_dict['LOCUS']
                    if 'TRANSCRIPT' in tmp_row_dict:
                            tmp_locus_id = tmp_locus_id + '.' + tmp_row_dict['TRANSCRIPT']
                    gene_id_to_object[tmp_locus_id].name = tmp_row_dict['ABBREVIATION']

        if reaction_note_dict.has_key('SUBSYSTEM'):
            reaction.subsystem = reaction_note_dict['SUBSYSTEM'][0]   

        reaction.reversibility = int(sbml_reaction.getReversible())
        #TODO: Use the cobra.metabolite objects here.
        reaction.add_metabolites(cobra_metabolites)