示例#1
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()
示例#2
0
def read_sbml(
    source: Union[Path, str],
    promote: bool = False,
    validate: bool = False,
    log_errors: bool = True,
    units_consistency: bool = True,
    modeling_practice: bool = True,
    internal_consistency: bool = True,
) -> libsbml.SBMLDocument:
    """Read SBMLDocument from given source.

    :param source: SBML path or string
    :param promote: promote local parameters to global parameters
    :param validate: validate file
    :param log_errors: validation flag
    :param units_consistency: validation flag
    :param modeling_practice: validation flag
    :param internal_consistency: validation flag

    :return: SBMLDocument
    """
    if isinstance(source, str) and "<sbml" in source:
        doc = libsbml.readSBMLFromString(source)
    else:
        if not isinstance(source, Path):
            logger.error(f"All SBML paths should be of type 'Path', but "
                         f"'{type(source)}' found for: {source}")
            source = Path(source)

        doc = libsbml.readSBMLFromFile(
            str(source))  # type: libsbml.SBMLDocument

    # promote local parameters
    if promote:
        doc = promote_local_variables(doc)  # type: libsbml.SBMLDocument

    # check for errors
    if doc.getNumErrors() > 0:
        if doc.getError(0).getErrorId() == libsbml.XMLFileUnreadable:
            err_message = f"Unreadable SBML file"
        elif doc.getError(0).getErrorId() == libsbml.XMLFileOperationError:
            err_message = "Problems reading SBML file: XMLFileOperationError"
        else:
            err_message = "SBMLDocumentErrors encountered while reading the SBML file."

        validation.log_sbml_errors_for_doc(doc)
        err_message = f"read_sbml error '{source}': {err_message}"
        logger.error(err_message)

    if validate:
        validation.validate_doc(
            doc=doc,
            name=source,
            log_errors=log_errors,
            units_consistency=units_consistency,
            modeling_practice=modeling_practice,
            internal_consistency=internal_consistency,
        )

    return doc
示例#3
0
    def create_parts(self):
        import libsbml
        from tellurium.analysis import _annotations
        self.set_visible(3)
        uri_id = self.widgets['ontologyResults'].value
        if self.widgets['ontologySelect'].value == 'ChEBI':
            matched_ids = self.bm.getModelsIdByChEBIId(uri_id)
        elif self.widgets['ontologySelect'].value == 'GO':
            matched_ids = self.bm.getModelsIdByGO(uri_id)
        else:
            raise Exception('No ontology selected')
        if not matched_ids:
            print 'No biomodels containing %s' % uri_id
            return

        self.matched_sbml = [libsbml.readSBMLFromString(
            self.bm.getModelSBMLById(id).encode('utf-8'))
            for id in matched_ids]
        self.matched_sbml_lookup = dict(zip(matched_ids, self.matched_sbml))
        self.matched_reactions = [_annotations.matching_reactions(sbml, uri_id)
                                  for sbml in self.matched_sbml]
        values = {}
        for r in sum(self.matched_reactions, []):
            msg = '%s: %s' % (
                _annotations.get_biomodel_id(r.model.getSBMLDocument()),
                r.__str__())
            values[msg] = r

        self.widgets['reactionResults'].values = values
示例#4
0
def update_node_dimensions(sbml_layout,
                           fig_dpi,
                           fig_width_pixels,
                           fig_height_pixels,
                           node_multiplier=1.0):
    """Increase the size of the node boxes, if necessary, to fit the text.

    Args:
        sbml_layout (libsbml_draw.model.SBMLlayout): current SBML model
        fig_dpi (int): dots-per-inch setting for the figure
        fig_width_pixels (int): width of the figure in pixels
        fig_height_pixels (int): height of the figure in pixels
        node_multiplier (optional, float): multiplier to achieve a width of
                the node box beyond what's needed for the text itself, eg. 1.1
                represents an extra 10%

    Returns: None
    """
    nodes = sbml_layout._SBMLlayout__network.nodes.values()

    nw_width_data_coords = (max([node.center.x for node in nodes]) -
                            min([node.center.x
                                 for node in nodes])) + SBNW_NODE_WIDTH

    nw_height_data_coords = (max([node.center.y for node in nodes]) -
                             min([node.center.y
                                  for node in nodes])) + SBNW_NODE_HEIGHT

    for node in nodes:

        width, height = compute_node_dimensions(
            node_multiplier * (len(node.name) + 0) * node.font_size,
            node_multiplier * (node.font_size + 0), fig_dpi, fig_width_pixels,
            fig_height_pixels, nw_width_data_coords, nw_height_data_coords)

        h_node_id = node.id.encode('utf-8')
        h_node = sbnw.nw_getNodepFromId(sbml_layout._SBMLlayout__h_network,
                                        h_node_id)

        sbnw.node_setWidth(h_node, width)
        node.width = width

        sbnw.node_setHeight(h_node, height)
        node.height = height

        node.lower_left_point = [
            node.center.x - node.width / 2, node.center.y - node.height / 2
        ]


#    h_reaction = sbnw.nw_getReactionp(self.__h_network, nr)
#    sbnw.reaction_recenter(h_reaction)

#    sbnw.nw_recenterJunctions(sbml_layout._SBMLlayout__h_network)
#    sbnw.nw_rebuildCurves(sbml_layout._SBMLlayout__h_network)

#    sbml_layout._SBMLlayout__updateNetworkLayout()
    sbml_layout._SBMLlayout__doc = libsbml.readSBMLFromString(
        sbml_layout._SBMLlayout__getSBMLWithLayoutString())
示例#5
0
def get_initial_assignments_dict(model):
    sbml = model.getSBML()
    sbml_document = libsbml.readSBMLFromString(sbml)
    sbml_model = sbml_document.getModel()
    assignments = {}
    for ia in sbml_model.getListOfInitialAssignments():
        assignments[ia.getId()] = libsbml.formulaToString(ia.getMath())
    return assignments
示例#6
0
def readrpSBMLtar(inputTar):
    rpsbml_paths = {}
    with tarfile.open(inputTar) as tar:
        for member in tar.getmembers():
            rpsbml_paths[member.name] = rpRanker.rpSBML(
                member.name,
                libsbml.readSBMLFromString(
                    tar.extractfile(member).read().decode("utf-8")))
    return rpsbml_paths
示例#7
0
文件: sbml.py 项目: superssnails/edd
 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
         contents = self.sbml_file.file.file.read()
         import libsbml
         self._sbml_document = libsbml.readSBMLFromString(contents)
     return self._sbml_document
示例#8
0
def runSingleSBML(rpcofactors, member_name, rpsbml_string, path_id,
                  compartment_id):
    #open one of the rp SBML files
    rpsbml = rpSBML.rpSBML(member_name,
                           libsbml.readSBMLFromString(rpsbml_string))
    #rpcofactors = rpRanker.rpCofactors()
    if rpcofactors.addCofactors(rpsbml, compartment_id, path_id):
        return libsbml.writeSBMLToString(rpsbml.document).encode('utf-8')
    else:
        return ''
示例#9
0
def biomodels_info():
    '''
    fetch latest biomodels release from ftp
    extract
    parse all curated models
    '''
    import ftplib
    import tarfile
    import libsbml
    import re
    import os

    if not os.path.exists('release.tar.bz2'):

        ftp = ftplib.FTP("ftp.ebi.ac.uk")
        ftp.login()
        ftp.cwd("/pub/databases/biomodels/releases/latest/")
        file_list = []
        ftp.dir(file_list.append)
        ftp_file = [x for x in file_list if x.endswith('pub-sbml_files.tar.bz2')][0].split()[-1]
        try:
            ftp.retrbinary('RETR %s' % ftp_file, open('release.tar.bz2', 'wb').write)
        except ftplib.error_perm:
            print 'ERROR: cannot read file "%s"' % ftp_file
            import os
            os.unlink(ftp_file)
            return
        #print '*** Downloaded "%s" to CWD' % ftp_file
    else:
        print 'used release.tar.bz2 in current folder! remove to redownload'

    #Unpack and read info
    tar = tarfile.open('release.tar.bz2', 'r:bz2')
    curated_files = [x for x in tar.getnames() if '/curated/' in x]
    items = []
    notes_items = []
    for fn in curated_files:
        #print fn[-19:-4]
        try: 
            cur_file = tar.extractfile(fn).read()
            doc = libsbml.readSBMLFromString(cur_file)
            model = doc.getModel()
            notes = re.sub('body', 'div', model.getNotes().getChild(0).toXMLString()) 
            model_id = fn[-19:-4]
            name = model.getName() 
            items.append([model_id, '<li><q><span bla="%s">%s: %s</span> <a href="{{=URL(r=request,f="biomodels_info_notes.html#%s")}}" target="_blank">notes</a></q></li>' % (model_id, model_id, name, model_id)])
            notes_items.append('<div id="%s">%s</div>' % (model_id, notes))
        except:
            pass
        #print model.getName(), model.getId(), 
    items.sort()
    biomodels_list = "<ul class='biomodels_select'>%s\n</ul>" % "\n".join([x for y,x in items])
    notes = "<div class='biomodels_notes'>%s</div><br/><br/><br/><br/><br/><br/><br/><br/>" % ''.join(notes_items)
    open('biomodels_info_list.html', 'w').write(biomodels_list)
    open('biomodels_info_notes.html', 'w').write(notes)
示例#10
0
def libSBML_read():

    with open(file_path, 'r') as file:
        SBML = file.read()
        SBML = libsbml.readSBMLFromString(SBML)

    model = SBML.getModel()

    species = model.getListOfSpecies()

    print(species.get(1))
示例#11
0
def translate():
    data = request.get_json()
    sbml = data.get('sbml')
    doc = libsbml.readSBMLFromString(sbml.encode('utf-8'))
    if doc.getNumErrors() > 0:
        messages = ['Invalid SBML!\n']
        for i in xrange(0, doc.getNumErrors()):
            error = doc.getError(i)
            messages.append(error.getMessage())
        return ''.join(messages)
    else:
        return sbml
示例#12
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

            with self.sbml_file.file.open() as upload:
                text = upload.read().decode("utf-8")
                self._sbml_document = libsbml.readSBMLFromString(text)
        return self._sbml_document
示例#13
0
 def __init__(self, sbml):
     '''
     sbml -- an SBML string, libsbml.SBMLDocument object, or libsbml.Model object
 
     '''
     
     if isinstance(sbml, basestring):
         self.doc = libsbml.readSBMLFromString(sbml)
         self.model = self.doc.getModel()
     elif isinstance(sbml, libsbml.SBMLDocument):
         self.doc = sbml
         self.model = self.doc.getModel()
     elif isinstance(sbml, libsbml.Model):
         self.model = sbml
     else:
         raise Exception('SBML Input is not valid')
 
     self.G = nx.DiGraph()
     self.labels = {}
     self.species = []
     self.reactions = []
     for i, s in enumerate(self.model.species):
         self.G.add_node(s.getId())
         self.species.append(s.getId())
     for i, r in enumerate(self.model.reactions):
         self.G.add_node(r.getId())
         self.reactions.append(r.getId())
         for s in r.reactants:
             self.G.add_edge(s.getSpecies(), r.getId(), kind='reactant')
         for s in r.products:
             self.G.add_edge(r.getId(), s.getSpecies(), kind='product')
         for s in r.modifiers:
             self.G.add_edge(s.getSpecies(), r.getId(), kind='modifier')
     
     self.modifier_edges = [key for key, val in nx.get_edge_attributes(self.G, 'kind').items() if val == 'modifier']
     self.product_edges = [key for key, val in nx.get_edge_attributes(self.G, 'kind').items() if val == 'product']
     self.reactant_edges = [key for key, val in nx.get_edge_attributes(self.G, 'kind').items() if val == 'reactant']
     #mass_transfer_edges = [key for key, val in nx.get_edge_attributes(G, 'kind').items() if val != 'modifier']
     
     # Default drawing options
     self.options = {}
     self.options['species'] = {
         'size': 500,
         'color': 'r',
         'alpha': 0.8,
         'label_size': 16
     }
     self.options
 def __init__(self, sbml):
     '''
     Initialize with from either SBML string or SBML Document object
     '''
     import libsbml
     if isinstance(sbml, libsbml.SBMLDocument):
         self.document = sbml
     elif isinstance(sbml, basestring):
         self.document = libsbml.readSBMLFromString(sbml)
     else:
         raise Exception("Model is not a string or SBML document object")
     
     
     if self.document.getNumErrors() > 0:
         raise Exception('SBML document contains erros')
     self.model = self.document.getModel()
