Exemplo n.º 1
0
def __get_events(sbml_model, gillespy_model):
    for i in range(sbml_model.getNumEvents()):
        event = sbml_model.getEvent(i)
        gillespy_assignments = []
        
        trigger = event.getTrigger()
        delay = event.getDelay()
        if delay is not None:
            delay = libsbml.formulaToL3String(delay.getMath())
        expression=libsbml.formulaToL3String(trigger.getMath())
        expression = expression.replace('&&', ' and ').replace('||', ' or ')
        initial_value = trigger.getInitialValue()
        persistent = trigger.getPersistent()
        use_values_from_trigger_time = event.getUseValuesFromTriggerTime()
        gillespy_trigger = gillespy2.EventTrigger(expression=expression, 
            initial_value=initial_value, persistent=persistent)
        assignments = event.getListOfEventAssignments()
        for a in assignments:
            # Convert Non-Constant Parameter to Species
            if a.getVariable() in gillespy_model.listOfParameters:
                gillespy_species = gillespy2.Species(name=a.getVariable(),
                                                        initial_value=gillespy_model.listOfParameters[a.getVariable()].expression,
                                                        mode='continuous', allow_negative_populations=True)
                gillespy_model.delete_parameter(a.getVariable())
                gillespy_model.add_species([gillespy_species])

            gillespy_assignment = gillespy2.EventAssignment(a.getVariable(),
                __get_math(a.getMath()))
            gillespy_assignments.append(gillespy_assignment)
        gillespy_event = gillespy2.Event(
            name=event.getId(), trigger=gillespy_trigger,
            assignments=gillespy_assignments, delay=delay,
            use_values_from_trigger_time=use_values_from_trigger_time)
        gillespy_model.add_event(gillespy_event)
Exemplo n.º 2
0
 def getreactions(self):
     self.reaction_dict = dict()
     for reaction in self.model.getListOfReactions():
         reaction_name = reaction.getId()
         second_reaction_name = reaction.getName()
         kinetic_law = libsbml.formulaToL3String(
             reaction.getKineticLaw().getMath())
         reactants = self.get_and_set(reaction_name,
                                      reaction.getListOfReactants(), "r")
         products = self.get_and_set(reaction_name,
                                     reaction.getListOfProducts(), "p")
         modifiers = self.get_and_set_modifier(reaction, reaction_name)
         parameters = []
         list_of_parameters = list(
             filter(lambda x: isinstance(x, libsbml.Parameter),
                    reaction.getListOfAllElements()))
         # Devo vedere se ci sono parametri locali alla reazione
         for param in list_of_parameters:
             self.parameter_dict[
                 param.getId() + "_" + reaction_name] = Parameter(
                     param.getId(),  # Nome
                     param.getValue(),  # Valore
                     param.getConstant()  # Se è costante oppure no
                 )
             parameters.append(param.getId())
             kinetic_law = kinetic_law.replace(
                 param.getId(),
                 param.getId() + "_" + reaction_name)
         for comp in self.comp_dict:
             kinetic_law = kinetic_law.replace(comp, "1.0")
         self.reaction_dict[reaction_name] = Reaction(
             reaction_name, second_reaction_name, reactants, products,
             modifiers, parameters, kinetic_law)
Exemplo n.º 3
0
    def test_create_kinetic_law_from_sbml(self):
        species = []
        specie_properties = {}
        for i_specie in range(self.species_sbml.size()):
            specie_sbml = self.species_sbml.get(i_specie)
            specie, properties = self.src.get_specie_from_sbml(specie_sbml)
            species.append(specie)
            specie_properties[specie_sbml.getId()] = properties
        units = {}
        units_sbml = self.test_model.getListOfUnitDefinitions()
        for i_unit in range(units_sbml.size()):
            unit_sbml = units_sbml.get(i_unit)
            units[unit_sbml.getId()] = unit_sbml.getName()

        functions = {}
        functions_sbml = self.test_model.getListOfFunctionDefinitions()
        for i_function in range(functions_sbml.size()):
            function_sbml = functions_sbml.get(i_function)
            math_sbml = function_sbml.getMath()
            if math_sbml.isLambda() and math_sbml.getNumChildren():
                eq = libsbml.formulaToL3String(
                    math_sbml.getChild(math_sbml.getNumChildren() - 1))
            else:
                eq = None
            if eq in ('', 'NaN'):
                eq = None
            functions[function_sbml.getId()] = eq

        result = self.src.create_kinetic_law_from_sbml(
            4096, self.reactions_sbml.get(0), species, specie_properties,
            functions, units)
        test_1 = 1922
        self.assertEqual(result['reactants'][0]['_id'], test_1)
Exemplo n.º 4
0
def evaluableMathML(astnode, variables={}, array=False):
    """ Create evaluable python string.

    """
    # replace variables with provided values
    for key, value in variables.iteritems():
        astnode.replaceArgument(key, libsbml.parseFormula(str(value)))

    # get formula
    formula = libsbml.formulaToL3String(astnode)

    # <replacements>
    # FIXME: these are not exhaustive, but are improved with examples
    if array is False:
        # scalar
        formula = formula.replace("&&", 'and')
        formula = formula.replace("||", 'or')
    else:
        # np.array
        formula = formula.replace("max", 'np.max')
        formula = formula.replace("min", 'np.min')
        formula = formula.replace("sum", 'np.sum')
        formula = formula.replace("product", 'np.prod')

    return formula
Exemplo n.º 5
0
def ParseRule(ruleIndex, rule):

    if rule.isAlgebraic():
        raise Exception("Algebraic rules are currently not supported")

#        outputFile.write("Rule; " + ruleId + "; Algebraic; " + ruleName + "\n")
    if rule.isAssignment():
        newRule = sbmltoodepy.dataclasses.AssignmentRuleData()
#        outputFile.write("Rule; " + ruleId + "; Assignment; " + ruleName + "\n")
    if rule.isRate():
        newRule = sbmltoodepy.dataclasses.RateRuleData()
#        outputFile.write("Rule; " + ruleId + "; Rate; " + ruleName + "\n")

    if rule.isSetName():
        newRule.name = str(rule.getName())
    else:
        newRule.name = ''

    if rule.isSetIdAttribute():
        newRule.Id = str(rule.getIdAttribute())
    else:
        newRule.Id = str(ruleIndex + 1)

    newRule.variable = rule.getVariable()
    newRule.math = libsbml.formulaToL3String(rule.getMath())

    if rule.getVariable() == "":
        raise Exception("Algebraic rules are currently not supported")

    else:
        return newRule
Exemplo n.º 6
0
def evaluableMathML(astnode, variables={}, array=False):
    """ Create evaluable python string.

    """
    # replace variables with provided values
    for key, value in variables.iteritems():
        astnode.replaceArgument(key, libsbml.parseFormula(str(value)))

    # get formula
    formula = libsbml.formulaToL3String(astnode)

    # <replacements>
    # FIXME: these are not exhaustive, but are improved with examples
    if array is False:
        # scalar
        formula = formula.replace("&&", 'and')
        formula = formula.replace("||", 'or')
    else:
        # np.array
        formula = formula.replace("max", 'np.max')
        formula = formula.replace("min", 'np.min')
        formula = formula.replace("sum", 'np.sum')
        formula = formula.replace("product", 'np.prod')

    return formula
Exemplo n.º 7
0
    def processCompartments(self):
        """Get compartment information, stoichiometric matrix and fluxes from
        SBML model.

        Arguments:

        Returns:

        Raises:

        """
        compartments = self.sbml.getListOfCompartments()
        self.compartmentSymbols = sp.Matrix(
            [sp.Symbol(comp.getId()) for comp in compartments])
        self.compartmentVolume = sp.Matrix([
            sp.sympify(comp.getVolume())
            if comp.isSetVolume() else sp.sympify(1.0) for comp in compartments
        ])

        compartment_ids = [comp.getId() for comp in compartments]
        for initial_assignment in self.sbml.getListOfInitialAssignments():
            if initial_assignment.getId() in compartment_ids:
                index = compartment_ids.index(initial_assignment.getId())
                self.compartmentVolume[index] = sp.sympify(
                    sbml.formulaToL3String(initial_assignment.getMath()))

        for comp, vol in zip(self.compartmentSymbols, self.compartmentVolume):
            self.replaceInAllExpressions(comp, vol)
