def __init__(self, string, sbml=None):
     super().__init__()
     self.knownatts.add("doc")
     self.knownatts.add("rr")
     self.knownatts.add("outputVariables")
     self.knownatts.add("rr_default_int")
     self.outputVariables = ['time']
     print("This is the constructor method.")
     if isfile(string):
         super().__setattr__("doc", tesbml.readSBMLFromFile(string))
         if self.doc.getModel() == None:
             raise Exception("No SBML model present at '" + string + "'.")
     elif sbml is not None:
         self.doc = sbml.clone()
     else:
         self.doc = tesbml.readSBMLFromString(string)
         if self.doc.getModel() == None:
             raise Exception(
                 "Unable to parse string as an SBML model, or file not found."
             )
     self.rr = roadrunner.RoadRunner(self.doc.toSBML())
     self.rr_default_int = self.rr.getIntegrator().getName()
     self.saveModelElements()
     self.saveRRElements()
     self['time'] = 0
Exemple #2
0
 def __init__(self, model):
     if isinstance(model, tellurium.roadrunner.extended_roadrunner.ExtendedRoadRunner):
         model_sbml = model.getSBML()
         self.doc = libsbml.readSBMLFromString(model_sbml)
         self._model = self.doc.getModel()
     elif isinstance(model, string_types):
         self.doc = libsbml.readSBMLFromString(model)
         self._model = self.doc.getModel()
     elif isinstance(model, libsbml.SBMLDocument):
         self.doc = model
         self._model = self.doc.getModel()
     elif isinstance(model, libsbml.Model):
         self._model = model
     else:
         raise Exception('SBML Input is not valid')
     self._name = 'sbml_model'
     self._sp_idx_dict = {sp.getId(): idx for idx, sp in enumerate(self.model.getListOfSpecies())}
Exemple #3
0
 def __init__(self, model):
     if isinstance(
             model,
             tellurium.roadrunner.extended_roadrunner.ExtendedRoadRunner):
         model_sbml = model.getSBML()
         self.doc = libsbml.readSBMLFromString(model_sbml)
         self.model = self.doc.getModel()
     elif isinstance(model, string_types):
         self.doc = libsbml.readSBMLFromString(model)
         self.model = self.doc.getModel()
     elif isinstance(model, libsbml.SBMLDocument):
         self.doc = model
         self.model = self.doc.getModel()
     elif isinstance(model, libsbml.Model):
         self.model = model
     else:
         raise Exception('SBML Input is not valid')
     self.graph = None
def makeModel(filenum=FILENUM):
    """
    :param str file_num:
    :return libsbml.Model:
    """
    url = makeURL(filenum)
    response = requests.get(url).content
    document = tesbml.readSBMLFromString(response.decode("utf-8"))
    return document.getModel()
Exemple #5
0
    def __init__(self, sbmlStr):
        try:
            import tesbml
        except ImportError:
            raise Exception(
                "Cannot import tesbml. Try tellurium.installPackage('tesbml')")

        self.doc = tesbml.readSBMLFromString(sbmlStr)
        self.model = self.doc.getModel()

        self.species_map = {}
        self.species_symbol_map = {}
        self.use_species_names = False
        self.use_ids = True

        from collections import defaultdict
        self.accumulators = {}
        self.accumulator_list = []

        def reactionParticipant(participant, stoich):
            stoich_sign = 1
            if stoich < 0:
                stoich_sign = -1
            if participant.isSetStoichiometry():
                stoich = participant.getStoichiometry()
            elif participant.isSetStoichiometryMath():
                raise RuntimeError('Stoichiometry math not supported')
            self.accumulators[participant.getSpecies()].addReaction(
                r, stoich_sign * stoich)

        newReactant = lambda p: reactionParticipant(p, -1)
        newProduct = lambda p: reactionParticipant(p, 1)

        for s in (self.model.getSpecies(i)
                  for i in range(self.model.getNumSpecies())):
            self.species_map[s.getId()] = s
            if s.isSetName() and self.use_species_names:
                self.species_symbol_map[s.getId()] = s.getName()
            else:
                self.species_symbol_map[s.getId()] = s.getId()
            a = Accumulator(s.getId())
            self.accumulators[s.getId()] = a
            self.accumulator_list.append(a)

        for r in (self.model.getReaction(i)
                  for i in range(self.model.getNumReactions())):
            for reactant in (r.getReactant(i)
                             for i in range(r.getNumReactants())):
                newReactant(reactant)
            for product in (r.getProduct(i)
                            for i in range(r.getNumProducts())):
                newProduct(product)
def run(filenum):
    url = "%s%s" % (URL_BASE, format(filenum, '010d'))
    response = requests.get(url).content
    document = tesbml.readSBMLFromString(response.decode("utf-8"))
    model = document.getModel()
    stg = " "
    for i in range(model.getNumReactions()):
        reaction = model.getReaction(i)
        for j in range(reaction.getNumReactants()):
            reactant = reaction.getReactant(j)
            stg = stg + " + " + reactant.getSpecies()
        stg = stg + " -> "
        for k in range(reaction.getNumProducts()):
            product = reaction.getProduct(k)
            stg = stg + " + " + product.getSpecies()
        stg = stg + ";\n"
    return stg