示例#15
0
def get_model_from_gzip_sbml(stream: bytes) -> "Model":
    """
    Generate a model instance from a gzip-compressed, UTF-8 encoded SBML document.

    Parameters
    ----------
    stream : bytes
        A gzip-compressed, UTF-8 encoded SBML document.

    Returns
    -------
    Model
        A model instance generated from the SBML document.

    """
    return _sbml_to_model(
        libsbml.readSBMLFromString(gzip.decompress(stream).decode("utf-8")))
示例#16
0
    def __init__(self, sbml,
                 species={},
                 reactions={},
                 reactants={},
                 products={},
                 modifiers={}):
        '''
        sbml -- an SBML string, libsbml.SBMLDocument object, or
        libsbml.Model object
        '''
        import pygraphviz as pgv
        import libsbml

        if isinstance(sbml, basestring):
            self.doc = libsbml.readSBMLFromString(sbml)
            self.model = self.doc.getModel()
        elif isinstance(sbml, libsbml.SBMLDocument):
            self.doc = sbml
            self.model = self.doc.getModel()
        elif isinstance(sbml, libsbml.Model):
            self.model = sbml
        else:
            raise Exception('SBML Input is not valid')

        self.G = pgv.AGraph(strict=False, directed=True)

        for i, s in enumerate(self.model.species):
            if s.getName():
                label = s.getName() + ' ({})'.format(s.getId())
            else:
                label = s.getId()
            self.G.add_node(s.getId(), label=label, **species)
        for i, r in enumerate(self.model.reactions):
            if r.getName():
                label = r.getName() + ' ({})'.format(r.getId())
            else:
                label = r.getId()
            self.G.add_node(r.getId(), label=label, **reactions)
            for s in r.reactants:
                self.G.add_edge(s.getSpecies(), r.getId(), **reactants)
            for s in r.products:
                self.G.add_edge(r.getId(), s.getSpecies(), **products)
            for s in r.modifiers:
                self.G.add_edge(s.getSpecies(), r.getId(), **modifiers)
示例#17
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))
示例#18
0
def species_df(r: roadrunner.RoadRunner) -> pd.DataFrame:
    """
    Create FloatingSpecies DataFrame.
    :return: pandas DataFrame
    """
    r_model = r.model  # type: roadrunner.ExecutableModel
    sbml_str = r.getCurrentSBML()

    doc = libsbml.readSBMLFromString(sbml_str)  # type: libsbml.SBMLDocument
    model = doc.getModel()  # type: libsbml.Model

    sids = r_model.getFloatingSpeciesIds() + r_model.getBoundarySpeciesIds()
    species = [model.getSpecies(sid)
               for sid in sids]  # type: List[libsbml.Species]

    data = {
        'sid':
        sids,
        'concentration':
        np.concatenate([
            r_model.getFloatingSpeciesConcentrations(),
            r_model.getBoundarySpeciesConcentrations()
        ],
                       axis=0),
        'amount':
        np.concatenate([
            r.model.getFloatingSpeciesAmounts(),
            r.model.getBoundarySpeciesAmounts()
        ],
                       axis=0),
        'unit': [s.getUnits() for s in species],
        'constant': [s.getConstant() for s in species],
        'boundaryCondition': [s.getBoundaryCondition() for s in species],
        'name': [s.getName() for s in species],
    }

    return pd.DataFrame(data,
                        columns=[
                            'sid', 'concentration', 'amount', 'unit',
                            'constant', 'boundaryCondition', 'species', 'name'
                        ])
示例#19
0
def clamp_species(r: roadrunner.RoadRunner,
                  sids,
                  boundary_condition=True) -> roadrunner.RoadRunner:
    """ Clamp/Free specie(s) via setting boundaryCondition=True/False.

    This requires changing the SBML and ODE system.

    :param r: roadrunner.RoadRunner
    :param sids: sid or iterable of sids
    :param boundary_condition: boolean flag to clamp (True) or free (False) species
    :return: modified roadrunner.RoadRunner
    """
    # get model for current SBML state
    sbml_str = r.getCurrentSBML()
    doc = libsbml.readSBMLFromString(sbml_str)  # type: libsbml.SBMLDocument
    model = doc.getModel()  # type: libsbml.Model

    if isinstance(sids, str):
        sids = [sids]

    for sid in sids:
        # set boundary conditions
        sbase = model.getElementBySId(sid)  # type: libsbml.SBase
        if not sbase:
            logging.error("No element for SId in model: {}".format(sid))
            return None
        else:
            if sbase.getTypeCode() == libsbml.SBML_SPECIES:
                species = sbase  # type: libsbml.Species
                species.setBoundaryCondition(boundary_condition)
            else:
                logging.error(
                    "SId in clamp does not match species: {}".format(sbase))
                return None

    # create modified roadrunner instance
    sbmlmod_str = libsbml.writeSBMLToString(doc)
    rmod = load_model(sbmlmod_str)  # type: roadrunner.RoadRunner
    set_timecourse_selections(rmod, r.timeCourseSelections)

    return rmod
示例#20
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 ) )
示例#21
0
def create(id, DIR_REPOS, VERSION):
    '''
    Generates repo contents for a specific model
    '''
    import bioservices
    import _template as t
    s = bioservices.BioModels()

    sbml = s.getModelSBMLById(id)
    mkdirp(os.path.join(DIR_REPOS, id, id))
    
    setup_params = {
        'name': id,
        'version': VERSION,
        'description': '%s from BioModels' % id,
        'url': 'http://www.ebi.ac.uk/biomodels-main/%s' % id
    }
    
    model_params = {
        'path': '%s.xml' % id
    }
    
    init_params = {}
    
    import libsbml
    doc = libsbml.readSBMLFromString(sbml.encode('utf-8'))
    model = doc.getModel()
    notes = h.handle(model.getNotesString().decode('utf-8'))
    
    with open(os.path.join(DIR_REPOS, id, 'setup.py'), 'w') as f:
        f.write(t.setuppy_template(setup_params))
    with open(os.path.join(DIR_REPOS, id, id, 'model.py'), 'w') as f:
        f.write(t.modelpy_template(model_params))
    with open(os.path.join(DIR_REPOS, id, id, id + '.xml'), 'w') as f:
        f.write(sbml.encode('utf-8'))
    with open(os.path.join(DIR_REPOS, id, id, '__init__.py'), 'w') as f:
        f.write(t.initpy_template(init_params))
    with open(os.path.join(DIR_REPOS, id, 'README.md'), 'w') as f:
        f.write(notes.encode('utf-8'))
示例#22
0
def parameter_df(r: roadrunner.RoadRunner) -> pd.DataFrame:
    """
    Create GlobalParameter DataFrame.
    :return: pandas DataFrame
    """
    r_model = r.model  # type: roadrunner.ExecutableModel
    doc = libsbml.readSBMLFromString(
        r.getCurrentSBML())  # type: libsbml.SBMLDocument
    model = doc.getModel()  # type: libsbml.Model
    sids = r_model.getGlobalParameterIds()
    parameters = [model.getParameter(sid)
                  for sid in sids]  # type: List[libsbml.Parameter]
    data = {
        'sid': sids,
        'value': r_model.getGlobalParameterValues(),
        'unit': [p.units for p in parameters],
        'constant': [p.constant for p in parameters],
        'name': [p.name for p in parameters],
    }
    df = pd.DataFrame(data,
                      columns=['sid', 'value', 'unit', 'constant', 'name'])
    return df
示例#23
0
 def __init__(self,
              sbml,
              species={},
              reactions={},
              reactants={},
              products={},
              modifiers={}):
     """
     :param sbml: SBML string, libsbml.SBMLDocument object, or libsbml.Model object
     :param species:
     :type species:
     :param reactions:
     :type reactions:
     :param reactants:
     :type reactants:
     :param products:
     :type products:
     :param modifiers:
     :type modifiers:
     """
     # load model
     if isinstance(sbml, basestring):
         self.doc = libsbml.readSBMLFromString(sbml)
         self.model = self.doc.getModel()
     elif isinstance(sbml, libsbml.SBMLDocument):
         self.doc = sbml
         self.model = self.doc.getModel()
     elif isinstance(sbml, libsbml.Model):
         self.model = sbml
     else:
         raise Exception('SBML Input is not valid')
     # create graph
     self.g = SBMLDiagram._createGraph(self.model,
                                       species=species,
                                       reactions=reactions,
                                       reactants=reactants,
                                       products=products,
                                       modifiers=modifiers)
示例#24
0
    def __init__(self, sbmlFileContents=None, exceptionOnError=True):

        self.model_name = None
        self.model_notes = {}

        self.metList = None
        self.reactionList = None

        self.initialSetFluxesCount = None
        self.initialBoundedFluxesCount = None
        self.initialCloselyBoundedFluxesCount = None

        self.errorCount = 0
        self.logStrings = []

        if not isinstance(sbmlFileContents, basestring):
            self.errorCount = 1
            self.logStrings = [
                'No SBML string provided (object is not a string).'
            ]
        elif sbmlFileContents.strip() == '':
            self.errorCount = 1
            self.logStrings = ['No SBML string provided (string is empty).']
        else:
            # Not saving a local pointer to sbmlDoc, in order to circumvent this error when attempting to deepcopy:
            # TypeError: object.__new__(SwigPyObject) is not safe, use SwigPyObject.__new__()
            sbmlDoc = libsbml.readSBMLFromString(sbmlFileContents)
            self.errorCount = sbmlDoc.getNumErrors()
            if self.errorCount:
                errs = sbmlDoc.getErrorLog()
                for x in range(self.errorCount):
                    err = errs.getError(x)
                    self.logStrings.append(err.getMessage())
            self.parseSBMLDoc(sbmlDoc)

        if self.errorCount > 0 and exceptionOnError:
            raise Exception('Errors parsing SBML:\n%s' %
                            ('\n'.join(self.logStrings)))
示例#25
0
 def __init__(self, sbml,
              species={},
              reactions={},
              reactants={},
              products={},
              modifiers={}):
     """
     :param sbml: SBML string, libsbml.SBMLDocument object, or libsbml.Model object
     :param species:
     :type species:
     :param reactions:
     :type reactions:
     :param reactants:
     :type reactants:
     :param products:
     :type products:
     :param modifiers:
     :type modifiers:
     """
     # load model
     if isinstance(sbml, basestring):
         self.doc = libsbml.readSBMLFromString(sbml)
         self.model = self.doc.getModel()
     elif isinstance(sbml, libsbml.SBMLDocument):
         self.doc = sbml
         self.model = self.doc.getModel()
     elif isinstance(sbml, libsbml.Model):
         self.model = sbml
     else:
         raise Exception('SBML Input is not valid')
     # create graph
     self.g = SBMLDiagram._createGraph(self.model,
                                       species=species,
                                       reactions=reactions,
                                       reactants=reactants,
                                       products=products,
                                       modifiers=modifiers)
def runSingleSBML(member_name, rpsbml_string, inSBML, isMerge, path_id):
    #open one of the rp SBML files
    input_rpsbml = rpSBML.rpSBML('inputMergeModel',
                                 libsbml.readSBMLFromFile(inSBML))
    rpsbml = rpSBML.rpSBML(member_name,
                           libsbml.readSBMLFromString(rpsbml_string))
    #read the input GEM sbml model
    #input_rpsbml = rpSBML.rpSBML('inputMergeModel', libsbml.readSBMLFromString(inSBML_string))
    #print(input_rpsbml)
    #print(input_rpsbml.model)
    rpsbml.mergeModels(input_rpsbml.model)
    rpfba = rpFBA.rpFBA(input_rpsbml)
    rpfba.allObj(path_id)
    if isMerge:
        ##### pass FBA results to the original model ####
        groups = rpfba.rpsbml.model.getPlugin('groups')
        rp_pathway = groups.getGroup(path_id)
        for member in rp_pathway.getListOfMembers():
            reacFBA = rpfba.rpsbml.model.getReaction(member.getIdRef())
            reacIN = rpsbml.model.getReaction(member.getIdRef())
            reacIN.setAnnotation(reacFBA.getAnnotation())
        return libsbml.writeSBMLToString(rpsbml.document).encode('utf-8')
    else:
        return libsbml.writeSBMLToString(input_rpsbml.document).encode('utf-8')