Exemplo n.º 8
0
    def test_set_get_math(self):
        model = Model(version='1.2.3', wc_lang_version='4.5.6')

        spec_1_c = Species(id='spec_1[c]')
        spec_2_c = Species(id='spec_2[c]')
        model_objs = {Species: {spec_1_c.id: spec_1_c, spec_2_c.id: spec_2_c}}

        expression, error = ObservableExpression.deserialize(
            'spec_1[c] + spec_2[c]', model_objs)
        assert error is None, str(error)

        sbml_doc = LibSbmlInterface.create_doc()
        sbml_model = LibSbmlInterface.init_model(model, sbml_doc)
        rule = LibSbmlInterface.call_libsbml(sbml_model.createAssignmentRule)
        LibSbmlInterface.set_math(rule.setMath, expression)

        self.assertEqual(
            libsbml.formulaToL3String(
                LibSbmlInterface.call_libsbml(rule.getMath)),
            'Species__spec_1__RB__c__LB__ + Species__spec_2__RB__c__LB__')

        expression_2 = LibSbmlInterface.get_math(rule.getMath,
                                                 ObservableExpression,
                                                 model_objs)
        self.assertTrue(expression_2.is_equal(expression))
        self.assertEqual(expression_2._parsed_expression._obj_tables_tokens,
                         expression._parsed_expression._obj_tables_tokens)
Exemplo n.º 9
0
def print_model_info(sbml_file):
    """Show model info"""

    sbml_reader = libsbml.SBMLReader()
    sbml_doc = sbml_reader.readSBML(sbml_file)
    sbml_model = sbml_doc.getModel()

    print('Model', sbml_file, f'(pwd: {os.getcwd()})')
    print('Species: ', [s.getId() for s in sbml_model.getListOfSpecies()])

    print('Parameters: ',
          [p.getId() for p in sbml_model.getListOfParameters()])

    print('\nReactions:')
    for reaction in sbml_model.getListOfReactions():
        reactants = ' + '.join([
            '%s %s' %
            (int(r.getStoichiometry()) if r.getStoichiometry() > 1 else '',
             r.getSpecies()) for r in reaction.getListOfReactants()
        ])
        products = ' + '.join([
            '%s %s' %
            (int(r.getStoichiometry()) if r.getStoichiometry() > 1 else '',
             r.getSpecies()) for r in reaction.getListOfProducts()
        ])
        reversible = '<' if reaction.getReversible() else ''
        print('%3s: %10s %1s->%10s\t\t[%s]' %
              (reaction.getId(), reactants, reversible, products,
               libsbml.formulaToL3String(reaction.getKineticLaw().getMath())))
Exemplo n.º 10
0
def ParseReaction(reactionIndex, reaction):
    newReaction = sbmltoodepy.dataclasses.ReactionData()
    if reaction.isSetIdAttribute():
        newReaction.Id = reaction.getIdAttribute()
    else:
        newReaction.Id = str(ruleIndex + 1)

    if reaction.isSetName():
        newReaction.name = reaction.getName()
    else:
        newReaction.name = ''

#    outputFile.write("Reaction; " + reactionId + "; " + reactionName + "\n")

    numReactants = reaction.getListOfReactants().size()
    numProducts = reaction.getListOfProducts().size()

    newReaction.reactants = []
    i = 0
    for i in range(numReactants):
        reactantStoich = -float(
            reaction.getListOfReactants().get(i).getStoichiometry())
        reactantSpecies = reaction.getListOfReactants().get(i).getSpecies()

        newReaction.reactants.append([reactantStoich, reactantSpecies])

    i = 0
    for i in range(numProducts):
        productStoich = float(
            reaction.getListOfProducts().get(i).getStoichiometry())
        #        productsString += " , "
        productSpecies = reaction.getListOfProducts().get(i).getSpecies()

        newReaction.reactants.append([productStoich, productSpecies])

    rateLawObject = reaction.getKineticLaw()

    if rateLawObject.getMath() != None:
        newReaction.rateLaw = libsbml.formulaToL3String(
            rateLawObject.getMath())
#        outputFile.write(formulaToString(rateLaw.getMath()) + "\n")
    else:
        raise Exception(
            "Rate law defined by plugin that is not currently supported")
#        outputFile.write("None\n")

    numRateLawParams = rateLawObject.getNumParameters()

    if numRateLawParams > 0:
        newReaction.rxnParameters = []
        for i in range(numRateLawParams):
            param = rateLawObject.getParameter(i)
            #            paramsString += param.getId() + "; " + str(param.getValue())
            newReaction.rxnParameters.append([param.getId(), param.getValue()])

    else:
        newReaction.rxnParameters = []

    return newReaction
Exemplo n.º 11
0
 def getfunctions(self):
     self.function_dict = dict()
     for func in self.model.getListOfFunctionDefinitions():
         function_id = func.getId()
         function_mathml = libsbml.formulaToL3String(func.getMath())[7:-1]
         input_params = [x.strip() for x in function_mathml.split(",")[:-1]]
         math_formula = function_mathml.split(",")[-1]
         self.function_dict[function_id] = Function(function_id, input_params, math_formula)
Exemplo n.º 12
0
 def getinit_assignment(self):
     for init_ass in self.model.getListOfInitialAssignments():
         symbol = init_ass.getSymbol()
         to = libsbml.formulaToL3String(init_ass.getMath())
         if not symbol in self.comp_dict:
             try:
                 self.species_dict[symbol].set_new_ivalue(to)
             except KeyError:
                 self.parameter_dict[symbol].set_value(to)
Exemplo n.º 13
0
 def getElementFromAssignment(element_id):
     assignment = self.sbml.getInitialAssignment(element_id)
     sym = sp.sympify(sbml.formulaToL3String(assignment.getMath()))
     # this is an initial assignment so we need to use
     # initial conditions
     if sym is not None:
         sym = sym.subs(self.symbols['species']['identifier'],
                        self.symbols['species']['value'])
     return sym
Exemplo n.º 14
0
 def get_hazards_vector(sbml_model, species_dict, param_dict):
     h = []
     for reaction_idx, reaction in enumerate(
             sbml_model.getListOfReactions()):
         math = SPN.replace_hazard_species(
             reaction.getKineticLaw().getMath(), sbml_model)
         math = SPN.replace_hazard_parameter(math, param_dict)
         math = libsbml.formulaToL3String(math)
         h.append(math)
     return h
Exemplo n.º 15
0
 def getevents(self):
     self.event_dict = dict()
     for event in self.model.getListOfEvents():
         event_id = event.getId()
         when_condition = libsbml.formulaToL3String(event.getTrigger().getMath())
         # Dal momento che gli and e gli or sono rappresentati come && e || allora li 
         # sostituiamo con and e or i quali sono leggibili da modelica.
         when_condition = when_condition.replace("&&", "and").replace("||", "or")
         event_assignments = [f"reinit({self.species_dict[ass.getId()].amount_name},{libsbml.formulaToL3String(ass.getMath())})" for ass in event.getListOfEventAssignments()]
         self.event_dict[event_id] = Event(event_id, when_condition, event_assignments)
Exemplo n.º 16
0
def __get_math(math):
    math_str = libsbml.formulaToL3String(math)
    replacements = {
        r'\bln\b': 'log',
        r'\^': '**',
        r'\&\&': 'and',
        r'\|\|': 'or'
        }
    for old, new in replacements.items():
        math_str = re.sub(old, new, math_str)
    return math_str
Exemplo n.º 17
0
def __get_math(math):
    math_str = libsbml.formulaToL3String(math)
    replacements = {
        'ln': 'log',
        '^': '**',
        '&&': 'and',
        '||': 'or'
        }
    for old, new in replacements.items():
        math_str = math_str.replace(old, new)
    return math_str