Exemple #7
0
    def __init__(self, sbmlStr):
        try:
            import tesbml
        except ImportError:
            raise Exception("Cannot import tesbml. Try tellurium.installPackage('tesbml')")
            
        self.doc = tesbml.readSBMLFromString (sbmlStr)
        self.model = self.doc.getModel()
               
        self.species_map = {}
        self.species_symbol_map = {}
        self.use_species_names = False
        self.use_ids = True

        from collections import defaultdict
        self.accumulators = {}
        self.accumulator_list = []
      
        def reactionParticipant(participant, stoich):
            stoich_sign = 1
            if stoich < 0:
                stoich_sign = -1
            if participant.isSetStoichiometry():
                stoich = participant.getStoichiometry()
            elif participant.isSetStoichiometryMath():
                raise RuntimeError('Stoichiometry math not supported')
            self.accumulators[participant.getSpecies()].addReaction(r, stoich_sign*stoich)

        newReactant = lambda p: reactionParticipant(p, -1)      
        newProduct  = lambda p: reactionParticipant(p, 1)

        for s in (self.model.getSpecies(i) for i in range(self.model.getNumSpecies())):
            self.species_map[s.getId()] = s
            if s.isSetName() and self.use_species_names:
                self.species_symbol_map[s.getId()] = s.getName()
            else:
                self.species_symbol_map[s.getId()] = s.getId()
            a = Accumulator(s.getId())
            self.accumulators[s.getId()] = a
            self.accumulator_list.append(a)

        for r in (self.model.getReaction(i) for i in range(self.model.getNumReactions())):
            for reactant in (r.getReactant(i) for i in range(r.getNumReactants())):
                newReactant(reactant)
            for product in (r.getProduct(i) for i in range(r.getNumProducts())):
                newProduct(product)
Exemple #8
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, string_types):
         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)
Exemple #9
0
    def __init__(self, sim_model, cmap='RdBu_r'):
        if isinstance(
                sim_model,
                tellurium.roadrunner.extended_roadrunner.ExtendedRoadRunner):
            model_sbml = sim_model.getSBML()
            self.doc = libsbml.readSBMLFromString(model_sbml)
            self.model = self.doc.getModel()
        else:
            raise Exception('Model must be a roadrunner instance')

        required_selections = ['time'] + [s.getId() for s in self.model.species] + \
                              [r.getId() for r in self.model.reactions]
        sim_selections = sim_model.selections

        # Check that the simulation selections include all species and reactions rate values
        if not all(x in required_selections for x in sim_selections):
            raise ValueError(
                'To use this visualization you must use '
                'this simulator selection \n {0}'.format(required_selections))
        self.y = sim_model.getSimulationData()
        self.sp_graph = None
        self.type_viz = ''
        self.cmap = cmap
Exemple #10
0
def generateParameterList(bifurcationModel, parameterList=None):
    """
    Generates a list of global parameters, floating and boundary species, and 
    a second list containing the current values for these parameters in the 
    loaded model. Conserved sum parameters, generated becaused 
    conserved moiety analysis is employed, are removed. Parameters defined
    by an assignement rule are removed.
    """
    if not parameterList:
        parameterList = bifurcationModel.getGlobalParameterIds() + list(
            bifurcationModel.getFloatingSpeciesInitialConcentrationIds(
            )) + bifurcationModel.getBoundarySpeciesIds()
        paramValues = list(bifurcationModel.getGlobalParameterValues()) + list(
            bifurcationModel.getFloatingSpeciesConcentrations()) + list(
                bifurcationModel.getBoundarySpeciesConcentrations())
    else:
        paramValues = []
        for parameter in parameterList:
            paramValues.append(bifurcationModel.getValue(parameter))
    doc = tesbml.readSBMLFromString(bifurcationModel.getCurrentSBML())
    model = doc.getModel()
    lenListRules = len(model.getListOfRules())
    assignmentRuleParams = []
    for i in range(lenListRules):
        assignmentRule = model.getRule(i)
        if (assignmentRule.getTypeCode() == tesbml.SBML_ASSIGNMENT_RULE):
            assignmentRuleParams.append(assignmentRule.getVariable())
    for element in range(len(parameterList)):
        for n in assignmentRuleParams:
            if (parameterList[element].startswith('_CSUM')) or (
                    parameterList[element] == n):
                parameterList[element] = 'remove'
                paramValues[element] = 'remove'
    parameterList = list(filter(lambda a: a != 'remove', parameterList))
    paramValues = list(filter(lambda a: a != 'remove', paramValues))
    return parameterList, paramValues