示例#27
0
    def _parameters_for_sensitivity(r, exclude_filter=None,
                                    exclude_zero: bool = True,
                                    zero_eps: float = 1E-8):
        """ Get parameter ids for sensitivity analysis.

        Values around current model state are used.

        :param r:
        :param exclude_filter: filter function to exclude parameters
        :param exclude_zero: exclude parameters which are zero
        :return:
        """
        doc = libsbml.readSBMLFromString(
            r.getSBML())  # type: libsbml.SBMLDocument
        model = doc.getModel()  # type: libsbml.Model

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

        # filter parameters
        parameters = OrderedDict()
        for pid in sorted(pids_const):
            if exclude_filter and exclude_filter(pid):
                continue

            value = r[pid]
            if exclude_zero:
                if np.abs(value) < zero_eps:
                    continue

            parameters[pid] = value

        return parameters
示例#28
0
    def test_sbml(self):
        fwd = Direction.forward()
        rev = Direction.reversible()

        a = M("A_c")
        b = M("B_c")
        c = M("C_e")
        e = M("E_e", boundary=True)

        model = Model()
        model.reactions = [
            R("R1", 1*a, 3*b, direction=fwd, bounds=Bounds(-100, 100)),
            R("R2", 1*c, 3*b, direction=fwd, bounds=Bounds(-100, 100)),
            R("R3", 1*b + 1*c, 1*e, direction=rev, bounds=Bounds(-100, 100))]

        import libsbml
        import converter
        sbml = converter.Bioopt2SbmlConverter().convert(model)
        sbml_export = libsbml.writeSBMLToString(sbml)

        doc = libsbml.readSBMLFromString(sbml_export)
        self.assertEquals(0, doc.getNumErrors())

        exp_export = """<?xml version="1.0" encoding="UTF-8"?>
<sbml xmlns="http://www.sbml.org/sbml/level2/version3" level="2" version="3">
  <model>
    <listOfUnitDefinitions>
      <unitDefinition id="mmol_per_gDW_per_hr">
        <listOfUnits>
          <unit kind="mole" scale="-3"/>
          <unit kind="second" exponent="-1" multiplier="0.00027778"/>
        </listOfUnits>
      </unitDefinition>
    </listOfUnitDefinitions>
    <listOfCompartments>
      <compartment id="C_0001" name="c"/>
      <compartment id="C_0002" name="e"/>
    </listOfCompartments>
    <listOfSpecies>
      <species id="M_0001_c" name="A_c" compartment="C_0001" initialAmount="0" boundaryCondition="false"/>
      <species id="M_0002_b" name="E_e" compartment="C_0002" initialAmount="0" boundaryCondition="true"/>
      <species id="M_0003_e" name="C_e" compartment="C_0002" initialAmount="0" boundaryCondition="false"/>
      <species id="M_0004_c" name="B_c" compartment="C_0001" initialAmount="0" boundaryCondition="false"/>
    </listOfSpecies>
    <listOfReactions>
      <reaction id="R_0001" name="R1" reversible="false">
        <listOfReactants>
          <speciesReference species="M_0001_c" stoichiometry="1"/>
        </listOfReactants>
        <listOfProducts>
          <speciesReference species="M_0004_c" stoichiometry="3"/>
        </listOfProducts>
        <kineticLaw>
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <ci> FLUX_VALUE </ci>
          </math>
          <listOfParameters>
            <parameter id="LOWER_BOUND" value="-100" units="mmol_per_gDW_per_hr"/>
            <parameter id="UPPER_BOUND" value="100" units="mmol_per_gDW_per_hr"/>
            <parameter id="OBJECTIVE_COEFFICIENT" value="0" units="dimensionless"/>
            <parameter id="FLUX_VALUE" value="0" units="mmol_per_gDW_per_hr"/>
          </listOfParameters>
        </kineticLaw>
      </reaction>
      <reaction id="R_0002" name="R2" reversible="false">
        <listOfReactants>
          <speciesReference species="M_0003_e" stoichiometry="1"/>
        </listOfReactants>
        <listOfProducts>
          <speciesReference species="M_0004_c" stoichiometry="3"/>
        </listOfProducts>
        <kineticLaw>
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <ci> FLUX_VALUE </ci>
          </math>
          <listOfParameters>
            <parameter id="LOWER_BOUND" value="-100" units="mmol_per_gDW_per_hr"/>
            <parameter id="UPPER_BOUND" value="100" units="mmol_per_gDW_per_hr"/>
            <parameter id="OBJECTIVE_COEFFICIENT" value="0" units="dimensionless"/>
            <parameter id="FLUX_VALUE" value="0" units="mmol_per_gDW_per_hr"/>
          </listOfParameters>
        </kineticLaw>
      </reaction>
      <reaction id="R_0003" name="R3" reversible="true">
        <listOfReactants>
          <speciesReference species="M_0004_c" stoichiometry="1"/>
          <speciesReference species="M_0003_e" stoichiometry="1"/>
        </listOfReactants>
        <listOfProducts>
          <speciesReference species="M_0002_b" stoichiometry="1"/>
        </listOfProducts>
        <kineticLaw>
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <ci> FLUX_VALUE </ci>
          </math>
          <listOfParameters>
            <parameter id="LOWER_BOUND" value="-100" units="mmol_per_gDW_per_hr"/>
            <parameter id="UPPER_BOUND" value="100" units="mmol_per_gDW_per_hr"/>
            <parameter id="OBJECTIVE_COEFFICIENT" value="0" units="dimensionless"/>
            <parameter id="FLUX_VALUE" value="0" units="mmol_per_gDW_per_hr"/>
          </listOfParameters>
        </kineticLaw>
      </reaction>
    </listOfReactions>
  </model>
</sbml>
"""

        exp_export = sbml_export # TODO: we have a stochioustic processes in metabolite id generation so strings can't be used to assert
        self.assertEquals(exp_export, sbml_export)
示例#29
0
def flattenExternalModelDefinitions(doc):
    """ Converts all ExternalModelDefinitions to ModelDefinitions.

    I.e. the definition of models in external files are read
    and directly included in the top model. The resulting
    comp model consists than only of a single file.

    The model refs in the submodel do not change in the process,
    so no need to update the submodels.

    :param doc: SBMLDocument
    :return: SBMLDocument with ExternalModelDefinitions replaced
    """
    # FIXME: handle /multiple levels of hierarchies recursively (ExternalModelDefinitions of submodels)

    model = doc.getModel()
    if model is None:
        return doc

    comp_doc = doc.getPlugin("comp")
    emd_list = comp_doc.getListOfExternalModelDefinitions()

    # no ExternalModelDefinitions
    if (emd_list is None) or (len(emd_list) == 0):
        return doc

    # ExternalModelDefinitions set as ModelDefinitions
    emd_ids = []
    mds = []
    for emd in emd_list:
        emd_ids.append(emd.getId())

        # get the model definition from the model
        ref_model = emd.getReferencedModel()

        # store model definition
        md = libsbml.ModelDefinition(ref_model)
        mds.append(md)

    packages = []
    for emd in emd_list:
        # get the model definition from the model
        ref_model = emd.getReferencedModel()
        ref_doc = ref_model.getSBMLDocument()
        # print('\n', ref_model)
        for k in range(ref_doc.getNumPlugins()):

            plugin = ref_doc.getPlugin(k)
            uri = plugin.getURI()
            prefix = plugin.getPrefix()
            name = plugin.getPackageName()
            required = None
            if ref_doc.isSetPackageRequired(name):
                required = ref_doc.getPackageRequired(name)

            packages.append({
                'model': ref_model,
                'uri': uri,
                'prefix': prefix,
                'name': name,
                'required': required
            })

    # remove emds from model (do not remove while iterating over the list)
    for emd_id in emd_ids:
        comp_doc.removeExternalModelDefinition(emd_id)

    # activate all the packages
    from pprint import pprint
    pprint(packages)
    for pdict in packages:
        doc.enablePackage(pdict['uri'], pdict['prefix'], True)
        doc.setPackageRequired(pdict['name'], pdict['required'])

    # now add the model definitions
    for md in mds:
        comp_doc.addModelDefinition(md)

    sbml_str = libsbml.writeSBMLToString(doc)
    doc = libsbml.readSBMLFromString(sbml_str)

    # replacement finished, now go through all ModelDefinitions
    # and add things the packages require
    print("-" * 80)
    for k in range(doc.getNumPlugins()):
        plugin = doc.getPlugin(k)
        name = plugin.getPackageName()
        print(name, '\n')
        md_list = comp_doc.getListOfModelDefinitions()
        for md_model in md_list:

            # if a package needs something on
            # a model we have to write it on all ModelDefinitions
            # this will break on a package per package basis ! We know about fbc it needs
            # a strict tag so writing this here
            if name == "fbc":
                # for some ModelDefinitions we don't get the fbc Plugin ???
                fbc_model = md_model.getPlugin(name)

                print('\tModel:', md_model)
                print('\tFBCModelPlugin:', fbc_model, type(fbc_model))

                # setting because it is required (if unlucky additional info required)
                # but we can't set it because we can't access the FBCModelPlugins of the ModelDefinitions
                if fbc_model is not None:
                    if not fbc_model.isSetStrict():
                        fbc_model.setStrict(False)
                else:
                    print(
                        "WARNING: This should never happen. All ModelDefinitions should have a FBCModelPlugin"
                    )

    doc.checkInternalConsistency()
    doc.printErrors()

    return doc
示例#30
0
def convertSBML2EML( aSBMLString ):

    aSBMLDocument = libsbml.readSBMLFromString( aSBMLString )
    aSBMLModel = aSBMLDocument.getModel()

    theModel = SBML_Model( aSBMLDocument, aSBMLModel )
    theCompartment = SBML_Compartment( theModel )
    theParameter = SBML_Parameter( theModel )
    theSpecies = SBML_Species( theModel )
    theRule = SBML_Rule( theModel )
    theReaction = SBML_Reaction( theModel )
#    theEvent = SBML_Event( theModel )

    anEml = Eml()

    # ------------------------------
    #  Set Stepper
    # ------------------------------

    anEml.createStepper( 'ODEStepper', 'DE' )