Exemplo n.º 18
0
def assignment_rules_to_dict(
        sbml_model: libsbml.Model,
        filter_function=lambda *_: True,
        remove: bool = False) -> Dict[str, Dict[str, Any]]:
    """
    Turn assignment rules into dictionary.

    Parameters:
        sbml_model:
            a sbml model instance.
        filter_function:
            callback function taking assignment variable as input
            and returning True/False to indicate if the respective rule should
            be turned into an observable.
        remove:
            Remove the all matching assignment rules from the model

    Returns:
        ::

            {
                assigneeId:
                {
                    'name': assigneeName,
                    'formula': formulaString
                }
            }

    """
    warn("This function will be removed in future releases.",
         DeprecationWarning)

    result = {}

    # iterate over rules
    for rule in sbml_model.getListOfRules():
        if rule.getTypeCode() != libsbml.SBML_ASSIGNMENT_RULE:
            continue
        assignee = rule.getVariable()
        parameter = sbml_model.getParameter(assignee)
        # filter
        if parameter and filter_function(parameter):
            result[assignee] = {
                'name': parameter.getName(),
                'formula': libsbml.formulaToL3String(rule.getMath())
            }

    # remove from model?
    if remove:
        for parameter_id in result:
            sbml_model.removeRuleByVariable(parameter_id)
            sbml_model.removeParameter(parameter_id)

    return result
Exemplo n.º 19
0
 def get_hazards_vector(sbml_model, species_dict, param_dict):
     h = []
     for reaction_idx, reaction in enumerate(
             sbml_model.getListOfReactions()):
         math = SPN.replace_hazard_species(
             reaction.getKineticLaw().getMath(),
             sbml_model)
         math = SPN.replace_hazard_parameter(math, param_dict)
         math = libsbml.formulaToL3String(math)
         h.append(math)
     return h
Exemplo n.º 20
0
    def rule_sbtab(self):
        '''
        Builds a Rule SBtab (deprecated).
        '''
        if len(self.model.getListOfRules()) == 0:
            return False

        rule = [[
            '!!SBtab TableID="rule" Document="' +
            self.filename.rstrip('.xml') +
            '" TableType="Rule" TableName="Rule" SBtabVersion="1.0"'
        ], ['']]
        header = ['!Rule', '!Name', '!Formula', '!Unit']
        identifiers = []
        column2ident = {}

        for ar in self.model.getListOfRules():
            value_row = [''] * len(header)
            value_row[0] = ar.getId()
            value_row[1] = ar.getElementName()
            try:
                var = ar.getVariable()
                vr = ar.getMath()
                value_row[2] = var + ' = ' + libsbml.formulaToL3String(vr)
            except:
                pass
            try:
                value_row[3] = ar.getUnits()
            except:
                pass
            try:
                annot_tuples = self.get_annotations(ar)
                for i, annotation in enumerate(annot_tuples):
                    if not ("!Identifiers:" + annotation[1]) in header:
                        identifiers.append(annotation[1])
                        column2ident[annotation[1]] = int(len(header) + 1)
                        header.append('!Identifiers:' + annotation[1])
                        value_row.append('')
                    if annotation[1] in identifiers:
                        value_row[column2ident[annotation[1]] -
                                  1] = annotation[0]
            except:
                pass
            rule.append(value_row)

        rule[1] = header
        rule_SB = rule[0]
        for row in rule[1:]:
            rule_SB.append('\t'.join(row))
        rule_SBtab = '\n'.join(rule_SB)

        return [rule_SBtab, 'rule']
Exemplo n.º 21
0
def ParseInitialAssignment(assignmentIndex, assignment):

    newAssignment = sbmltoodepy.dataclasses.InitialAssignmentData()

    if assignment.isSetIdAttribute():
        newAssignment.Id = str(assignment.getIdAttribute())
    else:
        newAssignment.Id = str(assignmentIndex + 1)

    newAssignment.variable = assignment.getSymbol()
    newAssignment.math = libsbml.formulaToL3String(assignment.getMath())
    newAssignment.name = assignment.getName()
    return newAssignment
Exemplo n.º 22
0
def getRuleVars(rules):
    """Extract free symbols in SBML rule formulas.

    Arguments:
        rules: sbml definitions of rules @type list

    Returns:
    Tuple of free symbolic variables in the formulas all provided rules

    Raises:

    """
    return sp.Matrix([
        sp.sympify(sbml.formulaToL3String(rule.getMath())) for rule in rules
        if rule.getFormula() != ''
    ]).free_symbols
Exemplo n.º 23
0
def astnode_to_expression(astnode: libsbml.ASTNode) -> Any:
    """Convert AstNode to sympy expression.

    An AST node in libSBML is a recursive tree structure; each node has a type,
    a pointer to a value, and a list of children nodes. Each ASTNode node may
    have none, one, two, or more children depending on its type. There are
    node types to represent numbers (with subtypes to distinguish integer,
    real, and rational numbers), names (e.g., constants or variables),
    simple mathematical operators, logical or relational operators and
    functions.

    see also: http://sbml.org/Software/libSBML/docs/python-api/libsbml-math.html

    :param astnode: libsbml.ASTNode
    :return: sympy expression
    """
    formula = libsbml.formulaToL3String(astnode)
    return formula_to_expression(formula)
Exemplo n.º 24
0
    def rule_sbtab(self):
        '''
        Builds a Rule SBtab (deprecated).
        '''
        if len(self.model.getListOfRules()) == 0:
            return False
            
        rule     = [['!!SBtab TableID="rule" Document="'+self.filename.rstrip('.xml')+'" TableType="Rule" TableName="Rule" SBtabVersion="1.0"'],['']]
        header   = ['!Rule','!Name','!Formula','!Unit']
        identifiers  = []
        column2ident = {}

        for ar in self.model.getListOfRules():
            value_row = ['']*len(header)
            value_row[0] = ar.getId()
            value_row[1] = ar.getElementName()
            try:
                var          = ar.getVariable()
                vr           = ar.getMath()
                value_row[2] = var+' = '+libsbml.formulaToL3String(vr)
            except: pass
            try: value_row[3] = ar.getUnits()
            except: pass            
            try:
                annot_tuples = self.get_annotations(ar)
                for i,annotation in enumerate(annot_tuples):
                    if not ("!Identifiers:"+annotation[1]) in header:
                        identifiers.append(annotation[1])
                        column2ident[annotation[1]] = int(len(header)+1)
                        header.append('!Identifiers:'+annotation[1])
                        value_row.append('')
                    if annotation[1] in identifiers:
                        value_row[column2ident[annotation[1]]-1] = annotation[0]
            except: pass
            rule.append(value_row)

        rule[1] = header
        rule_SB = rule[0]
        for row in rule[1:]:
            rule_SB.append('\t'.join(row))
        rule_SBtab = '\n'.join(rule_SB)
            
        return [rule_SBtab,'rule']
Exemplo n.º 25
0
def ParseFunction(functionIndex, function):

    newFunction = sbmltoodepy.dataclasses.FunctionData()
    #    outputFile.write("Function; " + str(functionIndex + 1) + "\n")

    if function.isSetName():
        newFunction.name = function.getName()
    else:
        newFunction.name = ''


#    outputFile.write(function.getId() + ";" + functionName + "\n")
    newFunction.Id = function.getId()
    newFunction.mathString = libsbml.formulaToL3String(function.getMath())
    numArguments = function.getNumArguments()
    funcStringIter = re.finditer(",", newFunction.mathString)
    newFunction.arguments = []
    for i in range(numArguments):
        match = next(funcStringIter)
        newFunction.arguments.append(
            libsbml.formulaToString(function.getArgument(i)))

    newFunction.mathString = newFunction.mathString[match.end() + 1:-1]

    #    functionMath = formulaToL3String(function.getMath())
    #    numArguments = function.getNumArguments()
    #    funcStringIter = re.finditer(",", functionMath)
    #    argumentString = ""
    #    for i in range(numArguments):
    #        match = next(funcStringIter)
    #        argumentString += formulaToString(function.getArgument(i))
    #        if i != numArguments-1:
    #            argumentString += ";"
    #    argumentString += "\n"
    #    functionMath = functionMath[match.end()+1:-1]
    #    outputFile.write(argumentString)
    #    outputFile.write(functionMath + "\n")

    return newFunction
