Ejemplo n.º 1
0
 def set_kinetic_law(model, reaction, formula):
     """ Sets the kinetic law in reaction based on given formula. """
     law = reaction.createKineticLaw()
     ast_node = libsbml.parseL3FormulaWithModel(formula, model)
     if ast_node is None:
         logging.error(libsbml.getLastParseL3Error())
     check(law.setMath(ast_node), 'set math in kinetic law')
     return law
Ejemplo n.º 2
0
 def set_kinetic_law(model, reaction, formula):
     """ Sets the kinetic law in reaction based on given formula. """
     law = reaction.createKineticLaw()
     ast_node = libsbml.parseL3FormulaWithModel(formula, model)
     if ast_node is None:
         logging.error(libsbml.getLastParseL3Error())
     check(law.setMath(ast_node), 'set math in kinetic law')
     return law
Ejemplo n.º 3
0
def formula_to_astnode(formula: str) -> libsbml.ASTNode:
    """Convert formula string to ASTNode.

    :param formula: SBML formula string
    :return: libsbml.ASTNode
    """
    astnode = libsbml.parseL3Formula(formula)
    if not astnode:
        logging.error(f"Formula could not be parsed: '{formula}'")
        logging.error(libsbml.getLastParseL3Error())
    return astnode
Ejemplo n.º 4
0
def ast_node_from_formula(model, formula):
    """ Parses the ASTNode from given formula string with model.

    :param model: SBMLModel instance
    :param formula: formula str
    :return:
    """
    ast_node = libsbml.parseL3FormulaWithModel(formula, model)
    if not ast_node:
        logging.error("Formula could not be parsed: '{}'".format(formula))
        logging.error(libsbml.getLastParseL3Error())
    return ast_node
Ejemplo n.º 5
0
def ast_node_from_formula(model, formula):
    """ Parses the ASTNode from given formula string with model.

    :param model: SBMLModel instance
    :param formula: formula str
    :return:
    """
    ast_node = libsbml.parseL3FormulaWithModel(formula, model)
    if not ast_node:
        logging.error("Formula could not be parsed: '{}'".format(formula))
        logging.error(libsbml.getLastParseL3Error())
    return ast_node
Ejemplo n.º 6
0
def distrib_all():
    """ Create simple distrib model.

    :return:
    """
    doc = _distrib_doc()
    model = doc.createModel()  # type: libsbml.Model

    # extended math approach
    formulas_data = [
        ('p_normal_1', 'normal(0, 1)'),
        ('p_normal_2', 'normal(0, 1, 0, 10)'),
        ('p_uniform', 'uniform(5, 10)'),
        ('p_bernoulli', 'bernoulli(0.4)'),
        ('p_binomial_1', 'binomial(100, 0.3)'),
        ('p_binomial_2', 'binomial(100, 0.3, 0, 2)'),
        ('p_cauchy_1', 'cauchy(0, 1)'),
        ('p_cauchy_2', 'cauchy(0, 1, 0, 5)'),
        ('p_chisquare_1', 'chisquare(10)'),
        ('p_chisquare_2', 'chisquare(10, 0, 10)'),
        ('p_exponential_1', 'exponential(1.0)'),
        ('p_exponential_2', 'exponential(1.0, 0, 10)'),
        ('p_gamma_1', 'gamma(0, 1)'),
        ('p_gamma_2', 'gamma(0, 1, 0, 10)'),
        ('p_laplace_1', 'laplace(0, 1)'),
        ('p_laplace_2', 'laplace(0, 1, 0, 10)'),
        ('p_lognormal_1', 'lognormal(0, 1)'),
        ('p_lognormal_2', 'lognormal(0, 1, 0, 10)'),
        ('p_poisson_1', 'poisson(0.5)'),
        ('p_poisson_2', 'poisson(0.5, 0, 10)'),
        ('p_raleigh_1', 'rayleigh(0.5)'),
        ('p_raleigh_2', 'rayleigh(0.5, 0, 10)'),
    ]

    # create parameters with distribution assignments
    for pid, formula in formulas_data:
        print("{} = {}".format(pid, formula))
        p = _create_parameter(pid, model=model)  # type: libsbml.Parameter
        assignment = model.createInitialAssignment(
        )  # type: libsbml.InitialAssignment
        assignment.setSymbol(pid)
        ast_node = libsbml.parseL3FormulaWithModel(formula, model)
        if ast_node is None:
            raise IOError("{}, {}".format(formula,
                                          libsbml.getLastParseL3Error()))
        assignment.setMath(ast_node), "setting math"

    return doc