##    anEml.createStepper( 'ODE45Stepper', 'DE' )


    # ------------------------------
    #  Set Compartment ( System )
    # ------------------------------

    # setFullID
    aSystemFullID='System::/'
    anEml.createEntity( 'System', aSystemFullID )
    anEml.setEntityProperty( aSystemFullID, 'StepperID', ['DE'] )
    anEml.setEntityProperty( aSystemFullID, 'Name', ['Default'] )



    for aCompartment in ( theModel.CompartmentList ):

        # initialize
        theCompartment.initialize( aCompartment )

        # getPath
        if ( theModel.Level == 1 ):
            aPath = theModel.getPath( aCompartment[1] )
        elif ( theModel.Level == 2 ):
            aPath = theModel.getPath( aCompartment[0] )           
        
        # setFullID
        if( aPath == '/' ):
            aSystemFullID = 'System::/'
        else:
            aSystemFullID = theCompartment.getCompartmentID( aCompartment )
            anEml.createEntity( 'System', aSystemFullID )


            # setStepper 
            anEml.setEntityProperty( aSystemFullID, 'StepperID', ['DE'] )


        # setName( default = [] )
        if ( theModel.Level == 2 ):
            if ( aCompartment[1] != '' ):
                anEml.setEntityProperty( aSystemFullID,
                                         'Name',
                                         aCompartment[1:2] )

        # setDimensions( default = 3 )
        aDimensionsFullID = 'Variable:' + aPath + ':Dimensions'
        anEml.createEntity( 'Variable', aDimensionsFullID )
        aTmpList = [ str( aCompartment[2] ) ]
        anEml.setEntityProperty( aDimensionsFullID, 'Value', aTmpList[0:1] )

                  
        # setSIZE
        aSizeFullID = 'Variable:' + aPath + ':SIZE'
        anEml.createEntity( 'Variable', aSizeFullID )

        aSizeValue = theCompartment.getCompartmentSize( aCompartment )
        aSizeUnit = theCompartment.getCompartmentUnit( aCompartment )

        # convert to ECELL Unit
        if ( aSizeUnit != '' ):
            aSizeValue = theModel.convertUnit( aSizeUnit, aSizeValue )

        aTmpList = [ str( aSizeValue ) ]
        anEml.setEntityProperty( aSizeFullID, 'Value', aTmpList[0:1] )


        # setConstant( default = 1 )
        if ( aCompartment[7] == 1 ):
            anEml.setEntityProperty( aSizeFullID, 'Fixed', ['1',] )
           
           
    # ------------------------------
    #  Set GlobalParameter ( Variable )
    # ------------------------------

    if ( theModel.ParameterList != [] ):
    
        # setGlobalParameterSystem
        aSystemFullID='System:/:SBMLParameter'
        anEml.createEntity( 'System', aSystemFullID )
        anEml.setEntityProperty( aSystemFullID, 'StepperID', ['DE'] )
        anEml.setEntityProperty( aSystemFullID, 'Name', ['Global Parameter'] )


    for aParameter in theModel.ParameterList:

        # setFullID
        aSystemFullID = theParameter.getParameterID( aParameter )
        anEml.createEntity( 'Variable', aSystemFullID )
            
        # setName
        if ( aParameter[1] != '' ):
            anEml.setEntityProperty( aSystemFullID, 'Name', aParameter[1:2] )

        # setValue
        aTmpList = [ str( theParameter.getParameterValue( aParameter ) ) ]
        anEml.setEntityProperty( aSystemFullID, 'Value', aTmpList[0:1] )


        # setFixed ( default = 1 )
        if ( aParameter[4] == 1 ):
            # aTmpList = [ str( aParameter[4] ) ]
            aTmpList = [ '1' ]
            anEml.setEntityProperty( aSystemFullID, 'Fixed', aTmpList[0:1] )


    # ------------------------------
    #  Set Species ( Variable )
    # ------------------------------

    for aSpecies in theModel.SpeciesList:
        
        ### setFullID ###
        
        aSystemFullID = theSpecies.getSpeciesID( aSpecies )
        anEml.createEntity( 'Variable', aSystemFullID )


        ### setName ###
        
        if( theModel.Level == 2 ):

            if ( aSpecies[1] != '' ):
                anEml.setEntityProperty( aSystemFullID, 'Name', aSpecies[1:2] )


        ### setValue ###
        
        aTmpList = [ str( theSpecies.getSpeciesValue( aSpecies ) ) ]
        anEml.setEntityProperty( aSystemFullID, 'Value', aTmpList[0:1] )


        ### setFixed ###

        aConstant = theSpecies.getConstant( aSpecies )
        anEml.setEntityProperty( aSystemFullID,
                                 'Fixed',
                                 [ str( aConstant ) ] )


    # ------------------------------
    #  Set Rule ( Process )
    # ------------------------------

    if ( theModel.RuleList != [] ):

        ### make Rule System ###
        
        aSystemFullID='System:/:SBMLRule'
        anEml.createEntity( 'System', aSystemFullID )
        anEml.setEntityProperty( aSystemFullID,
                                 'Name',
                                 ['System for SBML Rule'] )

        anEml.setEntityProperty( aSystemFullID, 'StepperID', ['DE'] )

        
    for aRule in theModel.RuleList:

        theRule.initialize()

        ### setFullID ###        
        aSystemFullID = theRule.getRuleID()


        ### Algebraic Rule ###
        if ( aRule[0] == libsbml.SBML_ALGEBRAIC_RULE ):

            anEml.createEntity( 'ExpressionAlgebraicProcess', aSystemFullID )


        ### Assignment Rule ###
        elif ( aRule[0] == libsbml.SBML_ASSIGNMENT_RULE or
               aRule[0] == libsbml.SBML_SPECIES_CONCENTRATION_RULE or
               aRule[0] == libsbml.SBML_COMPARTMENT_VOLUME_RULE or
               aRule[0] == libsbml.SBML_PARAMETER_RULE ):

            anEml.createEntity( 'ExpressionAssignmentProcess', aSystemFullID )

            aVariableType = theRule.getVariableType( aRule[2] )

            if ( aVariableType == libsbml.SBML_SPECIES ):
                theRule.setSpeciesToVariableReference( aRule[2], '1' )
            elif ( aVariableType == libsbml.SBML_PARAMETER ):
                theRule.setParameterToVariableReference( aRule[2], '1' )
            elif ( aVariableType == libsbml.SBML_COMPARTMENT ):
                theRule.setCompartmentToVariableReference( aRule[2], '1' )
            else:
                raise TypeError,\
            "Variable type must be Species, Parameter, or Compartment"

        ### Rate Rule ###
        elif ( aRule[0] == libsbml.SBML_RATE_RULE ):

            anEml.createEntity( 'ExpressionFluxProcess', aSystemFullID )

            aVariableType = theRule.getVariableType( aRule[2] )

            if ( aVariableType == libsbml.SBML_SPECIES ):
                theRule.setSpeciesToVariableReference( aRule[2], '1' )
            elif ( aVariableType == libsbml.SBML_PARAMETER ):
                theRule.setParameterToVariableReference( aRule[2], '1' )
            elif ( aVariableType == libsbml.SBML_COMPARTMENT ):
                theRule.setCompartmentToVariableReference( aRule[2], '1' )
            else:
                raise TypeError,\
            "Variable type must be Species, Parameter, or Compartment"


        else:
            raise TypeError,\
        " The type of Rule must be Algebraic, Assignment or Rate Rule"

        # convert SBML formula  to E-Cell formula
        convertedFormula = [ str( theRule.convertRuleFormula( aRule[1] ) ) ]

        # set Expression Property
        anEml.setEntityProperty( aSystemFullID,
                                 'Expression',
                                 convertedFormula )
        
        # setVariableReferenceList
        anEml.setEntityProperty( aSystemFullID,
                                 'VariableReferenceList',
                                 theRule.VariableReferenceList )



    # ------------------------------
    #  Set Reaction ( Process )
    # ------------------------------

    for aReaction in theModel.ReactionList:

        theReaction.initialize()

        # setFullID
        aSystemFullID = theReaction.getReactionID( aReaction )
        anEml.createEntity( 'ExpressionFluxProcess', aSystemFullID )

        # setName
        if ( theModel.Level == 2 ):
            if( aReaction[1] != '' ):
                anEml.setEntityProperty( aSystemFullID, 'Name', aReaction[1:2] )

        # setSubstrate
        for aSubstrate in aReaction[5]:
            aSubstrateList = []
            aSubstrateList.append( 'S' + str( theReaction.SubstrateNumber ) )
            theReaction.SubstrateNumber = theReaction.SubstrateNumber + 1
            aSubstrateID = theModel.getSpeciesReferenceID( aSubstrate[0] )
            if ( aSubstrateID == None ):
                raise NameError,"Species "+aSubstrate[0]+" not found"

            aSubstrateList.append( 'Variable:' + aSubstrateID )
            if ( aSubstrate[2] != 1 ):
                raise Exception,"Stoichiometry Error : E-Cell System can't set a floating Stoichiometry"
 
            aSubstrateList.append( str( -1 * theReaction.getStoichiometry(
                aSubstrate[0], aSubstrate[1] ) ) )
            theReaction.VariableReferenceList.append( aSubstrateList )

        # setProduct
        for aProduct in aReaction[6]:
            aProductList = []
            aProductList.append( 'P' + str(theReaction.ProductNumber) )
            theReaction.ProductNumber = theReaction.ProductNumber + 1
            aProductID = theModel.getSpeciesReferenceID( aProduct[0] )
            if ( aProductID == None ):
                raise NameError,"Species "+aProduct[0]+" not found"
            
            aProductList.append( 'Variable:' + aProductID )
            if ( aProduct[2] != 1 ):
                raise Exception,"Stoichiometry Error : E-Cell System can't set a floating Stoichiometry"

            aProductList.append( str( 1 * theReaction.getStoichiometry(
                aProduct[0],  aProduct[1] ) ) )

            theReaction.VariableReferenceList.append( aProductList )

        # setCatalyst
        for aModifier in aReaction[7]:
            aModifierList = []
            aModifierList.append( 'C' + str( theReaction.ModifierNumber ) )
            theReaction.ModifierNumber = theReaction.ModifierNumber + 1
            aModifierID = theModel.getSpeciesReferenceID( aModifier )
            if ( aModifierID == None ):
                raise NameError,"Species "+aModifier[0]+" not found"

            aModifierList.append( 'Variable:' + aModifierID )
            aModifierList.append( '0' )
            theReaction.VariableReferenceList.append( aModifierList )


        # setProperty
        if( aReaction[2] != [] ):
            if( aReaction[2][4] != [] ):
                for aParameter in aReaction[2][4]:
                    if ( aParameter[2] != '' ): 
                        aTmpList = [ str( aParameter[2] ) ]
                        if ( theModel.Level == 1 ):
                            anEml.setEntityProperty\
                            ( aSystemFullID, aParameter[1], aTmpList[0:1] )
                        elif ( theModel.Level == 2 ):
                            anEml.setEntityProperty\
                            ( aSystemFullID, aParameter[0], aTmpList[0:1] )
                            
                          
            # --------------------------
            # set "Expression" Property
            # --------------------------
        
            # convert SBML format formula to E-Cell format formula
            if( aReaction[2][0] != '' ):
                anExpression =\
                [ str( theReaction.convertKineticLawFormula( aReaction[2][0] ) ) ]



                # set Expression Property for ExpressionFluxProcess
                anEml.setEntityProperty( aSystemFullID,
                                         'Expression',
                                         anExpression )

                # setVariableReferenceList
                anEml.setEntityProperty( aSystemFullID,
                                         'VariableReferenceList',
                                         theReaction.VariableReferenceList )

    return anEml