Exemplo n.º 26
0
def writeCode(doc):
    comp_template = 'model.addCompartment(vol=%s, comp_id=\'%s\');'
    species_template = 'model.addSpecies(species_id=\'%s\', amt=%s, comp=\'%s\');'
    param_template = 'model.addParameter(param_id=\'%s\', val=%s, units=\'%s\');'
    rxn_template = 'model.addReaction(reactants=%s, products=%s, expression=\'%s\', local_params=%s, rxn_id=\'%s\');'
    event_template = 'model.addEvent(trigger=\'%s\', assignments=%s, persistent=%s, initial_value=%s, priority=%s, delay=%s, event_id=\'%s\');'
    event_defaults = [True, False, '0', 0]
    assignrule_template = 'model.addAssignmentRule(var=\'%s\', math=\'%s\');'
    raterule_template = 'model.addRateRule(var=\'%s\', math=\'%s\');'
    initassign_template = 'model.addInitialAssignment(symbol=\'%s\', math=\'%s\')'
    init_template = 'import simplesbml\nmodel = simplesbml.sbmlModel(time_units=\'%s\', extent_units=\'%s\', sub_units=\'%s\', level=%s, version=%s);'
    init_defaults = ['second', 'mole', 'mole', 3, 1]
    command_list = []

    if doc.getLevel() == 1:
        print "Warning: SimpleSBML does not support Level 1 SBML models.  Before \
        running this code, set the model to level 2 or 3."

    props = libsbml.ConversionProperties()
    props.addOption('flatten comp', True)
    result = doc.convert(props)
    if (result != libsbml.LIBSBML_OPERATION_SUCCESS):
        raise SystemExit('Conversion failed: (' + str(result) + ')')

    mod = doc.getModel()
    comps = mod.getListOfCompartments()
    species = mod.getListOfSpecies()
    params = mod.getListOfParameters()
    rxns = mod.getListOfReactions()
    events = mod.getListOfEvents()
    rules = mod.getListOfRules()
    inits = []
    if doc.getLevel() == 3 or (doc.getLevel() == 2 and doc.getVersion() > 1):
        inits = mod.getListOfInitialAssignments()

    timeUnits = 'second'
    substanceUnits = 'mole'
    extentUnits = 'mole'
    if doc.getLevel() == 3:
        timeUnits = mod.getTimeUnits()
        extentUnits = mod.getExtentUnits()
        substanceUnits = mod.getSubstanceUnits()
    level = mod.getLevel()
    version = mod.getVersion()
    init_list = [timeUnits, extentUnits, substanceUnits, level, version]
    for i in range(0, 5):
        if init_list[i] == init_defaults[i]:
            init_list[i] = 'del'

    command_list.append(init_template % \
            (init_list[0], init_list[1], init_list[2], init_list[3], init_list[4]))

    for comp in comps:
        if comp.getId() != 'c1':
            if comp.getId()[0] == 'c' and comp.getId()[1:len(comp.getId()
                                                             )].isdigit():
                if comp.getSize() == 1e-15:
                    command_list.append(comp_template % ('del', 'del'))
                else:
                    command_list.append(comp_template %
                                        (comp.getSize(), 'del'))
            else:
                if comp.getSize() == 1e-15:
                    command_list.append(comp_template % ('del', comp.getId()))
                else:
                    command_list.append(comp_template %
                                        (comp.getSize(), comp.getId()))

    for s in species:
        conc = s.getInitialConcentration()
        amt = s.getInitialAmount()
        sid = s.getId()
        if s.getCompartment() == 'c1':
            comp = 'del'
        else:
            comp = s.getCompartment()
        bc = s.getBoundaryCondition()
        if bc:
            sid = "$" + sid
        if isnan(conc) or amt > conc:
            command_list.append(species_template % (sid, str(amt), comp))
        else:
            command_list.append(species_template %
                                ("[" + sid + "]", str(conc), comp))

    for p in params:
        val = p.getValue()
        pid = p.getId()
        if p.getUnits() == 'per_second':
            units = 'del'
        else:
            units = p.getUnits()
        isDelay = pid.find('Delay')
        if isDelay == -1:
            command_list.append(param_template % (pid, str(val), str(units)))

    for v in rxns:
        vid = v.getId()
        if vid[0] == 'v' and vid[1:len(vid)].isdigit():
            vid = 'del'
        reactants = []
        for r in v.getListOfReactants():
            reactants.append(
                (str(r.getStoichiometry()) + ' ' + r.getSpecies()).replace(
                    '1.0 ', ''))
        products = []
        for p in v.getListOfProducts():
            products.append(
                (str(p.getStoichiometry()) + ' ' + p.getSpecies()).replace(
                    '1.0 ', ''))
        expr = libsbml.formulaToString(v.getKineticLaw().getMath())
        local_params = {}
        local_ids = []
        local_values = []
        for k in v.getKineticLaw().getListOfParameters():
            local_ids.append(k.getId())
            local_values.append(k.getValue())
        local_params = dict(zip(local_ids, local_values))
        if len(local_params) == 0:
            local_params = 'del'
        command_list.append(rxn_template % (str(reactants), str(products), \
                    expr, str(local_params), vid))

    for e in events:
        persistent = True
        initialValue = False
        priority = '0'
        eid = e.getId()
        if len(eid) == 0 or (eid[0] == 'e' and eid[1:len(eid)].isdigit()):
            eid = 'del'
        if doc.getLevel() == 3:
            persistent = e.getTrigger().getPersistent()
            initialValue = e.getTrigger().getInitialValue()
            priority = e.getPriority()
            if type(priority) == libsbml.Priority:
                priority = libsbml.formulaToL3String(priority.getMath())
            else:
                priority = '0'
        tri = libsbml.formulaToL3String(e.getTrigger().getMath())
        did = e.getDelay()
        if type(did) == libsbml.Delay:
            delay = libsbml.formulaToL3String(did.getMath())
        else:
            delay = '0'
        assigns = e.getListOfEventAssignments()
        var = []
        values = []
        for assign in assigns:
            var.append(assign.getVariable())
            values.append(libsbml.formulaToL3String(assign.getMath()))
        assigns = dict(zip(var, values))

        event_list = [persistent, initialValue, priority, delay]
        for i in range(0, 4):
            if event_list[i] == event_defaults[i]:
                event_list[i] = 'del'

        command_list.append(event_template % (tri, str(assigns), \
                event_list[0], event_list[1], event_list[2], event_list[3], eid))

    for r in rules:
        sym = r.getVariable()
        math = libsbml.formulaToL3String(r.getMath())
        if r.getTypeCode() == libsbml.SBML_ASSIGNMENT_RULE:
            command_list.append(assignrule_template % (sym, math))
        elif r.getTypeCode() == libsbml.SBML_RATE_RULE:
            command_list.append(raterule_template % (sym, math))
        else:
            next

    for i in inits:
        sym = i.getSymbol()
        math = libsbml.formulaToL3String(i.getMath())
        command_list.append(initassign_template % (sym, math))

    commands = '\n'.join(command_list)
    commands = sub('\w+=\'?del\'?(?=[,)])', '', commands)
    commands = sub('\((, )+', '(', commands)
    commands = sub('(, )+\)', ')', commands)
    commands = sub('(, )+', ', ', commands)
    return commands
