def set_fields(self, obj, model): """ Set fields on given object. :param obj: event :param model: :return: """ super(Event, self).set_fields(obj) obj.setUseValuesFromTriggerTime(True) t = obj.createTrigger() t.setInitialValue(self.trigger_initialValue) # False ! not supported by Copasi -> lame fix via time t.setPersistent(self.trigger_persistent) # True ! not supported by Copasi -> careful with usage ast_trigger = libsbml.parseL3FormulaWithModel(self.trigger, model) t.setMath(ast_trigger) if self.priority is not None: ast_priority = libsbml.parseL3FormulaWithModel(self.priority, model) obj.setPriority(ast_priority) if self.delay is not None: ast_delay = libsbml.parseL3FormulaWithModel(self.delay, model) obj.setDelay(ast_delay) for key, math in self.assignments.items(): ast_assign = libsbml.parseL3FormulaWithModel(str(math), model) ea = obj.createEventAssignment() ea.setVariable(key) ea.setMath(ast_assign)
def set_fields(self, obj, model): """ Set fields on given object. :param obj: event :param model: :return: """ super(Event, self).set_fields(obj) obj.setUseValuesFromTriggerTime(True) t = obj.createTrigger() t.setInitialValue(self.trigger_initialValue) # False ! not supported by Copasi -> lame fix via time t.setPersistent(self.trigger_persistent) # True ! not supported by Copasi -> careful with usage ast_trigger = libsbml.parseL3FormulaWithModel(self.trigger, model) t.setMath(ast_trigger) if self.priority is not None: ast_priority = libsbml.parseL3FormulaWithModel(self.priority, model) obj.setPriority(ast_priority) if self.delay is not None: ast_delay = libsbml.parseL3FormulaWithModel(self.delay, model) obj.setDelay(ast_delay) for key, math in self.assignments.items(): ast_assign = libsbml.parseL3FormulaWithModel(str(math), model) ea = obj.createEventAssignment() ea.setVariable(key) ea.setMath(ast_assign)
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
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
def DefineInitialAssignment(Container, Symbol, Size, MathExpression): RetInit = Container.createInitialAssignment() RetInit.setSymbol(Symbol) Init1Math = libsbml.parseL3FormulaWithModel(MathExpression,Container) Check(Init1Math,'Check Math') RetInit.setMath(Init1Math) DefineDimension(Container=RetInit, Size = Size, DimEnum=0, ID='d0') DefineIndex(Container=RetInit, DimEnum=0, ReferencedAttribute='symbol', MathExpr='d0') return RetInit
def _save_kineticlaws(model, sbml_model): for r_id, ratelaw in model.ratelaws.items(): sbml_reaction = sbml_model.getReaction(r_id) kineticLaw = sbml_reaction.createKineticLaw() #kineticLaw.setFormula(ratelaw) kineticLaw.setMath(parseL3FormulaWithModel(ratelaw, sbml_model)) #avoids conversion of Pi to pi for p_id, value in model.local_params[r_id].items(): parameter = kineticLaw.createParameter() parameter.setId(p_id) parameter.setValue(value)
def _save_kineticlaws(model, sbml_model): for r_id, ratelaw in model.ratelaws.items(): sbml_reaction = sbml_model.getReaction(r_id) kineticLaw = sbml_reaction.createKineticLaw() #kineticLaw.setFormula(ratelaw) kineticLaw.setMath(parseL3FormulaWithModel(ratelaw, sbml_model)) #avoids conversion of Pi to pi for p_id, value in model.local_params[r_id].items(): parameter = kineticLaw.createParameter() parameter.setId(p_id) parameter.setValue(value)
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
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
def DefineEvent(Container, Name, TriggerFormula, PriorityFormula, DelayFormula, Assignments): "Create Event" RetEvent = Container.createEvent() RetEvent.setName(Name) RetEvent.setUseValuesFromTriggerTime(False) RetTrigger = RetEvent.createTrigger() # Since event state trigger needs to be rechecked events are persistant RetTrigger.setPersistent(False) RetTrigger.setInitialValue(False) TriggerMath = libsbml.parseL3FormulaWithModel(TriggerFormula,Container) Check(TriggerMath,'Check Trigger Math') RetTrigger.setMath(TriggerMath) RetPriority = RetEvent.createPriority() PriorityMath = libsbml.parseL3FormulaWithModel(PriorityFormula,Container) Check(PriorityMath,'Check Priority Math') RetPriority.setMath(PriorityMath) RetDelay = RetEvent.createDelay() DelayyMath = libsbml.parseL3FormulaWithModel(DelayFormula,Container) Check(DelayyMath,'Check Delay Math') RetDelay.setMath(DelayyMath) for (AssignmentVariable, AssignmentFormula, ArrayData) in (Assignments): Assignment = RetEvent.createEventAssignment() Assignment.setVariable(AssignmentVariable) AssignmentMath = libsbml.parseL3FormulaWithModel(AssignmentFormula,Container) Check(AssignmentMath,'Assignment Math') Assignment.setMath(AssignmentMath) if ArrayData != None: DimEnum, ReferencedAttribute, MathExpr = ArrayData DefineIndex(Assignment, DimEnum, ReferencedAttribute, MathExpr) return RetEvent
def set_fields(self, obj: libsbml.Constraint, model: libsbml.Model): """ Set fields on given object. :param obj: constraint :param model: libsbml.Model instance :return: """ super(Constraint, self).set_fields(obj) if self.math is not None: ast_math = libsbml.parseL3FormulaWithModel(self.math, model) obj.setMath(ast_math) if self.message is not None: check(obj.setMessage(self.message), message="Setting message on constraint: '{}'".format(self.message))
def set_fields(self, obj: libsbml.Constraint, model: libsbml.Model): """ Set fields on given object. :param obj: constraint :param model: libsbml.Model instance :return: """ super(Constraint, self).set_fields(obj) if self.math is not None: ast_math = libsbml.parseL3FormulaWithModel(self.math, model) obj.setMath(ast_math) if self.message is not None: check(obj.setMessage(self.message), message="Setting message on constraint: '{}'".format(self.message))
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
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
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
def distrib_all() -> libsbml.SBMLDocument: """Create simple distrib model. :return: """ doc: libsbml.SBMLDocument = _distrib_doc() model: libsbml.Model = doc.createModel() # 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)) _: libsbml.Parameter = _create_parameter(pid, model=model) assignment: libsbml.InitialAssignment = model.createInitialAssignment() assignment.setSymbol(pid) ast_node = libsbml.parseL3FormulaWithModel(formula, model) if ast_node is None: raise IOError(f"{formula}, {libsbml.getLastParseL3Error()}") assignment.setMath(ast_node), "setting math" return doc
def distrib_normal(): """ Create simple distrib model. :return: """ doc = _distrib_doc() model = doc.createModel() # type: libsbml.Model # parameter p = _create_parameter("p1", model=model) # type: libsbml.Parameter # initial assignment assignment = model.createInitialAssignment() # type: libsbml.InitialAssignment assignment.setSymbol("p1") ast_node = libsbml.parseL3FormulaWithModel("1.0 mole * normal(0, 1.0)", model) assignment.setMath(ast_node) return doc
def distrib_normal() -> libsbml.SBMLDocument: """Create simple distrib model. :return: """ doc: libsbml.SBMLDocument = _distrib_doc() model: libsbml.Model = doc.createModel() # parameter _: libsbml.Parameter = _create_parameter("p1", model=model) # initial assignment assignment: libsbml.InitialAssignment = model.createInitialAssignment() assignment.setSymbol("p1") ast_node = libsbml.parseL3FormulaWithModel("1.0 mole * normal(0, 1.0)", model) assignment.setMath(ast_node) return doc
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)
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
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
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(self.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 not ast: logging.error("Formula could not be parsed in uncertainty: {}".format(self.formula)) up.setMath(ast) return uncertainty
def uncertainty() -> libsbml.SBMLDocument: """Create uncertainty with UncertParameter.""" doc: libsbml.SBMLDocument = _distrib_doc() model: libsbml.Model = doc.createModel() # parameter p: libsbml.Parameter = _create_parameter("p1", model=model) p_distrib: libsbml.DistribSBasePlugin = p.getPlugin("distrib") # -------------------------------------------- # Build generic uncertainty for parameter # -------------------------------------------- # 5.0 (mean) +- 0.3 (std) [2.0 - 8.0] uncertainty: libsbml.Uncertainty = p_distrib.createUncertainty() uncertainty.setName("Basic example: 5.0 +- 0.3 [2.0 - 8.0]") unit = libsbml.UnitKind_toString(libsbml.UNIT_KIND_MOLE) up_mean: libsbml.UncertParameter = uncertainty.createUncertParameter() up_mean.setType(libsbml.DISTRIB_UNCERTTYPE_MEAN) up_mean.setValue(5.0) up_mean.setUnits(unit) up_sd: libsbml.UncertParameter = uncertainty.createUncertParameter() up_sd.setType(libsbml.DISTRIB_UNCERTTYPE_STANDARDDEVIATION) up_sd.setValue(0.3) up_sd.setUnits(unit) up_range = libsbml.UncertSpan() up_range.setType(libsbml.DISTRIB_UNCERTTYPE_RANGE) up_range.setValueLower(2.0) up_range.setValueUpper(8.0) up_range.setUnits(unit) check(uncertainty.addUncertParameter(up_range), "add the span") check( uncertainty.setAnnotation( """ <body xmlns='http://www.w3.org/1999/xhtml'> <p>Experimental data from study</p> </body> """ ), "set annotations", ) # add an annotation with SBO terms uncertainty.setMetaId("meta_uncertainty1") cv1 = libsbml.CVTerm() cv1.setQualifierType(libsbml.BIOLOGICAL_QUALIFIER) cv1.setBiologicalQualifierType(6) # "BQB_IS_DESCRIBED_BY" cv1.addResource("https://identifiers.org/pubmed/123456") check(uncertainty.addCVTerm(cv1), "add cv term") cv2 = libsbml.CVTerm() cv2.setQualifierType(libsbml.BIOLOGICAL_QUALIFIER) cv2.setBiologicalQualifierType(10) # "BQB_HAS_PROPERTY" cv2.addResource("http://purl.obolibrary.org/obo/ECO_0006016") check(uncertainty.addCVTerm(cv2), "add cv term") # -------------------------------------------- # Set of all UncertParameters # -------------------------------------------- # create second uncertainty which contains all the individual uncertainties uncertainty = p_distrib.createUncertainty() uncertainty.setName("UncertParameter example") for k, parameter_type in enumerate( [ 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: libsbml.UncertParameter = uncertainty.createUncertParameter() up.setType(parameter_type) up.setValue(k) up.setUnits(unit) # -------------------------------------------- # Set of all UncertSpans # -------------------------------------------- uncertainty = p_distrib.createUncertainty() uncertainty.setName("UncertSpan example") for k, parameter_type in enumerate( [ libsbml.DISTRIB_UNCERTTYPE_CONFIDENCEINTERVAL, libsbml.DISTRIB_UNCERTTYPE_CREDIBLEINTERVAL, libsbml.DISTRIB_UNCERTTYPE_INTERQUARTILERANGE, libsbml.DISTRIB_UNCERTTYPE_RANGE, ] ): up_range = libsbml.UncertSpan() up_range.setType(parameter_type) up_range.setValueLower(k - 1.0) up_range.setValueUpper(k + 1.0) up_range.setUnits(unit) check(uncertainty.addUncertParameter(up_range), "add the span") # -------------------------------------------- # Use math for distribution definition # -------------------------------------------- # 5.0 dimensionless * normal(1.0 mole, 3.0 mole) uncertainty = p_distrib.createUncertainty() uncertainty.setName("math example: 5.0 dimensionless * normal(1.0 mole, 3.0 mole)") up = uncertainty.createUncertParameter() up.setType(libsbml.DISTRIB_UNCERTTYPE_DISTRIBUTION) up.setDefinitionURL("http://www.sbml.org/sbml/symbols/distrib/normal") ast = libsbml.parseL3FormulaWithModel( "5.0 dimensionless * normal(1.0 mole, 3.0 mole)", model ) if not ast: raise ValueError up.setMath(ast) # -------------------------------------------- # Use externalParameter # -------------------------------------------- # https://sites.google.com/site/probonto/ uncertainty = p_distrib.createUncertainty() uncertainty.setName("ExternalParameter example") up = uncertainty.createUncertParameter() up.setType(libsbml.DISTRIB_UNCERTTYPE_EXTERNALPARAMETER) up.setName("skewness") up.setValue(0.25) up.setUnits(unit) up.setDefinitionURL("http://purl.obolibrary.org/obo/STATO_0000068") # -------------------------------------------- # Use external distribution definition # -------------------------------------------- uncertainty = p_distrib.createUncertainty() uncertainty.setName("External distribution example") up = uncertainty.createUncertParameter() up.setType(libsbml.DISTRIB_UNCERTTYPE_DISTRIBUTION) up.setName("Geometric 1") up.setDefinitionURL("http://www.probonto.org/ontology#PROB_k0000782") up.setUnits(unit) # success probability of Geometric-1 up_mean_geo1 = up.createUncertParameter() up_mean_geo1.setType(libsbml.DISTRIB_UNCERTTYPE_EXTERNALPARAMETER) up_mean_geo1.setName("success probability of Geometric 1") up_mean_geo1.setValue(0.4) up_mean_geo1.setDefinitionURL("http://www.probonto.org/ontology#PROB_k0000789") return doc
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")
def _create_odes(self): """ Creates information of ODE system from SBMLDocument. :return: """ model = self.doc.getModel() # type: libsbml.Model # -------------- # parameters # -------------- # 1. constant parameters (real parameters of the system) for parameter in model.getListOfParameters(): # type: libsbml.Parameter pid = parameter.getId() if parameter.getConstant(): value = parameter.getValue() else: value = '' self.p[pid] = value # -------------- # compartments # -------------- # constant compartments (parameters of the system) for compartment in model.getListOfCompartments(): # type: libsbml.Compartment cid = compartment.getId() if compartment.getConstant(): value = compartment.getSize() else: value = '' self.p[cid] = value # -------------- # species # -------------- for species in model.getListOfSpecies(): # type: libsbml.Species sid = species.getId() self.dx_ast[sid] = '' # initial condition value = None compartment = model.getCompartment(species.getCompartment()) # type: libsbml.Compartment if species.isSetInitialAmount(): value = species.getInitialAmount() if not species.getHasOnlySubstanceUnits(): # FIXME: handle the initial assignments/assignment rules for compartment volumes value = value / compartment.getSize() elif species.isSetInitialConcentration(): value = species.getInitialConcentration() if species.getHasOnlySubstanceUnits(): # FIXME: handle the initial assignments/assignment rules for compartment volumes value = value * compartment.getSize() self.x0[sid] = value # -------------------- # initial assignments # -------------------- # types of objects whose identifiers are permitted as the values of InitialAssignment symbol attributes # are Compartment, Species, SpeciesReference and (global) Parameter objects in the model. for assignment in model.getListOfInitialAssignments(): # type: libsbml.InitialAssignment variable = assignment.getSymbol() astnode = assignment.getMath() self.x0[variable] = astnode # -------------- # rules # -------------- for rule in model.getListOfRules(): # type: libsbml.Rule type_code = rule.getTypeCode() # -------------- # rate rules # -------------- if type_code == libsbml.SBML_RATE_RULE: # directly converted to odes (create additional state variables) rate_rule = rule # type: libsbml.AssignmentRule variable = rate_rule.getVariable() # store rule astnode = rate_rule.getMath() self.dx_ast[variable] = astnode # dxids[variable] = evaluableMathML(astnode) # could be species, parameter, or compartment if variable in self.p: del self.p[variable] parameter = model.getParameter(variable) if parameter: self.x0[variable] = parameter.getValue() compartment = model.getCompartment(variable) if compartment: self.x0[variable] = compartment.getSize() # -------------- # assignment rules # -------------- elif type_code == libsbml.SBML_ASSIGNMENT_RULE: as_rule = rule # type: libsbml.RateRule variable = as_rule.getVariable() astnode = as_rule.getMath() self.y_ast[variable] = astnode # yids[variable] = evaluableMathML(astnode) if variable in self.dx_ast: del self.dx[variable] if variable in self.p: del self.p[variable] # Process the kinetic laws of reactions for reaction in model.getListOfReactions(): # type: libsbml.Reaction rid = reaction.getId() if reaction.isSetKineticLaw(): klaw = reaction.getKineticLaw() # type: libsbml.KineticLaw astnode = klaw.getMath() self.y_ast[rid] = astnode # create astnode for dx_ast for reactant in reaction.getListOfReactants(): # type: libsbml.SpeciesReference self._add_reaction_formula(model, rid=rid, species_ref=reactant, sign="-") for product in reaction.getListOfProducts(): # type: libsbml.SpeciesReference self._add_reaction_formula(model, rid=rid, species_ref=product, sign="+") # create astnodes for the formula strings for key, astnode in self.dx_ast.items(): if not isinstance(astnode, libsbml.ASTNode): astnode = libsbml.parseL3FormulaWithModel(astnode, model) self.dx_ast[key] = astnode # check which math depends on other math (build tree of dependencies) self.yids_ordered = self._ordered_yids()
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")
def uncertainty(): """ Create uncertainty with UncertParameter. :return: """ doc = _distrib_doc() model = doc.createModel() # type: libsbml.Model # parameter p = _create_parameter("p1", model=model) # type: libsbml.Parameter p_distrib = p.getPlugin("distrib") # type: libsbml.DistribSBasePlugin # -------------------------------------------- # Build generic uncertainty for parameter # -------------------------------------------- # 5.0 (mean) +- 0.3 (std) [2.0 - 8.0] uncertainty = p_distrib.createUncertainty() # type: libsbml.Uncertainty uncertainty.setName("Basic example: 5.0 +- 0.3 [2.0 - 8.0]") unit = libsbml.UnitKind_toString(libsbml.UNIT_KIND_MOLE) up_mean = uncertainty.createUncertParameter() # type: libsbml.UncertParameter up_mean.setType(libsbml.DISTRIB_UNCERTTYPE_MEAN) up_mean.setValue(5.0) up_mean.setUnits(unit) up_sd = uncertainty.createUncertParameter() # type: libsbml.UncertParameter up_sd.setType(libsbml.DISTRIB_UNCERTTYPE_STANDARDDEVIATION) up_sd.setValue(0.3) up_sd.setUnits(unit) # up_range = uncertainty.createUncertParameter() # type: libsbml.UncertParameter up_range = libsbml.UncertSpan() up_range.setType(libsbml.DISTRIB_UNCERTTYPE_RANGE) up_range.setValueLower(2.0) up_range.setValueUpper(8.0) up_range.setUnits(unit) check(uncertainty.addUncertParameter(up_range), "add the span") check(uncertainty.setAnnotation(""" <body xmlns='http://www.w3.org/1999/xhtml'> <p>Experimental data from study</p> </body> """), "set annotations") # add an annotation with SBO terms uncertainty.setMetaId("meta_uncertainty1") cv1 = libsbml.CVTerm() cv1.setQualifierType(libsbml.BIOLOGICAL_QUALIFIER) cv1.setBiologicalQualifierType(6) # "BQB_IS_DESCRIBED_BY" cv1.addResource("https://identifiers.org/pubmed/123456") check(uncertainty.addCVTerm(cv1), "add cv term") cv2 = libsbml.CVTerm() cv2.setQualifierType(libsbml.BIOLOGICAL_QUALIFIER) cv2.setBiologicalQualifierType(10) # "BQB_HAS_PROPERTY" cv2.addResource("http://purl.obolibrary.org/obo/ECO_0006016") check(uncertainty.addCVTerm(cv2), "add cv term") # -------------------------------------------- # Set of all UncertParameters # -------------------------------------------- # create second uncertainty which contains all the individual uncertainties uncertainty = p_distrib.createUncertainty() # type: libsbml.Uncertainty uncertainty.setName("UncertParameter example") for k, parameter_type in enumerate([ 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(parameter_type) up.setValue(k) up.setUnits(unit) # -------------------------------------------- # Set of all UncertSpans # -------------------------------------------- uncertainty = p_distrib.createUncertainty() # type: libsbml.Uncertainty uncertainty.setName("UncertSpan example") for k, parameter_type in enumerate([ libsbml.DISTRIB_UNCERTTYPE_CONFIDENCEINTERVAL, libsbml.DISTRIB_UNCERTTYPE_CREDIBLEINTERVAL, libsbml.DISTRIB_UNCERTTYPE_INTERQUARTILERANGE, libsbml.DISTRIB_UNCERTTYPE_RANGE]): up_range = libsbml.UncertSpan() up_range.setType(parameter_type) up_range.setValueLower(k-1.0) up_range.setValueUpper(k+1.0) up_range.setUnits(unit) check(uncertainty.addUncertParameter(up_range), "add the span") # -------------------------------------------- # Use math for distribution definition # -------------------------------------------- # 5.0 dimensionless * normal(1.0 mole, 3.0 mole) uncertainty = p_distrib.createUncertainty() # type: libsbml.Uncertainty uncertainty.setName("math example: 5.0 dimensionless * normal(1.0 mole, 3.0 mole)") up = uncertainty.createUncertParameter() # type: libsbml.UncertParameter up.setType(libsbml.DISTRIB_UNCERTTYPE_DISTRIBUTION) up.setDefinitionURL("http://www.sbml.org/sbml/symbols/distrib/normal") ast = libsbml.parseL3FormulaWithModel("5.0 dimensionless * normal(1.0 mole, 3.0 mole)", model) if not ast: raise ValueError up.setMath(ast) # -------------------------------------------- # Use externalParameter # -------------------------------------------- # https://sites.google.com/site/probonto/ uncertainty = p_distrib.createUncertainty() # type: libsbml.Uncertainty uncertainty.setName("ExternalParameter example") up = uncertainty.createUncertParameter() # type: libsbml.UncertParameter up.setType(libsbml.DISTRIB_UNCERTTYPE_EXTERNALPARAMETER) up.setName("skewness") up.setValue(0.25) up.setUnits(unit) up.setDefinitionURL("http://purl.obolibrary.org/obo/STATO_0000068") # -------------------------------------------- # Use external distribution definition # -------------------------------------------- uncertainty = p_distrib.createUncertainty() # type: libsbml.Uncertainty uncertainty.setName("External distribution example") up = uncertainty.createUncertParameter() # type: libsbml.UncertParameter up.setType(libsbml.DISTRIB_UNCERTTYPE_DISTRIBUTION) up.setName("Geometric 1") up.setDefinitionURL("http://www.probonto.org/ontology#PROB_k0000782") up.setUnits(unit) # success probability of Geometric-1 up_mean_geo1 = up.createUncertParameter() # type: libsbml.UncertParameter up_mean_geo1.setType(libsbml.DISTRIB_UNCERTTYPE_EXTERNALPARAMETER) up_mean_geo1.setName("success probability of Geometric 1") up_mean_geo1.setValue(0.4) up_mean_geo1.setDefinitionURL("http://www.probonto.org/ontology#PROB_k0000789") return doc