示例#31
0
    def __init__(self, sbml_to_compare):
        '''
        sbml_to_compare -- list of two SBML strings, libsbml.SBMLDocument objects, or
        libsbml.Model objects, to compare
        '''
        import pygraphviz as pgv
        import libsbml
        from tellurium.analysis import getMatchingSpecies, getMatchingReactions

        # List of the two sbml documents to create diff
        self.doc = []
        # Dict of species id (from model 1) to description of match in model 2
        self.matches = [dict(), dict()]
        # The pygraphviz graph object
        self.G = pgv.AGraph(strict=False, directed=True)


        for sbml in sbml_to_compare:
            if isinstance(sbml, basestring):
                self.doc.append(libsbml.readSBMLFromString(sbml))
            elif isinstance(sbml, libsbml.SBMLDocument):
                self.doc.append(sbml)
            elif isinstance(sbml, libsbml.Model):
                self.doc.append(sbml.getSBMLDocument())
            else:
                raise Exception('SBML Input is not valid')

        matching_species = getMatchingSpecies(self.doc[0].model, self.doc[1].model)

        # Create set of overlapping species IDs
        for entry in matching_species:
            self.matches[0][entry['id']] = entry
            for sub_entry in entry['children'] + entry['parents'] + entry['exact']:
                self.matches[1][sub_entry['id']] = entry

        first_color = 'blue'
        second_color = 'red'
        match_color = 'green'

        # Creating graph for first model
        for s in self.doc[0].model.species:
            if s.getName():
                label = s.getName()
            else:
                label = s.getId()
            if s.getId() in self.matches[0]:
                label += " ({})".format(self._create_matched_description(s.getId()))

            if s.getId() in self.matches[0]:
                color = match_color
            else:
                color = first_color
            self.G.add_node(s.getId(), label=label, color=color)
        for r in self.doc[0].model.reactions:
            if r.getName():
                label = r.getName()
            else:
                label = r.getId()
            self.G.add_node(r.getId(), label=label, shape='box', color=first_color)
            for s in r.reactants:
                self.G.add_edge(s.getSpecies(), r.getId(), arrowhead='none', color=first_color)
            for s in r.products:
                self.G.add_edge(r.getId(), s.getSpecies(), color=first_color)
            for s in r.modifiers:
                self.G.add_edge(s.getSpecies(), r.getId(), arrowhead='odot', color=first_color)

        # Creating graph for second model
        for s in self.doc[1].model.species:
            # Skip creating species node for matches
            if s.getId() in self.matches[1]:
                continue
            if s.getName():
                label = s.getName() + ' ({})'.format(s.getId())
            else:
                label = s.getId()
            self.G.add_node(s.getId(), label=label, color=second_color)
        for r in self.doc[1].model.reactions:
            if r.getName():
                label = r.getName() + ' ({})'.format(r.getId())
            else:
                label = r.getId()
            self.G.add_node(r.getId(), label=label, shape='box', color=second_color)
            for s in r.reactants:
                if s.getSpecies() in self.matches[1]:
                    matched_id = self.matches[1][s.getSpecies()]['id']
                    self.G.add_edge(matched_id, r.getId(), arrowhead='none', color=second_color)
                else:
                    self.G.add_edge(s.getSpecies(), r.getId(), arrowhead='none', color=second_color)
            for s in r.products:
                if s.getSpecies() in self.matches[1]:
                    matched_id = self.matches[1][s.getSpecies()]['id']
                    self.G.add_edge(r.getId(), matched_id, color=second_color)
                else:
                    self.G.add_edge(r.getId(), s.getSpecies(), color=second_color)
            for s in r.modifiers:
                if s.getSpecies() in self.matches[1]:
                    matched_id = self.matches[1][s.getSpecies()]['id']
                    self.G.add_edge(matched_id, r.getId(), arrowhead='odot', color=second_color)
                else:
                    self.G.add_edge(s.getSpecies(), r.getId(), arrowhead='odot', color=second_color)
def get_ia_and_rules(model):
    sbml = model.getSBML()
    sbml_document = libsbml.readSBMLFromString(sbml)
    sbml_model = sbml_document.getModel()
    return _get_sbml_ini_dict(sbml_model), _get_sbml_rule_dict(sbml_model)
示例#33
0
from __future__ import print_function, division

import libsbml
import tellurium as te
import lxml.etree as ET
from io import StringIO
import tempfile

r = te.loada('''
    J0: S1 -> S2; k1*S1;
    S1=10.0; S2=0.0; k1=1.0;
''')

# create SBML file
f = tempfile.NamedTemporaryFile('w', suffix=".xml")
r.exportToSBML(f.name)

# create C14N canonical XML
et = ET.parse(f.name)
output = StringIO.StringIO()
et.write_c14n(output)
c14n_xml = output.getvalue()
# TODO: in addition sort all elements of the listOfs

# read with libsbml
doc = libsbml.readSBMLFromString(c14n_xml)

# read with roadrunner
te.loadSBMLModel(c14n_xml)
示例#34
0
def convertSBML2EML(aSBMLString):

    aSBMLDocument = libsbml.readSBMLFromString(aSBMLString)
    aSBMLModel = aSBMLDocument.getModel()

    theModel = SBML_Model(aSBMLDocument, aSBMLModel)
    theCompartment = SBML_Compartment(theModel)
    theParameter = SBML_Parameter(theModel)
    theSpecies = SBML_Species(theModel)
    theRule = SBML_Rule(theModel)
    theReaction = SBML_Reaction(theModel)
    #    theEvent = SBML_Event( theModel )

    anEml = Eml()

    # ------------------------------
    #  Set Stepper
    # ------------------------------

    anEml.createStepper('ODEStepper', 'DE')
    ##    anEml.createStepper( 'ODE45Stepper', 'DE' )

    # ------------------------------
    #  Set Compartment ( System )
    # ------------------------------

    # setFullID
    aSystemFullID = 'System::/'
    anEml.createEntity('System', aSystemFullID)
    anEml.setEntityProperty(aSystemFullID, 'StepperID', ['DE'])
    anEml.setEntityProperty(aSystemFullID, 'Name', ['Default'])

    for aCompartment in (theModel.CompartmentList):

        # initialize
        theCompartment.initialize(aCompartment)

        # getPath
        if (theModel.Level == 1):
            aPath = theModel.getPath(aCompartment[1])
        elif (theModel.Level == 2):
            aPath = theModel.getPath(aCompartment[0])

        # setFullID
        if (aPath == '/'):
            aSystemFullID = 'System::/'
        else:
            aSystemFullID = theCompartment.getCompartmentID(aCompartment)
            anEml.createEntity('System', aSystemFullID)

            # setStepper
            anEml.setEntityProperty(aSystemFullID, 'StepperID', ['DE'])

        # setName( default = [] )
        if (theModel.Level == 2):
            if (aCompartment[1] != ''):
                anEml.setEntityProperty(aSystemFullID, 'Name',
                                        aCompartment[1:2])

        # setDimensions( default = 3 )
        aDimensionsFullID = 'Variable:' + aPath + ':Dimensions'
        anEml.createEntity('Variable', aDimensionsFullID)
        aTmpList = [str(aCompartment[2])]
        anEml.setEntityProperty(aDimensionsFullID, 'Value', aTmpList[0:1])

        # setSIZE
        aSizeFullID = 'Variable:' + aPath + ':SIZE'
        anEml.createEntity('Variable', aSizeFullID)

        aSizeValue = theCompartment.getCompartmentSize(aCompartment)
        aSizeUnit = theCompartment.getCompartmentUnit(aCompartment)

        # convert to ECELL Unit
        if (aSizeUnit != ''):
            aSizeValue = theModel.convertUnit(aSizeUnit, aSizeValue)

        aTmpList = [str(aSizeValue)]
        anEml.setEntityProperty(aSizeFullID, 'Value', aTmpList[0:1])

        # setConstant( default = 1 )
        if (aCompartment[7] == 1):
            anEml.setEntityProperty(aSizeFullID, 'Fixed', [
                '1',
            ])

    # ------------------------------
    #  Set GlobalParameter ( Variable )
    # ------------------------------

    if (theModel.ParameterList != []):

        # setGlobalParameterSystem
        aSystemFullID = 'System:/:SBMLParameter'
        anEml.createEntity('System', aSystemFullID)
        anEml.setEntityProperty(aSystemFullID, 'StepperID', ['DE'])
        anEml.setEntityProperty(aSystemFullID, 'Name', ['Global Parameter'])

    for aParameter in theModel.ParameterList:

        # setFullID
        aSystemFullID = theParameter.getParameterID(aParameter)
        anEml.createEntity('Variable', aSystemFullID)

        # setName
        if (aParameter[1] != ''):
            anEml.setEntityProperty(aSystemFullID, 'Name', aParameter[1:2])

        # setValue
        aTmpList = [str(theParameter.getParameterValue(aParameter))]
        anEml.setEntityProperty(aSystemFullID, 'Value', aTmpList[0:1])

        # setFixed ( default = 1 )
        if (aParameter[4] == 1):
            # aTmpList = [ str( aParameter[4] ) ]
            aTmpList = ['1']
            anEml.setEntityProperty(aSystemFullID, 'Fixed', aTmpList[0:1])

    # ------------------------------
    #  Set Species ( Variable )
    # ------------------------------

    for aSpecies in theModel.SpeciesList:

        ### setFullID ###

        aSystemFullID = theSpecies.getSpeciesID(aSpecies)
        anEml.createEntity('Variable', aSystemFullID)

        ### setName ###

        if (theModel.Level == 2):

            if (aSpecies[1] != ''):
                anEml.setEntityProperty(aSystemFullID, 'Name', aSpecies[1:2])

        ### setValue ###

        aTmpList = [str(theSpecies.getSpeciesValue(aSpecies))]
        anEml.setEntityProperty(aSystemFullID, 'Value', aTmpList[0:1])

        ### setFixed ###

        aConstant = theSpecies.getConstant(aSpecies)
        anEml.setEntityProperty(aSystemFullID, 'Fixed', [str(aConstant)])

    # ------------------------------
    #  Set Rule ( Process )
    # ------------------------------

    if (theModel.RuleList != []):

        ### make Rule System ###

        aSystemFullID = 'System:/:SBMLRule'
        anEml.createEntity('System', aSystemFullID)
        anEml.setEntityProperty(aSystemFullID, 'Name',
                                ['System for SBML Rule'])

        anEml.setEntityProperty(aSystemFullID, 'StepperID', ['DE'])

    for aRule in theModel.RuleList:

        theRule.initialize()

        ### setFullID ###
        aSystemFullID = theRule.getRuleID()

        ### Algebraic Rule ###
        if (aRule[0] == libsbml.SBML_ALGEBRAIC_RULE):

            anEml.createEntity('ExpressionAlgebraicProcess', aSystemFullID)

        ### Assignment Rule ###
        elif (aRule[0] == libsbml.SBML_ASSIGNMENT_RULE
              or aRule[0] == libsbml.SBML_SPECIES_CONCENTRATION_RULE
              or aRule[0] == libsbml.SBML_COMPARTMENT_VOLUME_RULE
              or aRule[0] == libsbml.SBML_PARAMETER_RULE):

            anEml.createEntity('ExpressionAssignmentProcess', aSystemFullID)

            aVariableType = theRule.getVariableType(aRule[2])

            if (aVariableType == libsbml.SBML_SPECIES):
                theRule.setSpeciesToVariableReference(aRule[2], '1')
            elif (aVariableType == libsbml.SBML_PARAMETER):
                theRule.setParameterToVariableReference(aRule[2], '1')
            elif (aVariableType == libsbml.SBML_COMPARTMENT):
                theRule.setCompartmentToVariableReference(aRule[2], '1')
            else:
                raise TypeError,\
            "Variable type must be Species, Parameter, or Compartment"

        ### Rate Rule ###
        elif (aRule[0] == libsbml.SBML_RATE_RULE):

            anEml.createEntity('ExpressionFluxProcess', aSystemFullID)

            aVariableType = theRule.getVariableType(aRule[2])

            if (aVariableType == libsbml.SBML_SPECIES):
                theRule.setSpeciesToVariableReference(aRule[2], '1')
            elif (aVariableType == libsbml.SBML_PARAMETER):
                theRule.setParameterToVariableReference(aRule[2], '1')
            elif (aVariableType == libsbml.SBML_COMPARTMENT):
                theRule.setCompartmentToVariableReference(aRule[2], '1')
            else:
                raise TypeError,\
            "Variable type must be Species, Parameter, or Compartment"

        else:
            raise TypeError,\
        " The type of Rule must be Algebraic, Assignment or Rate Rule"

        # convert SBML formula  to E-Cell formula
        convertedFormula = [str(theRule.convertRuleFormula(aRule[1]))]

        # set Expression Property
        anEml.setEntityProperty(aSystemFullID, 'Expression', convertedFormula)

        # setVariableReferenceList
        anEml.setEntityProperty(aSystemFullID, 'VariableReferenceList',
                                theRule.VariableReferenceList)

    # ------------------------------
    #  Set Reaction ( Process )
    # ------------------------------

    for aReaction in theModel.ReactionList:

        theReaction.initialize()

        # setFullID
        aSystemFullID = theReaction.getReactionID(aReaction)
        anEml.createEntity('ExpressionFluxProcess', aSystemFullID)

        # setName
        if (theModel.Level == 2):
            if (aReaction[1] != ''):
                anEml.setEntityProperty(aSystemFullID, 'Name', aReaction[1:2])

        # setSubstrate
        for aSubstrate in aReaction[5]:
            aSubstrateList = []
            aSubstrateList.append('S' + str(theReaction.SubstrateNumber))
            theReaction.SubstrateNumber = theReaction.SubstrateNumber + 1
            aSubstrateID = theModel.getSpeciesReferenceID(aSubstrate[0])
            if (aSubstrateID == None):
                raise NameError, "Species " + aSubstrate[0] + " not found"

            aSubstrateList.append('Variable:' + aSubstrateID)
            if (aSubstrate[2] != 1):
                raise Exception, "Stoichiometry Error : E-Cell System can't set a floating Stoichiometry"

            aSubstrateList.append(
                str(-1 * theReaction.getStoichiometry(aSubstrate[0],
                                                      aSubstrate[1])))
            theReaction.VariableReferenceList.append(aSubstrateList)

        # setProduct
        for aProduct in aReaction[6]:
            aProductList = []
            aProductList.append('P' + str(theReaction.ProductNumber))
            theReaction.ProductNumber = theReaction.ProductNumber + 1
            aProductID = theModel.getSpeciesReferenceID(aProduct[0])
            if (aProductID == None):
                raise NameError, "Species " + aProduct[0] + " not found"

            aProductList.append('Variable:' + aProductID)
            if (aProduct[2] != 1):
                raise Exception, "Stoichiometry Error : E-Cell System can't set a floating Stoichiometry"

            aProductList.append(
                str(1 *
                    theReaction.getStoichiometry(aProduct[0], aProduct[1])))

            theReaction.VariableReferenceList.append(aProductList)

        # setCatalyst
        for aModifier in aReaction[7]:
            aModifierList = []
            aModifierList.append('C' + str(theReaction.ModifierNumber))
            theReaction.ModifierNumber = theReaction.ModifierNumber + 1
            aModifierID = theModel.getSpeciesReferenceID(aModifier)
            if (aModifierID == None):
                raise NameError, "Species " + aModifier[0] + " not found"

            aModifierList.append('Variable:' + aModifierID)
            aModifierList.append('0')
            theReaction.VariableReferenceList.append(aModifierList)

        # setProperty
        if (aReaction[2] != []):
            if (aReaction[2][4] != []):
                for aParameter in aReaction[2][4]:
                    if (aParameter[2] != ''):
                        aTmpList = [str(aParameter[2])]
                        if (theModel.Level == 1):
                            anEml.setEntityProperty\
                            ( aSystemFullID, aParameter[1], aTmpList[0:1] )
                        elif (theModel.Level == 2):
                            anEml.setEntityProperty\
                            ( aSystemFullID, aParameter[0], aTmpList[0:1] )

            # --------------------------
            # set "Expression" Property
            # --------------------------

            # convert SBML format formula to E-Cell format formula
            if (aReaction[2][0] != ''):
                anExpression =\
                [ str( theReaction.convertKineticLawFormula( aReaction[2][0] ) ) ]

                # set Expression Property for ExpressionFluxProcess
                anEml.setEntityProperty(aSystemFullID, 'Expression',
                                        anExpression)

                # setVariableReferenceList
                anEml.setEntityProperty(aSystemFullID, 'VariableReferenceList',
                                        theReaction.VariableReferenceList)

    return anEml