Exemplo n.º 27
0
    def event_sbtab(self):
        '''
        Builds an Event SBtab (deprecated).
        '''
        if len(self.model.getListOfEvents()) == 0:
            return False

        event = [[
            '!!SBtab TableID="event" Document="' +
            self.filename.rstrip('.xml') +
            '" TableType="Event" TableName="Event" SBtabVersion="1.0"'
        ], ['']]
        header = [
            '!Event', '!Name', '!Assignments', '!Trigger', '!SBOterm',
            '!Delay', '!UseValuesFromTriggerTime'
        ]
        identifiers = []
        column2ident = {}

        for eve in self.model.getListOfEvents():
            value_row = [''] * len(header)
            value_row[0] = eve.getId()
            value_row[1] = eve.getName()
            if eve.getNumEventAssignments() > 1:
                try:
                    eas = eve.getListOfEventAssignments()
                    ea_entry = ''
                    for ea in eas:
                        var = ea.getVariable()
                        ea_e = ea.getMath()
                        ea_entry += var + ' = ' + libsbml.formulaToL3String(
                            ea_e) + ' | '
                    value_row[2] = ea_entry[:-3]
                except:
                    pass
            else:
                try:
                    eas = eve.getListOfEventAssignments()
                    for ea in eas:
                        var = ea.getVariable()
                        vr = ea.getMath()
                        value_row[2] = var + ' = ' + libsbml.formulaToL3String(
                            vr)
                except:
                    pass
            try:
                trigger = eve.getTrigger().getMath()
                value_row[3] = libsbml.formulaToL3String(trigger)
            except:
                pass
            if str(eve.getSBOTerm()) != '-1':
                value_row[4] = 'SBO:%.7d' % eve.getSBOTerm()
            try:
                value_row[5] = str(eve.getDelay())
            except:
                pass
            try:
                value_row[6] = str(eve.getUseValuesFromTriggerTime())
            except:
                pass
            try:
                annot_tuples = self.get_annotations(eve)
                for i, annotation in enumerate(annot_tuples):
                    if not ("!Identifiers:" + annotation[1]) in header:
                        identifiers.append(annotation[1])
                        column2ident[annotation[1]] = int(len(header) + 1)
                        header.append('!Identifiers:' + annotation[1])
                        value_row.append('')
                    if annotation[1] in identifiers:
                        value_row[column2ident[annotation[1]] -
                                  1] = annotation[0]
            except:
                pass
            event.append(value_row)

        event[1] = header
        event_SB = event[0]
        for row in event[1:]:
            event_SB.append('\t'.join(row))
        event_SBtab = '\n'.join(event_SB)

        return [event_SBtab, 'event']
Exemplo n.º 28
0
def writeCodeFromFile(filename):
    comp_template = 'model.addCompartment(\'%s\');';
    species_template = 'model.addSpecies(\'%s\', %s);';
    param_template = 'model.addParameter(\'%s\', %s);';
    rxn_template = 'model.addReaction(%s, %s, \'%s\', \'%s\');';
    event_template = 'model.addEvent(\'%s\', %s, %s, %s, %s, %s, %s, \'%s\');';
    init_template = 'import simplesbml\nmodel = simplesbml.sbmlModel(\'%s\', \'%s\', \'%s\');';
    command_list = [];
    
    reader = libsbml.SBMLReader();
    doc = reader.readSBMLFromFile(filename);
    mod = doc.getModel();
    comps = mod.getListOfCompartments();
    species = mod.getListOfSpecies();
    params = mod.getListOfParameters();
    rxns = mod.getListOfReactions();
    events = mod.getListOfEvents();
    
    timeUnits = mod.getTimeUnits();
    extentUnits = mod.getExtentUnits();
    substanceUnits = mod.getSubstanceUnits();
    command_list.append(init_template % (timeUnits, extentUnits, substanceUnits));
    
    for comp in comps:
        if comp.getId() != 'c1':
            command_list.append(comp_template % (comp.getId()));
            
    for s in species:
        amt = s.getInitialAmount();
        sid = s.getId();
        bc = s.getBoundaryCondition();
        if bc:
            sid = "$" + sid;
        command_list.append(species_template % (sid, str(amt)));
        
    for p in params:
        val = p.getValue();
        pid = p.getId();
        isDelay = pid.find('Delay');
        if isDelay == -1:
            command_list.append(param_template % (pid, str(val)));
        
    for v in rxns:
        vid = v.getId();
        reactants = [];
        for r in v.getListOfReactants():
            reactants.append(r.getSpecies());
        products = [];
        for p in v.getListOfProducts():
            products.append(p.getSpecies());
        expr = libsbml.formulaToString(v.getKineticLaw().getMath());
        command_list.append(rxn_template % (str(reactants), str(products), expr, vid));
        
    for e in events:
        persistent = e.getTrigger().getPersistent();
        initialValue = e.getTrigger().getInitialValue();
        eid = e.getId();
        priority = libsbml.formulaToL3String(e.getPriority().getMath());
        tri = libsbml.formulaToL3String(e.getTrigger().getMath());
        did = libsbml.formulaToL3String(e.getDelay().getMath());
        delay = mod.getParameter(did).getValue();
        assigns = e.getListOfEventAssignments();
        var = [];
        values = [];
        for assign in assigns:
            var.append(assign.getVariable());
            values.append(libsbml.formulaToL3String(assign.getMath()));
        command_list.append(event_template % (tri, str(delay), str(var), str(values), \
                str(persistent), str(initialValue), str(priority), eid));
    
    commands = '\n'.join(command_list);
    return commands;
Exemplo n.º 29
0
def writeCode(doc):
    comp_template = 'model.addCompartment(vol=%s, comp_id=\'%s\');';
    species_template = 'model.addSpecies(species_id=\'%s\', amt=%s, comp=\'%s\');';
    param_template = 'model.addParameter(param_id=\'%s\', val=%s, units=\'%s\');';
    rxn_template = 'model.addReaction(reactants=%s, products=%s, expression=\'%s\', local_params=%s, rxn_id=\'%s\');';
    event_template = 'model.addEvent(trigger=\'%s\', assignments=%s, persistent=%s, initial_value=%s, priority=%s, delay=%s, event_id=\'%s\');';
    event_defaults = [True, False, '0', 0];
    assignrule_template = 'model.addAssignmentRule(var=\'%s\', math=\'%s\');';
    raterule_template = 'model.addRateRule(var=\'%s\', math=\'%s\');';
    initassign_template = 'model.addInitialAssignment(symbol=\'%s\', math=\'%s\')';
    init_template = 'import simplesbml\nmodel = simplesbml.sbmlModel(time_units=\'%s\', extent_units=\'%s\', sub_units=\'%s\', level=%s, version=%s);';
    init_defaults = ['second', 'mole', 'mole', 3, 1];
    command_list = [];
    
    if doc.getLevel() == 1:
        print "Warning: SimpleSBML does not support Level 1 SBML models.  Before \
        running this code, set the model to level 2 or 3."

    props = libsbml.ConversionProperties()
    props.addOption('flatten comp', True)
    result = doc.convert(props)
    if(result != libsbml.LIBSBML_OPERATION_SUCCESS):
        raise SystemExit('Conversion failed: (' + str(result) + ')');
    
    mod = doc.getModel();
    comps = mod.getListOfCompartments();
    species = mod.getListOfSpecies();
    params = mod.getListOfParameters();
    rxns = mod.getListOfReactions();
    events = mod.getListOfEvents();
    rules = mod.getListOfRules();
    inits = [];
    if doc.getLevel() == 3 or (doc.getLevel() == 2 and doc.getVersion() > 1):
        inits = mod.getListOfInitialAssignments();
    
    timeUnits = 'second';
    substanceUnits = 'mole';
    extentUnits = 'mole';
    if doc.getLevel() == 3:    
        timeUnits = mod.getTimeUnits();
        extentUnits = mod.getExtentUnits();
        substanceUnits = mod.getSubstanceUnits();
    level = mod.getLevel();
    version = mod.getVersion();
    init_list = [timeUnits, extentUnits, substanceUnits, level, version];
    for i in range(0,5):
        if init_list[i] == init_defaults[i]:
            init_list[i] = 'del';
                   
    command_list.append(init_template % \
            (init_list[0], init_list[1], init_list[2], init_list[3], init_list[4]));
    
    for comp in comps:
        if comp.getId() != 'c1':
            if comp.getId()[0] == 'c' and comp.getId()[1:len(comp.getId())].isdigit():
                if comp.getSize() == 1e-15:
                    command_list.append(comp_template % ('del', 'del'));
                else:
                    command_list.append(comp_template % (comp.getSize(), 'del'));
            else:
                if comp.getSize() == 1e-15:
                    command_list.append(comp_template % ('del', comp.getId()));
                else:
                    command_list.append(comp_template % (comp.getSize(), comp.getId()));
            
    for s in species:
        conc = s.getInitialConcentration();
        amt = s.getInitialAmount();
        sid = s.getId();
        if s.getCompartment() == 'c1':
            comp = 'del';
        else:
            comp = s.getCompartment();
        bc = s.getBoundaryCondition();
        if bc:
            sid = "$" + sid;
        if isnan(conc) or amt > conc:
            command_list.append(species_template % (sid, str(amt), comp));
        else:
            command_list.append(species_template % ("[" + sid + "]", str(conc), comp));
        
    for p in params:
        val = p.getValue();
        pid = p.getId();
        if p.getUnits() == 'per_second':
            units = 'del';
        else:
            units = p.getUnits();
        isDelay = pid.find('Delay');
        if isDelay == -1:
            command_list.append(param_template % (pid, str(val), str(units)));
        
    for v in rxns:
        vid = v.getId();
        if vid[0] == 'v' and vid[1:len(vid)].isdigit():
            vid = 'del';
        reactants = [];
        for r in v.getListOfReactants():
            reactants.append((str(r.getStoichiometry()) + ' ' + r.getSpecies()).replace('1.0 ', ''));
        products = [];
        for p in v.getListOfProducts():
            products.append((str(p.getStoichiometry()) + ' ' + p.getSpecies()).replace('1.0 ', ''));
        expr = libsbml.formulaToString(v.getKineticLaw().getMath());
        local_params = {};
        local_ids = [];
        local_values = [];
        for k in v.getKineticLaw().getListOfParameters():
            local_ids.append(k.getId());
            local_values.append(k.getValue());
        local_params = dict(zip(local_ids, local_values));
        if len(local_params) == 0:
            local_params = 'del';
        command_list.append(rxn_template % (str(reactants), str(products), \
                    expr, str(local_params), vid));
        
    for e in events:
        persistent = True;
        initialValue = False;
        priority = '0';
        eid = e.getId();
        if len(eid) == 0 or (eid[0] == 'e' and eid[1:len(eid)].isdigit()):
            eid = 'del';
        if doc.getLevel() == 3:
            persistent = e.getTrigger().getPersistent();
            initialValue = e.getTrigger().getInitialValue();
            priority = e.getPriority();
            if type(priority) == libsbml.Priority:
                priority = libsbml.formulaToL3String(priority.getMath());
            else:
                priority = '0';
        tri = libsbml.formulaToL3String(e.getTrigger().getMath());
        did = e.getDelay();
        if type(did) == libsbml.Delay:
            delay = libsbml.formulaToL3String(did.getMath());
        else:
            delay = '0';
        assigns = e.getListOfEventAssignments();
        var = [];
        values = [];
        for assign in assigns:
            var.append(assign.getVariable());
            values.append(libsbml.formulaToL3String(assign.getMath()));
        assigns = dict(zip(var, values));
        
        event_list = [persistent, initialValue, priority, delay];
        for i in range(0,4):
            if event_list[i] == event_defaults[i]:
                event_list[i] = 'del';
            
        command_list.append(event_template % (tri, str(assigns), \
                event_list[0], event_list[1], event_list[2], event_list[3], eid));
    
    for r in rules:
        sym = r.getVariable();
        math = libsbml.formulaToL3String(r.getMath());
        if r.getTypeCode() == libsbml.SBML_ASSIGNMENT_RULE:
            command_list.append(assignrule_template % (sym, math));
        elif r.getTypeCode() == libsbml.SBML_RATE_RULE:
            command_list.append(raterule_template % (sym, math));
        else:
            next
            
    for i in inits:
        sym = i.getSymbol();
        math = libsbml.formulaToL3String(i.getMath());
        command_list.append(initassign_template % (sym, math));
    
    commands = '\n'.join(command_list);
    commands = sub('\w+=\'?del\'?(?=[,)])', '', commands);
    commands = sub('\((, )+', '(', commands);
    commands = sub('(, )+\)', ')', commands);
    commands = sub('(, )+', ', ', commands);
    return commands;