Exemple #11
0
def generateReactionListFromAntimony(antStr):
    """
    """
    import tesbml
    import sympy
    
    r = te.loada(antStr)
    
    numBnd = r.getNumBoundarySpecies()
    numFlt = r.getNumFloatingSpecies()
    boundaryId = r.getBoundarySpeciesIds()
    floatingId = r.getFloatingSpeciesIds()
    nr = r.getNumReactions()
    
    # prepare symbols for sympy
    boundaryId_sympy = [] 
    floatingId_sympy = []
    
    # Fix issues with reserved characters
    for i in range(numBnd):
        if boundaryId[i] == 'S':
            boundaryId_sympy.append('_S')
        else:
            boundaryId_sympy.append(boundaryId[i])
    
    for i in range(numFlt):
        if floatingId[i] == 'S':
            floatingId_sympy.append('_S')
        else:
            floatingId_sympy.append(floatingId[i])
    
    paramIdsStr = ' '.join(r.getGlobalParameterIds())
    floatingIdsStr = ' '.join(floatingId_sympy)
    boundaryIdsStr = ' '.join(boundaryId_sympy)
    comparmentIdsStr = ' '.join(r.getCompartmentIds())
    
    allIds = paramIdsStr + ' ' + floatingIdsStr + ' ' + boundaryIdsStr + ' ' + comparmentIdsStr
    
    avsym = sympy.symbols(allIds)
    
    # extract reactant, product, modifiers, and kinetic laws
    rct = []
    prd = []
    mod = []
    r_type = []
    kineticLaw = []
    mod_type = []
    
    doc = tesbml.readSBMLFromString(r.getSBML())
    sbmlmodel = doc.getModel()

    for slr in sbmlmodel.getListOfReactions():
        temprct = []
        tempprd = []
        tempmod = []
        
        sbmlreaction = sbmlmodel.getReaction(slr.getId())
        for sr in range(sbmlreaction.getNumReactants()):
            sbmlrct = sbmlreaction.getReactant(sr)
            temprct.append(sbmlrct.getSpecies())
        for sp in range(sbmlreaction.getNumProducts()):
            sbmlprd = sbmlreaction.getProduct(sp)
            tempprd.append(sbmlprd.getSpecies())
        for sm in range(sbmlreaction.getNumModifiers()):
            sbmlmod = sbmlreaction.getModifier(sm)
            tempmod.append(sbmlmod.getSpecies())
        kl = sbmlreaction.getKineticLaw()
        
        rct.append(sorted(temprct, key=lambda v: (v.upper(), v[0].islower())))
        prd.append(sorted(tempprd, key=lambda v: (v.upper(), v[0].islower())))
        mod.append(sorted(tempmod, key=lambda v: (v.upper(), v[0].islower())))
        
        # Update kinetic law according to change in species name
        kl_split = kl.getFormula().split(' ')
        for i in range(len(kl_split)):
            if kl_split[i] == 'S':
                kl_split[i] = '_S'
        
        kineticLaw.append(' '.join(kl_split))
    
    # use sympy for analyzing modifiers weSmart
    for ml in range(len(mod)):
        mod_type_temp = []
        expression = kineticLaw[ml]
        n,d = sympy.fraction(expression)
        for ml_i in range(len(mod[ml])):
            if n.has(mod[ml][ml_i]):
                mod_type_temp.append('activator')
            elif d.has(mod[ml][ml_i]) and not n.has(mod[ml][ml_i]):
                mod_type_temp.append('inhibitor')
            elif n.has(mod[ml][ml_i]) and d.has(mod[ml][ml_i]):
                mod_type_temp.append('inhibitor_activator')
            else:
                mod_type_temp.append('modifier')
        mod_type.append(mod_type_temp)
        
        # In case all products are in rate law, assume it is a reversible reaction
        if all(ext in str(n) for ext in prd[ml]):
            r_type.append('reversible')
        else:
            r_type.append('irreversible')
        
    reactionList = []
    
    for i in range(nr):
        inhib = []
        activ = []
        rct_temp = []
        prd_temp = []
        
        if len(rct[i]) == 1:
            if len(prd[i]) == 1:
                rType = 0
            elif len(prd[i]) == 2:
                rType = 2
        elif len(rct[i]) == 2:
            if len(prd[i]) == 1:
                rType = 1
            elif len(prd[i]) == 2:
                rType = 3
        
        for j in range(len(rct[i])):
            rct_temp.append(int(rct[i][j][1:]))
            
        for j in range(len(prd[i])):
            prd_temp.append(int(prd[i][j][1:]))
        
        if len(mod_type[i]) == 0:
            regType = 0
        else:
            for k in range(len(mod_type[i])):
                if mod_type[i][k] == 'inhibitor':
                    inhib.append(int(mod[i][k][1:]))
                elif mod_type[i][k] == 'activator':
                    activ.append(int(mod[i][k][1:]))
                
                if len(inhib) > 0:
                    if len(activ) == 0:
                        regType = 1
                    else:
                        regType = 3
                else:
                    regType = 2
                
        if r_type[i] == 'reversible':
            revType = 1
        else:
            revType = 0

        reactionList.append([rType, 
                             regType, 
                             revType, 
                             rct_temp, 
                             prd_temp,
                             activ,
                             inhib])
    
    return reactionList
Exemple #12
0
 def setUp(self) -> None:
     self.sbml = biomodels_download(self.model_id)
     self.doc = libsbml.readSBMLFromString(self.sbml)
     # self.doc.setLevelAndVersion(3, 2)
     print(self.doc.getLevel(), self.doc.getVersion())