示例#35
0
def runSingleSBML(rpthermo, member_name, rpsbml_string, path_id):
    #open one of the rp SBML files
    rpsbml = rpSBML.rpSBML(member_name,
                           libsbml.readSBMLFromString(rpsbml_string))
    rpthermo.pathway_drG_prime_m(rpsbml, path_id)
    return libsbml.writeSBMLToString(rpsbml.document).encode('utf-8')
示例#36
0
def readrpSBMLzip(inputZip):
    input_zip = zipfile.ZipFile(inputZip)
    rpsbml_paths = {}
    for name in input_zip.namelist():
        rpsbml_paths[name] = rpFBA.rpSBML(name, libsbml.readSBMLFromString(input_zip.read(name).decode("utf-8")))
    return rpsbml_paths
示例#37
0
def flattenExternalModelDefinitions(doc):
    """ Converts all ExternalModelDefinitions to ModelDefinitions.

    I.e. the definition of models in external files are read
    and directly included in the top model. The resulting
    comp model consists than only of a single file.

    The model refs in the submodel do not change in the process,
    so no need to update the submodels.

    :param doc: SBMLDocument
    :return: SBMLDocument with ExternalModelDefinitions replaced
    """
    # FIXME: handle /multiple levels of hierarchies recursively (ExternalModelDefinitions of submodels)

    model = doc.getModel()
    if model is None:
        return doc

    comp_doc = doc.getPlugin("comp")
    emd_list = comp_doc.getListOfExternalModelDefinitions()

    # no ExternalModelDefinitions
    if (emd_list is None) or (len(emd_list) == 0):
        return doc

    # ExternalModelDefinitions set as ModelDefinitions
    emd_ids = []
    mds = []
    for emd in emd_list:
        emd_ids.append(emd.getId())

        # get the model definition from the model
        ref_model = emd.getReferencedModel()

        # store model definition
        md = libsbml.ModelDefinition(ref_model)
        mds.append(md)

    packages = []
    for emd in emd_list:
        # get the model definition from the model
        ref_model = emd.getReferencedModel()
        ref_doc = ref_model.getSBMLDocument()
        # print('\n', ref_model)
        for k in range(ref_doc.getNumPlugins()):

            plugin = ref_doc.getPlugin(k)
            uri = plugin.getURI()
            prefix = plugin.getPrefix()
            name = plugin.getPackageName()
            required = None
            if ref_doc.isSetPackageRequired(name):
                required = ref_doc.getPackageRequired(name)

            packages.append({
                'model': ref_model,
                'uri': uri,
                'prefix': prefix,
                'name': name,
                'required': required
            })

    # remove emds from model (do not remove while iterating over the list)
    for emd_id in emd_ids:
        comp_doc.removeExternalModelDefinition(emd_id)

    # activate all the packages
    from pprint import pprint
    pprint(packages)
    for pdict in packages:
        doc.enablePackage(pdict['uri'], pdict['prefix'], True)
        doc.setPackageRequired(pdict['name'], pdict['required'])

    # now add the model definitions
    for md in mds:
        comp_doc.addModelDefinition(md)

    sbml_str = libsbml.writeSBMLToString(doc)
    doc = libsbml.readSBMLFromString(sbml_str)

    # replacement finished, now go through all ModelDefinitions
    # and add things the packages require
    print("-"*80)
    for k in range(doc.getNumPlugins()):
        plugin = doc.getPlugin(k)
        name = plugin.getPackageName()
        print(name, '\n')
        md_list = comp_doc.getListOfModelDefinitions()
        for md_model in md_list:

            # if a package needs something on
            # a model we have to write it on all ModelDefinitions
            # this will break on a package per package basis ! We know about fbc it needs
            # a strict tag so writing this here
            if name == "fbc":
                # for some ModelDefinitions we don't get the fbc Plugin ???
                fbc_model = md_model.getPlugin(name)

                print('\tModel:', md_model)
                print('\tFBCModelPlugin:', fbc_model, type(fbc_model))

                # setting because it is required (if unlucky additional info required)
                # but we can't set it because we can't access the FBCModelPlugins of the ModelDefinitions
                if fbc_model is not None:
                    if not fbc_model.isSetStrict():
                        fbc_model.setStrict(False)
                else:
                    print("WARNING: This should never happen. All ModelDefinitions should have a FBCModelPlugin")

    doc.checkInternalConsistency()
    doc.printErrors()

    return doc
示例#38
0
def convertSBML2EML(
        aSBMLString,
        anODEStepper="ODEStepper",
        aFixedODEStepper='FixedODE1Stepper',
        aDiscreteStepper='DiscreteTimeStepper'):  ## 'PassiveStepper'

    theDefaultStepperID = 'Default'
    theDefaultODEStepperID = 'ODE'
    theDefaultDiscreteStepperID = 'Discrete'

    Steppers = dict(ODE=anODEStepper,
                    FixedODE=aFixedODEStepper,
                    Discrete=aDiscreteStepper)

    StepperIDs = dict(default=theDefaultStepperID,
                      ODE=theDefaultODEStepperID,
                      Discrete=theDefaultDiscreteStepperID)

    aSBMLDocument = libsbml.readSBMLFromString(aSBMLString)

    # ------------------------------
    #  Function Definition Converter
    # ------------------------------

    theFunctionDefinitionConverter = libsbml.SBMLFunctionDefinitionConverter()
    theFunctionDefinitionConverter.setDocument(aSBMLDocument)
    print "    FunctionDefinitionConverter: %s" % \
        libsbml.OperationReturnValue_toString( theFunctionDefinitionConverter.convert() )

    # ------------------------------
    #  Initial Assignment Converter
    # ------------------------------

    theInitialAssignmentConverter = libsbml.SBMLInitialAssignmentConverter()
    theInitialAssignmentConverter.setDocument(aSBMLDocument)
    print "    InitialAssignmentConverter:  %s" % \
        libsbml.OperationReturnValue_toString( theInitialAssignmentConverter.convert() )

    ## FIXME: theInitialAssignmentConverter.convert() always returns None.

    aSBMLModel = aSBMLDocument.getModel()

    ##    theUndetermined =

    theModel = SBML_Model(aSBMLDocument, aSBMLModel)
    theCompartment = SBML_Compartment(theModel)
    theParameter = SBML_Parameter(theModel)
    theSpecies = SBML_Species(theModel)
    theRule = SBML_Rule(theModel)
    theReaction = SBML_Reaction(theModel)
    theEvent = SBML_Event(theModel)

    ##    # dump FunctionDefinition
    ##    print "\n"
    ##    for aFunctionDefinition in theModel.FunctionDefinitionList:
    ##        print "FunctionDefinition: %s\n" % str( aFunctionDefinition )

    anEml = Eml()

    set_Steppers(theModel, anEml, Steppers, StepperIDs)
    set_Compartments(theCompartment, anEml, StepperIDs)
    set_GlobalParameters(theParameter, anEml, StepperIDs)
    set_Species(theSpecies, anEml)
    set_Rules(theRule, anEml, StepperIDs)
    set_Reactions(theReaction, anEml, StepperIDs)
    set_Events(theEvent, anEml, StepperIDs)

    return anEml
示例#39
0
    #9) The overlap of the same changes --> might not be applicable in our case

    #10) Reduced model

    #11) ECM

#This is to test the good functioing of the main function and make sure that
#there are no errors
#TODO: change this to the stepTest
if __name__ == "__main__":
    #read the TAR.XZ with all the SBML pathways
    rpsbml_paths = {}
    tar = tarfile.open('tests/testFBAin.tar.xz') #TODO: create this
    rpsbml_paths = {}
    for member in tar.getmembers():
        rpsbml_paths[member.name] = rpFBA.rpSBML(member.name,libsbml.readSBMLFromString(tar.extractfile(member).read().decode("utf-8")))
    #pass the different models to the SBML solvers and write the results to file
    #rpsbml_paths = readrpSBMLzip(params.inSBMLzip)
    for rpsbml_name in rpsbml_paths:
        rpfba = rpFBA.rpFBA(rpsbml_paths[rpsbml_name])
        rpfba.allObj()
    #writerpSBMLzip(rpsbml_paths, params.outSBMLzip)
    #designed to write using TAR.XZ with all the SBML pathways
    with tarfile.open('testFBAout.tar.xz', 'w:xz') as tf:
        for rpsbml_name in rpsbml_paths:
            data = libsbml.writeSBMLToString(rpsbml_paths[rpsbml_name].document).encode('utf-8')
            fiOut = BytesIO(data)
            info = tarfile.TarInfo(rpsbml_name)
            info.size = len(data)
            tf.addfile(tarinfo=info, fileobj=fiOut)
示例#40
0
from __future__ import print_function, division

import libsbml
import tellurium as te
import lxml.etree as ET
from io import StringIO
import tempfile


r = te.loada('''
    J0: S1 -> S2; k1*S1;
    S1=10.0; S2=0.0; k1=1.0;
''')

# create SBML file
f = tempfile.NamedTemporaryFile('w', suffix=".xml")
r.exportToSBML(f.name)

# create C14N canonical XML
et = ET.parse(f.name)
output = StringIO.StringIO()
et.write_c14n(output)
c14n_xml = output.getvalue()
# TODO: in addition sort all elements of the listOfs