Ejemplo n.º 7
0
def ast_node_from_formula(model, formula):
    """Parses the ASTNode from given formula string with model.

    :param model: SBMLModel instance
    :param formula: formula str
    :return:
    """
    # sanitize formula (allow double and int assignments)
    if not isinstance(formula, str):
        formula = str(formula)

    ast_node = libsbml.parseL3FormulaWithModel(formula, model)
    if not ast_node:
        logger.error("Formula could not be parsed: '{}'".format(formula))
        logger.error(libsbml.getLastParseL3Error())
    return ast_node
Ejemplo n.º 8
0
def distrib_all():
    """ Create simple distrib model.

    :return:
    """
    doc = _distrib_doc()
    model = doc.createModel()  # type: libsbml.Model

    # extended math approach
    formulas_data = [
        ('p_normal_1', 'normal(0, 1)'),
        ('p_normal_2', 'normal(0, 1, 0, 10)'),
        ('p_uniform', 'uniform(5, 10)'),
        ('p_bernoulli', 'bernoulli(0.4)'),
        ('p_binomial_1', 'binomial(100, 0.3)'),
        ('p_binomial_2', 'binomial(100, 0.3, 0, 2)'),
        ('p_cauchy_1', 'cauchy(0, 1)'),
        ('p_cauchy_2', 'cauchy(0, 1, 0, 5)'),
        ('p_chisquare_1', 'chisquare(10)'),
        ('p_chisquare_2', 'chisquare(10, 0, 10)'),
        ('p_exponential_1', 'exponential(1.0)'),
        ('p_exponential_2', 'exponential(1.0, 0, 10)'),
        ('p_gamma_1', 'gamma(0, 1)'),
        ('p_gamma_2', 'gamma(0, 1, 0, 10)'),
        ('p_laplace_1', 'laplace(0, 1)'),
        ('p_laplace_2', 'laplace(0, 1, 0, 10)'),
        ('p_lognormal_1', 'lognormal(0, 1)'),
        ('p_lognormal_2', 'lognormal(0, 1, 0, 10)'),
        ('p_poisson_1', 'poisson(0.5)'),
        ('p_poisson_2', 'poisson(0.5, 0, 10)'),
        ('p_raleigh_1', 'rayleigh(0.5)'),
        ('p_raleigh_2', 'rayleigh(0.5, 0, 10)'),
    ]

    # create parameters with distribution assignments
    for pid, formula in formulas_data:
        print("{} = {}".format(pid, formula))
        p = _create_parameter(pid, model=model)  # type: libsbml.Parameter
        assignment = model.createInitialAssignment()  # type: libsbml.InitialAssignment
        assignment.setSymbol(pid)
        ast_node = libsbml.parseL3FormulaWithModel(formula, model)
        if ast_node is None:
            raise IOError("{}, {}".format(formula,
                                          libsbml.getLastParseL3Error()))
        assignment.setMath(ast_node), "setting math"

    return doc
Ejemplo n.º 9
0
    def add_interpolator_to_model(interpolator: "Interpolator",
                                  model: libsbml.Model) -> None:
        """Add interpolator to model.

        The parameters, formulas and rules have to be added to the SBML model.

        :param interpolator:
        :param model: Model
        :return:
        """

        # create parameter
        pid = interpolator.yid

        # if parameter exists remove it
        if model.getParameter(pid):
            logger.warning(
                "Model contains parameter: {}. Parameter is removed.".format(
                    pid))
            model.removeParameter(pid)

        # if assignment rule exists remove it
        for rule in model.getListOfRules():
            if rule.isAssignment():
                if rule.getVariable() == pid:
                    model.removeRule(rule)
                    break

        p = model.createParameter()
        p.setId(pid)
        p.setName(pid)
        p.setConstant(False)

        # create rule
        rule = model.createAssignmentRule()
        rule.setVariable(pid)
        formula = interpolator.formula()
        ast_node = libsbml.parseL3FormulaWithModel(formula, model)
        if ast_node is None:
            logger.warning(libsbml.getLastParseL3Error())
        else:
            rule.setMath(ast_node)