Exemplo n.º 30
0
    def processRules(self):
        """Process Rules defined in the SBML model.

        Arguments:

        Returns:

        Raises:

        """
        rules = self.sbml.getListOfRules()

        rulevars = getRuleVars(rules)
        fluxvars = self.fluxVector.free_symbols
        specvars = self.symbols['species']['identifier'].free_symbols
        volumevars = self.compartmentVolume.free_symbols
        compartmentvars = self.compartmentSymbols.free_symbols
        parametervars = sp.Matrix([
            sp.Symbol(par.getId()) for par in self.sbml.getListOfParameters()
        ])
        stoichvars = self.stoichiometricMatrix.free_symbols

        assignments = {}

        for rule in rules:
            if rule.getFormula() == '':
                continue
            variable = sp.sympify(rule.getVariable())
            # avoid incorrect parsing of pow(x, -1) in symengine
            formula = sp.sympify(sbml.formulaToL3String(rule.getMath()))
            _check_unsupported_functions(formula, 'Rule')

            if variable in stoichvars:
                self.stoichiometricMatrix = \
                    self.stoichiometricMatrix.subs(variable, formula)

            if variable in specvars:
                raise SBMLException('Species assignment rules are currently'
                                    ' not supported!')

            if variable in compartmentvars:
                raise SBMLException('Compartment assignment rules are'
                                    ' currently not supported!')

            if variable in parametervars:
                try:
                    idx = self.parameterIndex[str(variable)]
                    self.symbols['parameter']['value'][idx] \
                        = float(formula)
                except:
                    self.sbml.removeParameter(str(variable))
                    assignments[str(variable)] = formula

            if variable in fluxvars:
                self.fluxVector = self.fluxVector.subs(variable, formula)

            if variable in volumevars:
                self.compartmentVolume = \
                    self.compartmentVolume.subs(variable, formula)

            if variable in rulevars:
                for nested_rule in rules:
                    nested_formula = sp.sympify(
                        sbml.formulaToL3String(nested_rule.getMath()))
                    nested_formula = \
                        nested_formula.subs(variable, formula)
                    nested_rule.setFormula(str(nested_formula))

                for variable in assignments:
                    assignments[variable].subs(variable, formula)

        # do this at the very end to ensure we have flattened all recursive
        # rules
        for variable in assignments.keys():
            self.replaceInAllExpressions(sp.sympify(variable),
                                         assignments[variable])