# read with libsbml
doc = libsbml.readSBMLFromString(c14n_xml)

# read with roadrunner
te.loadSBMLModel(c14n_xml)
示例#41
0
import os

path = os.path.dirname(os.path.realpath(__file__))
sbmlFilePath = os.path.join(path, 'MODEL0911989198.xml')

with open(sbmlFilePath,'r') as f:
    sbmlString = f.read()

def module_exists(module_name):
    try:
        __import__(module_name)
    except ImportError:
        return False
    else:
        return True

if module_exists('libsbml'):
    import libsbml
    sbml = libsbml.readSBMLFromString(sbmlString)
示例#42
0
    def reversibilityIndex():
        """Quantitative measure for the reversibility of a reaction by taking into consideration the concentration of the substrate and products
        """
        return False


if __name__ == "__main__":
    #READ THE TAR.XZ FILE
    rpsbml_paths = {}
    tar = tarfile.open('tests/testTHERMOin.tar.xz')  #TODO: create this
    rpsbml_paths = {}
    for member in tar.getmembers():
        rpsbml_paths[member.name] = rpFBA.rpSBML(
            member.name,
            libsbml.readSBMLFromString(
                tar.extractfile(member).read().decode("utf-8")))
    ###
    rpthermo = rpThermo()
    for rpsbml_name in rpsbml_paths:
        rpthermo.pathway_drG_prime_m(rpsbml_paths[rpsbml_name])
    #WRITE THE TAR.XZ FILE
    with tarfile.open('testFBAout.tar.xz', 'w:xz') as tf:
        for rpsbml_name in rpsbml_paths:
            data = libsbml.writeSBMLToString(
                rpsbml_paths[rpsbml_name].document).encode('utf-8')
            fiOut = BytesIO(data)
            info = tarfile.TarInfo(rpsbml_name)
            info.size = len(data)
            tf.addfile(tarinfo=info, fileobj=fiOut)
示例#43
0
def biomodels_info():
    '''
    fetch latest biomodels release from ftp
    extract
    parse all curated models
    '''
    import ftplib
    import tarfile
    import libsbml
    import re
    import os

    if not os.path.exists('release.tar.bz2'):

        ftp = ftplib.FTP("ftp.ebi.ac.uk")
        ftp.login()
        ftp.cwd("/pub/databases/biomodels/releases/latest/")
        file_list = []
        ftp.dir(file_list.append)
        ftp_file = [
            x for x in file_list if x.endswith('pub-sbml_files.tar.bz2')
        ][0].split()[-1]
        try:
            ftp.retrbinary('RETR %s' % ftp_file,
                           open('release.tar.bz2', 'wb').write)
        except ftplib.error_perm:
            print 'ERROR: cannot read file "%s"' % ftp_file
            import os
            os.unlink(ftp_file)
            return
        #print '*** Downloaded "%s" to CWD' % ftp_file
    else:
        print 'used release.tar.bz2 in current folder! remove to redownload'

    #Unpack and read info
    tar = tarfile.open('release.tar.bz2', 'r:bz2')
    curated_files = [x for x in tar.getnames() if '/curated/' in x]
    items = []
    notes_items = []
    for fn in curated_files:
        #print fn[-19:-4]
        try:
            cur_file = tar.extractfile(fn).read()
            doc = libsbml.readSBMLFromString(cur_file)
            model = doc.getModel()
            notes = re.sub('body', 'div',
                           model.getNotes().getChild(0).toXMLString())
            model_id = fn[-19:-4]
            name = model.getName()
            items.append([
                model_id,
                '<li><q><span bla="%s">%s: %s</span> <a href="{{=URL(r=request,f="biomodels_info_notes.html#%s")}}" target="_blank">notes</a></q></li>'
                % (model_id, model_id, name, model_id)
            ])
            notes_items.append('<div id="%s">%s</div>' % (model_id, notes))
        except:
            pass
        #print model.getName(), model.getId(),
    items.sort()
    biomodels_list = "<ul class='biomodels_select'>%s\n</ul>" % "\n".join(
        [x for y, x in items])
    notes = "<div class='biomodels_notes'>%s</div><br/><br/><br/><br/><br/><br/><br/><br/>" % ''.join(
        notes_items)
    open('biomodels_info_list.html', 'w').write(biomodels_list)
    open('biomodels_info_notes.html', 'w').write(notes)
示例#44
0
import libsbml
import roadrunner


sbml_path = "body19_livertoy_flat.xml"
r = roadrunner.RoadRunner("body19_livertoy_flat.xml")  # type: roadrunner.RoadRunner
sbml_str = r.getCurrentSBML()

doc1 = libsbml.readSBMLFromFile(sbml_path)  # type: libsbml.SBMLDocument
doc2 = libsbml.readSBMLFromString(sbml_str)  # type: libsbml.SBMLDocument

docs = {"sbml": doc1, "roadrunner": doc2}

for key, doc in docs.items():
    print(key)
    model = doc.getModel()  # type: libsbml.Model
    s = model.getSpecies("Ave_glc")  # type: libsbml.Species
    print(s)
    print("initial concentration: ", s.getInitialConcentration())
    print("initial amount: ", s.getInitialAmount())

    print("-" * 80)
示例#45
0
def convertSBML2EML( aSBMLString,
                     anODEStepper     = "ODEStepper",
                     aFixedODEStepper = 'FixedODE1Stepper',
                     aDiscreteStepper = 'DiscreteTimeStepper' ):   ## 'PassiveStepper'

    theDefaultStepperID         = 'Default'
    theDefaultODEStepperID      = 'ODE'
    theDefaultDiscreteStepperID = 'Discrete'

    Steppers = dict(
        ODE      = anODEStepper,
        FixedODE = aFixedODEStepper,
        Discrete = aDiscreteStepper )

    StepperIDs = dict(
        default  = theDefaultStepperID,
        ODE      = theDefaultODEStepperID,
        Discrete = theDefaultDiscreteStepperID )


    aSBMLDocument = libsbml.readSBMLFromString( aSBMLString )

    # ------------------------------
    #  Function Definition Converter
    # ------------------------------

    theFunctionDefinitionConverter = libsbml.SBMLFunctionDefinitionConverter()
    theFunctionDefinitionConverter.setDocument( aSBMLDocument )
    print "    FunctionDefinitionConverter: %s" % \
        libsbml.OperationReturnValue_toString( theFunctionDefinitionConverter.convert() )

    # ------------------------------
    #  Initial Assignment Converter
    # ------------------------------

    theInitialAssignmentConverter = libsbml.SBMLInitialAssignmentConverter()
    theInitialAssignmentConverter.setDocument( aSBMLDocument )
    print "    InitialAssignmentConverter:  %s" % \
        libsbml.OperationReturnValue_toString( theInitialAssignmentConverter.convert() )

    ## FIXME: theInitialAssignmentConverter.convert() always returns None.

    
    aSBMLModel = aSBMLDocument.getModel()

##    theUndetermined = 

    theModel       = SBML_Model( aSBMLDocument, aSBMLModel )
    theCompartment = SBML_Compartment( theModel )
    theParameter   = SBML_Parameter( theModel )
    theSpecies     = SBML_Species( theModel )
    theRule        = SBML_Rule( theModel )
    theReaction    = SBML_Reaction( theModel )
    theEvent       = SBML_Event( theModel )

##    # dump FunctionDefinition
##    print "\n"
##    for aFunctionDefinition in theModel.FunctionDefinitionList:
##        print "FunctionDefinition: %s\n" % str( aFunctionDefinition )

    anEml = Eml()

    set_Steppers( theModel, anEml, Steppers, StepperIDs )
    set_Compartments( theCompartment, anEml, StepperIDs )
    set_GlobalParameters( theParameter, anEml, StepperIDs )
    set_Species( theSpecies, anEml )
    set_Rules( theRule, anEml, StepperIDs )
    set_Reactions( theReaction, anEml, StepperIDs )
    set_Events( theEvent, anEml, StepperIDs )

    return anEml
示例#46
0
def sbml2jsbgn(sbml_str, rxncon=False):
    try:
        import libsbml
    except ImportError:
        raise HTTP(500, 'Your need to install libsbml-python to use this function. For Debian/Ubuntu see http://sbos.eu/doku.php?id=installation_instructions')
    doc = libsbml.readSBMLFromString(sbml_str)
    model = doc.getModel()
    graph = dict(nodes = [], edges = [])
    compartment2species = {}
    seen_species = set()
    #------------------------------------------
    if 'rxncon.org' in sbml_str:
        import re
        pattern_nd = re.compile('(.+)\(([^\)]*)\)')
    def modification2statevariable(mod):
        if '~' in mod:
            mod_split = mod.split('~')
            if mod_split[1] == 'U':
                return mod_split[0]
            if mod_split[0] == 'bd':
                return mod_split[1]
            else:
                return '%s@%s'%(mod_split[1],mod_split[0])
        return ''
    #------------------------------------------
    name_or_id = lambda x : x.getName() or x.getId()
    #------------------------------------------
    def add_node(species_id, source_id, target_id, edge_sbo):
        species = model.getSpecies(species_id)
        if species_id not in seen_species:
            seen_species.add(species_id)
            #-------------------------------------
            if 'rxncon.org' in sbml_str:
                #print species.getName()
                if 'sink' in species_id:
                    node_item = dict( id = species_id, sbo = 291, is_abstract = 0, data = dict ( x = 0.0, y = 0.0, width = 60, height = 60))
                    graph['nodes'].append(node_item)
                elif species.getName().startswith('xXx') and species.getName().endswith('xXx()'):
                    node_item = dict(id = species_id, sbo = 347, is_abstract = 0, data = dict( x = 0.0, y = 0.0, width = 90, height = 60, label=species.getName()[3:-5]))
                    graph['nodes'].append(node_item)
                elif '__' in species.getName():
                    complex_item = dict(id = species_id, sbo = 253, is_abstract = 0, data = dict(x = 0.0, y = 0.0, width = 60, height = 60, subnodes=[]))
                    for subnode_id in species.getName().split('__'):
                        match = re.search(pattern_nd, subnode_id)
                        print 'subnode_id', subnode_id
                        subnode_id, mods = match.group(1), match.group(2)
                        if ('rna' in subnode_id.lower()) or ('dna' in subnode_id.lower()):
                            sbo = 250
                        else:
                            sbo = 252
                        node_item = dict( id = species_id+subnode_id, sbo = sbo, is_abstract = 0, data = dict ( x = 0.0, y = 0.0, width = 60, height = 60, label=subnode_id))
                        if mods:
                            show_mods = [modification2statevariable(mod) for mod in mods.split(',') if '!' not in mod]
                            node_item['data']['statevariable'] = [x for x in show_mods if x]
                        complex_item['data']['subnodes'].append(species_id+subnode_id)
                        graph['nodes'].append(node_item)
                    graph['nodes'].append(complex_item)
                else:
                    match = re.search(pattern_nd, species.getName())
                    spec_id, mods = match.group(1),match.group(2)
                    if ('rna' in spec_id.lower()) or ('dna' in spec_id.lower()):
                        sbo = 250
                    else:
                        sbo = 252
                    node_item = dict( id = species_id, sbo = sbo, is_abstract = 0, data = dict ( x = 0.0, y = 0.0, width = 60, height = 60, label=spec_id))
                    if mods:
                        show_mods = [modification2statevariable(mod) for mod in mods.split(',') if '!' not in mod]
                        node_item['data']['statevariable'] = [x for x in show_mods if x]
                    graph['nodes'].append(node_item)
                    #-------------------------------------
            else:
                if 'sink' in species_id or name_or_id(species).lower() == 'emptyset':
                    sbo = 291
                    label = ''
                else:
                    sbo = 285
                    #-------------------------------------
                    #guess sbo
                    for n in range(species.getNumCVTerms()):
                        cvt = species.getCVTerm(n)
                        res = cvt.getResources()
                        for m in range(res.getLength()):
                            resource = res.getValue(m)
                            if 'urn:miriam:obo.chebi' in resource:
                                sbo = 247
                                break
                            if 'urn:miriam:pubchem' in resource:
                                sbo = 247
                                break
                            if 'urn:miriam:uniprot' in resource:
                                sbo = 245
                                break
                    if ('rna' in name_or_id(species).lower()) or ('dna' in name_or_id(species).lower()):
                        sbo = 250
                    #if 'complex' in name_or_id(species).lower():
                    #    sbo = 253
                    label = name_or_id(species)
                #-------------------------------------
                #create node
                node_item = dict(
                    id = species_id,
                    sbo = sbo,
                    is_abstract = 0,
                    data = dict (
                        x = 0.0,
                        y = 0.0,
                        width = 60,
                        height = 60,
                        )
                    )
                if label:
                    node_item['data']['label'] = label
                #-------------------------------------
                graph['nodes'].append(node_item)
        #-------------------------------------
        #create edge
        edge_item = dict(
            id = 'x',
            source = source_id,
            target = target_id,
            sbo = edge_sbo,
            )
        graph['edges'].append(edge_item)
        #-------------------------------------
        #add compartment (compartments are linked from the compartment as subnodes)
        if species:
            #node_item['data']['compartment'] = species.getCompartment()
            try:
                compartment2species[species.getCompartment()].append(species.getId())
            except KeyError:
                compartment2species[species.getCompartment()] = [species.getId()]
            return species.getCompartment()
    #------------------------------------------
    for reaction in model.getListOfReactions():
        node_item = dict(
            id = reaction.getId(),
            sbo = 375,
            is_abstract = 0,
            data = dict (
                x = 0.0,
                y = 0.0,
                label = name_or_id(reaction),
                width = 20,
                height = 20,
                )
            )
        graph['nodes'].append(node_item)
        #---------------
        #reactands
        comp = None
        has_sink = False
        if len(reaction.getListOfReactants())==0:
            add_node(reaction.getId()+'sink', reaction.getId()+'sink', reaction.getId(), 394)
            has_sink = reaction.getId()+'sink'
        else:
            for substrate in reaction.getListOfReactants():
                comp = add_node(substrate.getSpecies(), substrate.getSpecies(), reaction.getId(), 394)
                if comp:
                    compartment2species[comp].append(reaction.getId())
        #---------------
        #products
        if len(reaction.getListOfProducts())==0:
            add_node(reaction.getId()+'sink', reaction.getId(), reaction.getId()+'sink', 393)
            has_sink = reaction.getId()+'sink'
        else:
            for product in reaction.getListOfProducts():
                comp = add_node(product.getSpecies(), reaction.getId(), product.getSpecies(), 393)
                if comp:
                    compartment2species[comp].append(reaction.getId())
        if has_sink:
            compartment2species[comp].append(has_sink)
        #---------------
        #modifiers
        for modifier in reaction.getListOfModifiers():
            #FIXME check sbo for edge_sbo
            add_node(modifier.getSpecies(), modifier.getSpecies(), reaction.getId(), 168)
    #------------------------------------------
    for compartment in model.getListOfCompartments():
        node_item = dict(
            id = compartment.getId(),
            sbo = 290,
            is_abstract = 0,
            data = dict (
                x = 10.0,
                y = 10.0,
                label = name_or_id(compartment),
                height = 200,
                width = 200,
                )
            )
        if compartment.getId() in compartment2species:
            node_item['data']['subnodes'] = list(set(compartment2species[compartment.getId()]))
        graph['nodes'].append(node_item)
    for i in range(len(graph['edges'])):
        graph['edges'][i]['id'] = 'edge%s'%i
    #print graph
    return graph