Ejemplo n.º 10
0
def formula_to_astnode(
    formula: str, model: Optional[libsbml.Model] = None
) -> libsbml.ASTNode:
    """Convert formula string to ASTNode.

    :param formula: SBML formula string
    :param model: libsbml.Model
    :return: libsbml.ASTNode
    """
    if model:
        astnode = libsbml.parseL3FormulaWithModel(formula, model)
    else:
        astnode = libsbml.parseL3Formula(formula)
    if not astnode:
        logger.error(f"Formula could not be parsed: '{formula}'")
        logger.error(libsbml.getLastParseL3Error())
        raise ValueError(
            f"Formula could not be parsed: '{formula}'.\n"
            f"{libsbml.getLastParseL3Error()}"
        )
    return astnode
Ejemplo n.º 11
0
    def create_sbml(self, sbase):
        """ Create libsbml Uncertainty.

        :param model:
        :return:
        """
        sbase_distrib = sbase.getPlugin(
            "distrib")  # type: libsbml.DistribSBasePlugin
        uncertainty = sbase_distrib.createUncertainty(
        )  # type: libsbml.Uncertainty

        for uncertParameter in self.uncertParameters:
            up = None
            if uncertParameter.type in [
                    libsbml.DISTRIB_UNCERTTYPE_INTERQUARTILERANGE,
                    libsbml.DISTRIB_UNCERTTYPE_CREDIBLEINTERVAL,
                    libsbml.DISTRIB_UNCERTTYPE_CONFIDENCEINTERVAL,
                    libsbml.DISTRIB_UNCERTTYPE_RANGE,
            ]:

                up = uncertainty.createUncertSpan()  # type: libsbml.UncertSpan
                up.setType(uncertParameter.type)
                if uncertParameter.valueLower is not None:
                    up.setValueLower(uncertParameter.valueLower)
                if uncertParameter.valueUpper is not None:
                    up.setValueUpper(uncertParameter.valueUpper)
                if uncertParameter.varLower is not None:
                    up.setVarLower(uncertParameter.varLower)
                if uncertParameter.varUpper is not None:
                    up.setValueLower(uncertParameter.varUpper)

            elif uncertParameter.type in [
                    libsbml.DISTRIB_UNCERTTYPE_COEFFIENTOFVARIATION,
                    libsbml.DISTRIB_UNCERTTYPE_KURTOSIS,
                    libsbml.DISTRIB_UNCERTTYPE_MEAN,
                    libsbml.DISTRIB_UNCERTTYPE_MEDIAN,
                    libsbml.DISTRIB_UNCERTTYPE_MODE,
                    libsbml.DISTRIB_UNCERTTYPE_SAMPLESIZE,
                    libsbml.DISTRIB_UNCERTTYPE_SKEWNESS,
                    libsbml.DISTRIB_UNCERTTYPE_STANDARDDEVIATION,
                    libsbml.DISTRIB_UNCERTTYPE_STANDARDERROR,
                    libsbml.DISTRIB_UNCERTTYPE_VARIANCE,
            ]:
                up = uncertainty.createUncertParameter(
                )  # type: libsbml.UncertParameter
                up.setType(uncertParameter.type)
                if uncertParameter.value is not None:
                    up.setValue(uncertParameter.value)
                if uncertParameter.var is not None:
                    up.setValue(uncertParameter.var)
            else:
                logging.error(
                    "Unsupported UncertParameter or UncertSpan type: %s",
                    uncertParameter.type)

            if up and uncertParameter.unit:
                up.setUnits(Unit.get_unit_string(uncertParameter.unit))

        # create a distribution uncertainty
        if self.formula:
            model = sbase.getModel()
            up = uncertainty.createUncertParameter(
            )  # type: libsbml.UncertParameter
            up.setType(libsbml.DISTRIB_UNCERTTYPE_DISTRIBUTION)
            for key in [
                    "normal", "uniform", "bernoulli", "binomial", "cauchy",
                    "chisquare", "exponential", "gamma", "laplace",
                    "lognormal", "poisson", "raleigh"
            ]:
                if key in self.formula:
                    up.setDefinitionURL(
                        "http://www.sbml.org/sbml/symbols/distrib/{}".format(
                            key))
                    ast = libsbml.parseL3FormulaWithModel(self.formula, model)
                    if ast is None:
                        logging.error(libsbml.getLastParseL3Error())
                    else:
                        check(up.setMath(ast), 'set math in distrib formula')

        return uncertainty