Exemplo n.º 31
0
def sbml_statistics(sbml_path):
    """Calculate dictionary of statistics for given SBML model

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

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

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

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

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

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

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

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

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

        # FIXME: annotations & SBO terms

    return s
Exemplo n.º 32
0
    def processReactions(self):
        """Get reactions from SBML model.

        Arguments:

        Returns:

        Raises:

        """
        reactions = self.sbml.getListOfReactions()
        nr = len(reactions)
        nx = len(self.symbols['species']['name'])
        # stoichiometric matrix
        self.stoichiometricMatrix = sp.SparseMatrix(sp.zeros(nx, nr))
        self.fluxVector = sp.zeros(nr, 1)

        assignment_ids = [
            ass.getId() for ass in self.sbml.getListOfInitialAssignments()
        ]
        rulevars = [
            rule.getVariable() for rule in self.sbml.getListOfRules()
            if rule.getFormula() != ''
        ]

        reaction_ids = [
            reaction.getId() for reaction in reactions if reaction.isSetId()
        ]

        def getElementFromAssignment(element_id):
            assignment = self.sbml.getInitialAssignment(element_id)
            sym = sp.sympify(sbml.formulaToL3String(assignment.getMath()))
            # this is an initial assignment so we need to use
            # initial conditions
            if sym is not None:
                sym = sym.subs(self.symbols['species']['identifier'],
                               self.symbols['species']['value'])
            return sym

        def getElementStoichiometry(element):
            if element.isSetId():
                if element.getId() in assignment_ids:
                    symMath = getElementFromAssignment(element.getId())
                    if symMath is None:
                        symMath = sp.sympify(element.getStoichiometry())
                elif element.getId() in rulevars:
                    return sp.Symbol(element.getId())
                else:
                    # dont put the symbol if it wont get replaced by a
                    # rule
                    symMath = sp.sympify(element.getStoichiometry())
            elif element.isSetStoichiometry():
                symMath = sp.sympify(element.getStoichiometry())
            else:
                return sp.sympify(1.0)
            _check_unsupported_functions(symMath, 'Stoichiometry')
            return symMath

        def isConstant(specie):
            return specie in self.constantSpecies or \
                specie in self.boundaryConditionSpecies

        for reactionIndex, reaction in enumerate(reactions):
            for elementList, sign in [(reaction.getListOfReactants(), -1.0),
                                      (reaction.getListOfProducts(), 1.0)]:
                elements = {}
                for index, element in enumerate(elementList):
                    # we need the index here as we might have multiple elements
                    # for the same species
                    elements[index] = {'species': element.getSpecies()}
                    elements[index]['stoichiometry'] = getElementStoichiometry(
                        element)

                for index in elements.keys():
                    if not isConstant(elements[index]['species']):
                        specieIndex = self.speciesIndex[elements[index]
                                                        ['species']]
                        self.stoichiometricMatrix[specieIndex, reactionIndex] \
                            += sign \
                            * elements[index]['stoichiometry'] \
                            * self.speciesConversionFactor[specieIndex] \
                            / self.speciesCompartment[specieIndex]

            # usage of formulaToL3String ensures that we get "time" as time
            # symbol
            math = sbml.formulaToL3String(reaction.getKineticLaw().getMath())
            try:
                symMath = sp.sympify(math)
            except:
                raise SBMLException(f'Kinetic law "{math}" contains an '
                                    'unsupported expression!')
            _check_unsupported_functions(symMath, 'KineticLaw')
            for r in reactions:
                elements = list(r.getListOfReactants()) \
                           + list(r.getListOfProducts())
                for element in elements:
                    if element.isSetId() & element.isSetStoichiometry():
                        symMath = symMath.subs(
                            sp.sympify(element.getId()),
                            sp.sympify(element.getStoichiometry()))

            self.fluxVector[reactionIndex] = symMath
            if any([
                    str(symbol) in reaction_ids
                    for symbol in self.fluxVector[reactionIndex].free_symbols
            ]):
                raise SBMLException(
                    'Kinetic laws involving reaction ids are currently'
                    ' not supported!')
Exemplo n.º 33
0
def writeCode(doc):
    comp_template = 'model.addCompartment(\'%s\');'
    species_template = 'model.addSpecies(\'%s\', %s);'
    param_template = 'model.addParameter(\'%s\', %s);'
    rxn_template = 'model.addReaction(%s, %s, \'%s\', %s, \'%s\');'
    event_template = 'model.addEvent(\'%s\', %s, %s, %s, %s, %s, \'%s\');'
    assignrule_template = 'model.addAssignmentRule(\'%s\', \'%s\');'
    raterule_template = 'model.addRateRule(\'%s\', \'%s\');'
    initassign_template = 'model.addInitialAssignment(\'%s\', \'%s\')'
    init_template = 'import simplesbml\nmodel = simplesbml.sbmlModel(\'%s\', \'%s\', \'%s\');'
    command_list = []

    mod = doc.getModel()
    comps = mod.getListOfCompartments()
    species = mod.getListOfSpecies()
    params = mod.getListOfParameters()
    rxns = mod.getListOfReactions()
    events = mod.getListOfEvents()
    rules = mod.getListOfRules()
    inits = mod.getListOfInitialAssignments()

    timeUnits = mod.getTimeUnits()
    extentUnits = mod.getExtentUnits()
    substanceUnits = mod.getSubstanceUnits()
    command_list.append(init_template %
                        (timeUnits, extentUnits, substanceUnits))

    for comp in comps:
        if comp.getId() != 'c1':
            command_list.append(comp_template % (comp.getId()))

    for s in species:
        amt = s.getInitialAmount()
        sid = s.getId()
        bc = s.getBoundaryCondition()
        if bc:
            sid = "$" + sid
        command_list.append(species_template % (sid, str(amt)))

    for p in params:
        val = p.getValue()
        pid = p.getId()
        isDelay = pid.find('Delay')
        if isDelay == -1:
            command_list.append(param_template % (pid, str(val)))

    for v in rxns:
        vid = v.getId()
        reactants = []
        for r in v.getListOfReactants():
            reactants.append(r.getSpecies())
        products = []
        for p in v.getListOfProducts():
            products.append(p.getSpecies())
        expr = libsbml.formulaToString(v.getKineticLaw().getMath())
        local_ids = []
        local_values = []
        for k in v.getKineticLaw().getListOfLocalParameters():
            local_ids.append(k.getId())
            local_values.append(k.getValue())
        local_params = dict(zip(local_ids, local_values))
        command_list.append(rxn_template % (str(reactants), str(products), \
                    expr, str(local_params), vid))

    for e in events:
        persistent = e.getTrigger().getPersistent()
        initialValue = e.getTrigger().getInitialValue()
        eid = e.getId()
        priority = libsbml.formulaToL3String(e.getPriority().getMath())
        tri = libsbml.formulaToL3String(e.getTrigger().getMath())
        did = libsbml.formulaToL3String(e.getDelay().getMath())
        delay = mod.getParameter(did).getValue()
        assigns = e.getListOfEventAssignments()
        var = []
        values = []
        for assign in assigns:
            var.append(assign.getVariable())
            values.append(libsbml.formulaToL3String(assign.getMath()))
        assigns = dict(zip(var, values))
        command_list.append(event_template % (tri, str(delay), str(assigns), \
                str(persistent), str(initialValue), str(priority), eid))

    for r in rules:
        sym = r.getVariable()
        math = libsbml.formulaToL3String(r.getMath())
        if r.getTypeCode() == libsbml.SBML_ASSIGNMENT_RULE:
            command_list.append(assignrule_template % (sym, math))
        elif r.getTypeCode() == libsbml.SBML_RATE_RULE:
            command_list.append(raterule_template % (sym, math))
        else:
            next

    for i in inits:
        sym = i.getSymbol()
        math = libsbml.formulaToL3String(i.getMath())
        command_list.append(initassign_template % (sym, math))

    commands = '\n'.join(command_list)
    return commands
Exemplo n.º 34
0
    def processSpecies(self):
        """Get species information from SBML model.

        Arguments:

        Returns:

        Raises:

        """
        species = self.sbml.getListOfSpecies()

        self.speciesIndex = {
            species_element.getId(): species_index
            for species_index, species_element in enumerate(species)
        }

        self.symbols['species']['identifier'] = sp.Matrix(
            [sp.Symbol(spec.getId()) for spec in species])
        self.symbols['species']['name'] = [spec.getName() for spec in species]

        self.speciesCompartment = sp.Matrix(
            [sp.Symbol(spec.getCompartment()) for spec in species])

        self.constantSpecies = [
            species_element.getId() for species_element in species
            if species_element.getConstant()
        ]

        self.boundaryConditionSpecies = [
            species_element.getId() for species_element in species
            if species_element.getBoundaryCondition()
        ]
        self.speciesHasOnlySubstanceUnits = [
            specie.getHasOnlySubstanceUnits() for specie in species
        ]

        concentrations = [spec.getInitialConcentration() for spec in species]
        amounts = [spec.getInitialAmount() for spec in species]

        def getSpeciesInitial(index, conc):
            if not math.isnan(conc):
                return sp.sympify(conc)
            if not math.isnan(amounts[index]):
                return \
                    sp.sympify(amounts[index]) / self.speciesCompartment[index]
            return self.symbols['species']['identifier'][index]

        speciesInitial = sp.Matrix([
            getSpeciesInitial(index, conc)
            for index, conc in enumerate(concentrations)
        ])

        species_ids = [spec.getId() for spec in self.sbml.getListOfSpecies()]
        for initial_assignment in self.sbml.getListOfInitialAssignments():
            if initial_assignment.getId() in species_ids:
                index = species_ids.index(initial_assignment.getId())
                symMath = sp.sympify(
                    sbml.formulaToL3String(initial_assignment.getMath()))
                if symMath is not None:
                    _check_unsupported_functions(symMath, 'InitialAssignment')
                    speciesInitial[index] = symMath

        for ix, (symbol, init) in enumerate(
                zip(self.symbols['species']['identifier'], speciesInitial)):
            if symbol == init:
                speciesInitial[ix] = sp.sympify(0.0)

        # flatten initSpecies
        while any([
                species in speciesInitial.free_symbols
                for species in self.symbols['species']['identifier']
        ]):
            speciesInitial = speciesInitial.subs([
                (symbol, init) for symbol, init in zip(
                    self.symbols['species']['identifier'], speciesInitial)
            ])

        self.symbols['species']['value'] = speciesInitial

        if self.sbml.isSetConversionFactor():
            conversion_factor = sp.Symbol(self.sbml.getConversionFactor())
        else:
            conversion_factor = 1.0

        self.speciesConversionFactor = sp.Matrix([
            sp.sympify(specie.getConversionFactor())
            if specie.isSetConversionFactor() else conversion_factor
            for specie in species
        ])
Exemplo n.º 35
0
    def event_sbtab(self):
        '''
        Builds an Event SBtab (deprecated).
        '''
        if len(self.model.getListOfEvents()) == 0:
            return False
            
        event    = [['!!SBtab TableID="event" Document="'+self.filename.rstrip('.xml')+'" TableType="Event" TableName="Event" SBtabVersion="1.0"'],['']]
        header   = ['!Event','!Name','!Assignments','!Trigger','!SBOterm','!Delay','!UseValuesFromTriggerTime']
        identifiers  = []
        column2ident = {}

        for eve in self.model.getListOfEvents():
            value_row = ['']*len(header)
            value_row[0] = eve.getId()
            value_row[1] = eve.getName()
            if eve.getNumEventAssignments() > 1:
                try:
                    eas = eve.getListOfEventAssignments()
                    ea_entry = ''
                    for ea in eas:
                        var       = ea.getVariable()
                        ea_e      = ea.getMath()
                        ea_entry += var+' = '+libsbml.formulaToL3String(ea_e)+' | '
                    value_row[2] = ea_entry[:-3]
                except: pass
            else:
                try:
                    eas = eve.getListOfEventAssignments()
                    for ea in eas:
                        var          = ea.getVariable()
                        vr           = ea.getMath()
                        value_row[2] = var+' = '+libsbml.formulaToL3String(vr)
                except: pass
            try:
                trigger      = eve.getTrigger().getMath()
                value_row[3] = libsbml.formulaToL3String(trigger)
            except: pass
            if str(eve.getSBOTerm()) != '-1': value_row[4] ='SBO:%.7d'%eve.getSBOTerm()
            try: value_row[5] = str(eve.getDelay())
            except: pass
            try: value_row[6] = str(eve.getUseValuesFromTriggerTime())
            except: pass
            try:
                annot_tuples = self.get_annotations(eve)
                for i,annotation in enumerate(annot_tuples):
                    if not ("!Identifiers:"+annotation[1]) in header:
                        identifiers.append(annotation[1])
                        column2ident[annotation[1]] = int(len(header)+1)
                        header.append('!Identifiers:'+annotation[1])
                        value_row.append('')
                    if annotation[1] in identifiers:
                        value_row[column2ident[annotation[1]]-1] = annotation[0]
            except: pass
            event.append(value_row)

        event[1] = header
        event_SB = event[0]
        for row in event[1:]:
            event_SB.append('\t'.join(row))
        event_SBtab = '\n'.join(event_SB)
            
        return [event_SBtab,'event']
Exemplo n.º 36
0
    import tesbml as libsbml

doc = libsbml.SBMLDocument(3, 2)
model = doc.createModel()
model.id = "test_inline_unit"

ud = model.createUnitDefinition()
ud.setId("m")
u = model.createUnit()
u.setKind(libsbml.UNIT_KIND_METRE)
u.setExponent(1.0)
u.setScale(1)
u.setMultiplier(1.0)
ud.addUnit(u)

p = model.createParameter()
p.id = "p"
p.constant = False
p.units = "m"

rule = model.createAssignmentRule()
rule.variable = "p"
ast = libsbml.parseL3FormulaWithModel("5.0 m", model)
rule.setMath(ast)

formula = libsbml.formulaToL3String(ast)
print(formula)


libsbml.writeSBMLToFile(doc, "/home/mkoenig/Desktop/inline_units_py.xml")
Exemplo n.º 37
0
except ImportError:
    import tesbml as libsbml

doc = libsbml.SBMLDocument(3, 2)
model = doc.createModel()
model.id = "test_inline_unit"

ud = model.createUnitDefinition()
ud.setId("m")
u = model.createUnit()
u.setKind(libsbml.UNIT_KIND_METRE)
u.setExponent(1.0)
u.setScale(1)
u.setMultiplier(1.0)
ud.addUnit(u)

p = model.createParameter()
p.id = "p"
p.constant = False
p.units = "m"

rule = model.createAssignmentRule()
rule.variable = "p"
ast = libsbml.parseL3FormulaWithModel("5.0 m", model)
rule.setMath(ast)

formula = libsbml.formulaToL3String(ast)
print(formula)

libsbml.writeSBMLToFile(doc, "/home/mkoenig/Desktop/inline_units_py.xml")
Exemplo n.º 38
0
def writeCode(doc):
    comp_template = 'model.addCompartment(\'%s\');';
    species_template = 'model.addSpecies(\'%s\', %s);';
    param_template = 'model.addParameter(\'%s\', %s);';
    rxn_template = 'model.addReaction(%s, %s, \'%s\', %s, \'%s\');';
    event_template = 'model.addEvent(\'%s\', %s, %s, %s, %s, %s, \'%s\');';
    assignrule_template = 'model.addAssignmentRule(\'%s\', \'%s\');';
    raterule_template = 'model.addRateRule(\'%s\', \'%s\');';
    initassign_template = 'model.addInitialAssignment(\'%s\', \'%s\')';
    init_template = 'import simplesbml\nmodel = simplesbml.sbmlModel(\'%s\', \'%s\', \'%s\');';
    command_list = [];
    
    mod = doc.getModel();
    comps = mod.getListOfCompartments();
    species = mod.getListOfSpecies();
    params = mod.getListOfParameters();
    rxns = mod.getListOfReactions();
    events = mod.getListOfEvents();
    rules = mod.getListOfRules();
    inits = mod.getListOfInitialAssignments();
    
    timeUnits = mod.getTimeUnits();
    extentUnits = mod.getExtentUnits();
    substanceUnits = mod.getSubstanceUnits();
    command_list.append(init_template % (timeUnits, extentUnits, substanceUnits));
    
    for comp in comps:
        if comp.getId() != 'c1':
            command_list.append(comp_template % (comp.getId()));
            
    for s in species:
        amt = s.getInitialAmount();
        sid = s.getId();
        bc = s.getBoundaryCondition();
        if bc:
            sid = "$" + sid;
        command_list.append(species_template % (sid, str(amt)));
        
    for p in params:
        val = p.getValue();
        pid = p.getId();
        isDelay = pid.find('Delay');
        if isDelay == -1:
            command_list.append(param_template % (pid, str(val)));
        
    for v in rxns:
        vid = v.getId();
        reactants = [];
        for r in v.getListOfReactants():
            reactants.append(r.getSpecies());
        products = [];
        for p in v.getListOfProducts():
            products.append(p.getSpecies());
        expr = libsbml.formulaToString(v.getKineticLaw().getMath());
        local_ids = [];
        local_values = [];
        for k in v.getKineticLaw().getListOfLocalParameters():
            local_ids.append(k.getId());
            local_values.append(k.getValue());
        local_params = dict(zip(local_ids, local_values));
        command_list.append(rxn_template % (str(reactants), str(products), \
                    expr, str(local_params), vid));
        
    for e in events:
        persistent = e.getTrigger().getPersistent();
        initialValue = e.getTrigger().getInitialValue();
        eid = e.getId();
        priority = libsbml.formulaToL3String(e.getPriority().getMath());
        tri = libsbml.formulaToL3String(e.getTrigger().getMath());
        did = libsbml.formulaToL3String(e.getDelay().getMath());
        delay = mod.getParameter(did).getValue();
        assigns = e.getListOfEventAssignments();
        var = [];
        values = [];
        for assign in assigns:
            var.append(assign.getVariable());
            values.append(libsbml.formulaToL3String(assign.getMath()));
        assigns = dict(zip(var, values));
        command_list.append(event_template % (tri, str(delay), str(assigns), \
                str(persistent), str(initialValue), str(priority), eid));
    
    for r in rules:
        sym = r.getVariable();
        math = libsbml.formulaToL3String(r.getMath());
        if r.getTypeCode() == libsbml.SBML_ASSIGNMENT_RULE:
            command_list.append(assignrule_template % (sym, math));
        elif r.getTypeCode() == libsbml.SBML_RATE_RULE:
            command_list.append(raterule_template % (sym, math));
        else:
            next
            
    for i in inits:
        sym = i.getSymbol();
        math = libsbml.formulaToL3String(i.getMath());
        command_list.append(initassign_template % (sym, math));
    
    commands = '\n'.join(command_list);
    return commands;