示例#47
0
import os

path = os.path.dirname(os.path.realpath(__file__))
sbmlFilePath = os.path.join(path, 'MODEL1204280021.xml')

with open(sbmlFilePath,'r') as f:
    sbmlString = f.read()

def module_exists(module_name):
    try:
        __import__(module_name)
    except ImportError:
        return False
    else:
        return True

if module_exists('libsbml'):
    import libsbml
    sbml = libsbml.readSBMLFromString(sbmlString)
示例#48
0
def sbml2jsbgn(sbml_str, rxncon=False):
    try:
        import libsbml
    except ImportError:
        raise HTTP(
            500,
            'Your need to install libsbml-python to use this function. For Debian/Ubuntu see http://sbos.eu/doku.php?id=installation_instructions'
        )
    doc = libsbml.readSBMLFromString(sbml_str)
    model = doc.getModel()
    graph = dict(nodes=[], edges=[])
    compartment2species = {}
    seen_species = set()
    #------------------------------------------
    if 'rxncon.org' in sbml_str:
        import re
        pattern_nd = re.compile('(.+)\(([^\)]*)\)')

    def modification2statevariable(mod):
        if '~' in mod:
            mod_split = mod.split('~')
            if mod_split[1] == 'U':
                return mod_split[0]
            if mod_split[0] == 'bd':
                return mod_split[1]
            else:
                return '%s@%s' % (mod_split[1], mod_split[0])
        return ''

    #------------------------------------------
    name_or_id = lambda x: x.getName() or x.getId()

    #------------------------------------------
    def add_node(species_id, source_id, target_id, edge_sbo):
        species = model.getSpecies(species_id)
        if species_id not in seen_species:
            seen_species.add(species_id)
            #-------------------------------------
            if 'rxncon.org' in sbml_str:
                #print species.getName()
                if 'sink' in species_id:
                    node_item = dict(id=species_id,
                                     sbo=291,
                                     is_abstract=0,
                                     data=dict(x=0.0,
                                               y=0.0,
                                               width=60,
                                               height=60))
                    graph['nodes'].append(node_item)
                elif species.getName().startswith(
                        'xXx') and species.getName().endswith('xXx()'):
                    node_item = dict(id=species_id,
                                     sbo=347,
                                     is_abstract=0,
                                     data=dict(x=0.0,
                                               y=0.0,
                                               width=90,
                                               height=60,
                                               label=species.getName()[3:-5]))
                    graph['nodes'].append(node_item)
                elif '__' in species.getName():
                    complex_item = dict(id=species_id,
                                        sbo=253,
                                        is_abstract=0,
                                        data=dict(x=0.0,
                                                  y=0.0,
                                                  width=60,
                                                  height=60,
                                                  subnodes=[]))
                    for subnode_id in species.getName().split('__'):
                        match = re.search(pattern_nd, subnode_id)
                        print 'subnode_id', subnode_id
                        subnode_id, mods = match.group(1), match.group(2)
                        if ('rna' in subnode_id.lower()) or (
                                'dna' in subnode_id.lower()):
                            sbo = 250
                        else:
                            sbo = 252
                        node_item = dict(id=species_id + subnode_id,
                                         sbo=sbo,
                                         is_abstract=0,
                                         data=dict(x=0.0,
                                                   y=0.0,
                                                   width=60,
                                                   height=60,
                                                   label=subnode_id))
                        if mods:
                            show_mods = [
                                modification2statevariable(mod)
                                for mod in mods.split(',') if '!' not in mod
                            ]
                            node_item['data']['statevariable'] = [
                                x for x in show_mods if x
                            ]
                        complex_item['data']['subnodes'].append(species_id +
                                                                subnode_id)
                        graph['nodes'].append(node_item)
                    graph['nodes'].append(complex_item)
                else:
                    match = re.search(pattern_nd, species.getName())
                    spec_id, mods = match.group(1), match.group(2)
                    if ('rna' in spec_id.lower()) or ('dna'
                                                      in spec_id.lower()):
                        sbo = 250
                    else:
                        sbo = 252
                    node_item = dict(id=species_id,
                                     sbo=sbo,
                                     is_abstract=0,
                                     data=dict(x=0.0,
                                               y=0.0,
                                               width=60,
                                               height=60,
                                               label=spec_id))
                    if mods:
                        show_mods = [
                            modification2statevariable(mod)
                            for mod in mods.split(',') if '!' not in mod
                        ]
                        node_item['data']['statevariable'] = [
                            x for x in show_mods if x
                        ]
                    graph['nodes'].append(node_item)
                    #-------------------------------------
            else:
                if 'sink' in species_id or name_or_id(
                        species).lower() == 'emptyset':
                    sbo = 291
                    label = ''
                else:
                    sbo = 285
                    #-------------------------------------
                    #guess sbo
                    for n in range(species.getNumCVTerms()):
                        cvt = species.getCVTerm(n)
                        res = cvt.getResources()
                        for m in range(res.getLength()):
                            resource = res.getValue(m)
                            if 'urn:miriam:obo.chebi' in resource:
                                sbo = 247
                                break
                            if 'urn:miriam:pubchem' in resource:
                                sbo = 247
                                break
                            if 'urn:miriam:uniprot' in resource:
                                sbo = 245
                                break
                    if ('rna' in name_or_id(species).lower()) or (
                            'dna' in name_or_id(species).lower()):
                        sbo = 250
                    #if 'complex' in name_or_id(species).lower():
                    #    sbo = 253
                    label = name_or_id(species)
                #-------------------------------------
                #create node
                node_item = dict(id=species_id,
                                 sbo=sbo,
                                 is_abstract=0,
                                 data=dict(
                                     x=0.0,
                                     y=0.0,
                                     width=60,
                                     height=60,
                                 ))
                if label:
                    node_item['data']['label'] = label
                #-------------------------------------
                graph['nodes'].append(node_item)
        #-------------------------------------
        #create edge
        edge_item = dict(
            id='x',
            source=source_id,
            target=target_id,
            sbo=edge_sbo,
        )
        graph['edges'].append(edge_item)
        #-------------------------------------
        #add compartment (compartments are linked from the compartment as subnodes)
        if species:
            #node_item['data']['compartment'] = species.getCompartment()
            try:
                compartment2species[species.getCompartment()].append(
                    species.getId())
            except KeyError:
                compartment2species[species.getCompartment()] = [
                    species.getId()
                ]
            return species.getCompartment()

    #------------------------------------------
    for reaction in model.getListOfReactions():
        node_item = dict(id=reaction.getId(),
                         sbo=375,
                         is_abstract=0,
                         data=dict(
                             x=0.0,
                             y=0.0,
                             label=name_or_id(reaction),
                             width=20,
                             height=20,
                         ))
        graph['nodes'].append(node_item)
        #---------------
        #reactands
        comp = None
        has_sink = False
        if len(reaction.getListOfReactants()) == 0:
            add_node(reaction.getId() + 'sink',
                     reaction.getId() + 'sink', reaction.getId(), 394)
            has_sink = reaction.getId() + 'sink'
        else:
            for substrate in reaction.getListOfReactants():
                comp = add_node(substrate.getSpecies(), substrate.getSpecies(),
                                reaction.getId(), 394)
                if comp:
                    compartment2species[comp].append(reaction.getId())
        #---------------
        #products
        if len(reaction.getListOfProducts()) == 0:
            add_node(reaction.getId() + 'sink', reaction.getId(),
                     reaction.getId() + 'sink', 393)
            has_sink = reaction.getId() + 'sink'
        else:
            for product in reaction.getListOfProducts():
                comp = add_node(product.getSpecies(), reaction.getId(),
                                product.getSpecies(), 393)
                if comp:
                    compartment2species[comp].append(reaction.getId())
        if has_sink:
            compartment2species[comp].append(has_sink)
        #---------------
        #modifiers
        for modifier in reaction.getListOfModifiers():
            #FIXME check sbo for edge_sbo
            add_node(modifier.getSpecies(), modifier.getSpecies(),
                     reaction.getId(), 168)
    #------------------------------------------
    for compartment in model.getListOfCompartments():
        node_item = dict(id=compartment.getId(),
                         sbo=290,
                         is_abstract=0,
                         data=dict(
                             x=10.0,
                             y=10.0,
                             label=name_or_id(compartment),
                             height=200,
                             width=200,
                         ))
        if compartment.getId() in compartment2species:
            node_item['data']['subnodes'] = list(
                set(compartment2species[compartment.getId()]))
        graph['nodes'].append(node_item)
    for i in range(len(graph['edges'])):
        graph['edges'][i]['id'] = 'edge%s' % i
    #print graph
    return graph