示例#1
0
    def events(self, model: libsbml.Model) -> List[Dict[str, Any]]:
        """Information dictionaries for Events.

        :return: list of info dictionaries for Events
        """

        events = []
        event: libsbml.Event
        for event in model.getListOfEvents():
            d = self.sbase_dict(event)

            d["useValuesFromTriggerTime"] = (
                event.getUseValuesFromTriggerTime()
                if event.isSetUseValuesFromTriggerTime() else None)

            trigger: libsbml.Trigger = (event.getTrigger()
                                        if event.isSetTrigger() else None)
            if trigger:
                d["trigger"] = {
                    "math":
                    astnode_to_latex(trigger.getMath())
                    if trigger.isSetMath() else None,
                    "initialValue":
                    trigger.initial_value,
                    "persistent":
                    trigger.persistent,
                }
            else:
                d["trigger"] = None

            priority: libsbml.Priority = (event.getPriority()
                                          if event.isSetPriority() else None)
            if priority:
                d["priority"] = (astnode_to_latex(priority.getMath())
                                 if priority.isSetMath() else None)
            delay: libsbml.Delay = event.getDelay() if event.isSetDelay(
            ) else None
            if delay:
                d["delay"] = (astnode_to_latex(delay.getMath())
                              if delay.isSetMath() else None)

            assignments = []
            eva: libsbml.EventAssignment
            for eva in event.getListOfEventAssignments():
                assignments.append({
                    "variable":
                    eva.getVariable() if eva.isSetVariable() else None,
                    "math":
                    astnode_to_latex(eva.getMath())
                    if eva.isSetMath() else None,
                })
            d["listOfEventAssignments"] = assignments

            events.append(d)

        return events
示例#2
0
    def rules(self, model: libsbml.Model) -> Dict:
        """Information for Rules.

        :return: list of info dictionaries for Rules
        """

        rules: Dict[str, List] = {
            "assignmentRules": [],
            "rateRules": [],
            "algebraicRules": [],
        }
        rule: libsbml.Rule
        for rule in model.getListOfRules():
            d = self.sbase_dict(rule)
            d["variable"] = self._rule_variable_to_string(rule)
            d["math"] = astnode_to_latex(
                rule.getMath()) if rule.isSetMath() else None
            d["derivedUnits"] = udef_to_string(rule.getDerivedUnitDefinition())

            type = d["sbmlType"]
            key = f"{type[0].lower()}{type[1:]}s"

            rules[key].append(d)

        return rules
示例#3
0
    def function_definitions(self, model: libsbml.Model) -> List:
        """Information dictionaries for FunctionDefinitions.

        :return: list of info dictionaries for FunctionDefinitions
        """
        func_defs = []
        fd: libsbml.FunctionDefinition
        for fd in model.getListOfFunctionDefinitions():
            d = self.sbase_dict(fd)
            d["math"] = astnode_to_latex(
                fd.getMath()) if fd.isSetMath() else None

            func_defs.append(d)

        return func_defs
示例#4
0
    def constraints(self, model: libsbml.Model) -> List[Dict[str, Any]]:
        """Information for Constraints.

        :return: list of info dictionaries for Constraints
        """

        constraints = []
        constraint: libsbml.Constraint
        for constraint in model.getListOfConstraints():
            d = self.sbase_dict(constraint)
            d["math"] = (astnode_to_latex(constraint.getMath())
                         if constraint.isSetMath() else None)
            d["message"] = (constraint.getMessage()
                            if constraint.isSetMessage() else None)
            constraints.append(d)

        return constraints
示例#5
0
    def initial_assignments(self, model: libsbml.Model) -> List:
        """Information for InitialAssignments.

        :return: list of info dictionaries for InitialAssignments
        """

        assignments = []
        assignment: libsbml.InitialAssignment
        for assignment in model.getListOfInitialAssignments():
            d = self.sbase_dict(assignment)
            d["symbol"] = assignment.getSymbol() if assignment.isSetSymbol(
            ) else None
            d["math"] = astnode_to_latex(assignment.getMath())
            d["derivedUnits"] = udef_to_string(
                assignment.getDerivedUnitDefinition())
            assignments.append(d)

        return assignments
示例#6
0
def math(item: libsbml.SBase, math_type: str = "cmathml") -> str:
    """Create MathML content for the item.

    :param item: SBML object for which MathML content is to be generated
    :param math_type: specifies which math rendering mode to use
    :return: formatted MathML content for the item
    """

    if item:
        if not isinstance(item, libsbml.ASTNode):
            astnode = item.getMath()
        else:
            astnode = item
        if math_type == "cmathml":
            return astnode_to_mathml(astnode)
        elif math_type == "pmathml":
            cmathml = astnode_to_mathml(astnode)
            return mathml.cmathml_to_pmathml(cmathml)
        elif math_type == "latex":
            latex_str = mathml.astnode_to_latex(astnode)
            return f"$${latex_str}$$"
    return empty_html()
示例#7
0
    def reactions(self, model: libsbml.Model) -> List[Dict[str, Any]]:
        """Information dictionaries for ListOfReactions.

        :return: list of info dictionaries for Reactions

        -- take a look at local parameter once
        """

        reactions = []
        r: libsbml.Reaction
        for r in model.getListOfReactions():
            d = self.sbase_dict(r)
            d["reversible"] = r.getReversible() if r.isSetReversible(
            ) else None
            d["compartment"] = r.getCompartment() if r.isSetCompartment(
            ) else None
            d["listOfReactants"] = [
                self._species_reference(reac)
                for reac in r.getListOfReactants()
            ]
            d["listOfProducts"] = [
                self._species_reference(prod)
                for prod in r.getListOfProducts()
            ]
            d["listOfModifiers"] = [
                mod.getSpecies() for mod in r.getListOfModifiers()
            ]
            d["fast"] = r.getFast() if r.isSetFast() else None
            d["equation"] = self._equation_from_reaction(r)

            klaw: libsbml.KineticLaw = (r.getKineticLaw()
                                        if r.isSetKineticLaw() else None)
            if klaw:
                d_law: Dict[str, Any] = {}
                d_law["math"] = (astnode_to_latex(klaw.getMath())
                                 if klaw.isSetMath() else None)
                d_law["derivedUnits"] = udef_to_string(
                    klaw.getDerivedUnitDefinition())

                d_law["localParameters"] = []
                for i in range(len(klaw.getListOfLocalParameters())):
                    lp: libsbml.LocalParameter = klaw.getLocalParameter(i)
                    lpar_info = {
                        "id":
                        lp.getId() if lp.isSetId() else None,
                        "value":
                        lp.getValue() if lp.isSetValue() else None,
                        "units_sid":
                        lp.getUnits() if lp.isSetUnits() else None,
                        "derivedUnits":
                        udef_to_string(lp.getDerivedUnitDefinition()),
                    }
                    lpar_info["units"] = udef_to_string(
                        lpar_info["units_sid"], model)
                    d_law["localParameters"].append(lpar_info)
                d["kineticLaw"] = d_law
            else:
                d["kineticLaw"] = None

            # fbc
            rfbc = r.getPlugin("fbc")
            d["fbc"] = ({
                "bounds": self._bounds_dict_from_reaction(r, model),
                "gpa": self._gene_product_association_from_reaction(r),
            } if rfbc else None)

            key = r.pk.split(":")[-1]
            if key in self.maps["assignments"]:
                d["assignment"] = self.maps["assignments"][key]
            if key in self.maps["ports"]:
                d["port"] = self.maps["ports"][key]

            reactions.append(d)

        return reactions
示例#8
0
    def sbase_dict(cls, sbase: libsbml.SBase) -> Dict[str, Any]:
        """Info dictionary for SBase.

        :param sbase: SBase instance for which info dictionary is to be created
        :return info dictionary for item
        """
        pk = cls._get_pk(sbase)
        d = {
            "pk": pk,
            "sbmlType": cls._sbml_type(sbase),
            "id": sbase.getId() if sbase.isSetId() else None,
            "metaId": sbase.getMetaId() if sbase.isSetMetaId() else None,
            "name": sbase.getName() if sbase.isSetName() else None,
            "sbo": sbase.getSBOTermID() if sbase.isSetSBOTerm() else None,
            "cvterms": cls.cvterms(sbase),
            "history": cls.model_history(sbase),
            "notes": sbase.getNotesString() if sbase.isSetNotes() else None,
        }

        # TODO: add the ports information

        if sbase.getTypeCode() in {libsbml.SBML_DOCUMENT, libsbml.SBML_MODEL}:
            d["xml"] = None
        else:
            d["xml"] = sbase.toSBML()

        # comp
        item_comp = sbase.getPlugin("comp")
        if item_comp and type(item_comp) == libsbml.CompSBasePlugin:
            # ReplacedBy
            if item_comp.isSetReplacedBy():
                replaced_by = item_comp.getReplacedBy()
                submodel_ref = replaced_by.getSubmodelRef()
                d["replacedBy"] = {
                    "submodelRef": submodel_ref,
                    "replacedBySbaseref": cls._sbaseref(replaced_by),
                }
            else:
                d["replacedBy"] = None

            # ListOfReplacedElements
            if item_comp.getNumReplacedElements() > 0:
                replaced_elements = []
                for rep_el in item_comp.getListOfReplacedElements():
                    submodel_ref = rep_el.getSubmodelRef()
                    replaced_elements.append({
                        "submodelRef":
                        submodel_ref,
                        "replacedElementSbaseref":
                        cls._sbaseref(rep_el),
                    })

                d["replacedElements"] = replaced_elements
            else:
                d["replacedElements"] = None

        # distrib
        sbml_distrib: libsbml.DistribSBasePlugin = sbase.getPlugin("distrib")
        if sbml_distrib and isinstance(sbml_distrib,
                                       libsbml.DistribSBasePlugin):
            d["uncertainties"] = []
            for uncertainty in sbml_distrib.getListOfUncertainties():
                u_dict = SBMLDocumentInfo.sbase_dict(uncertainty)

                u_dict["uncertaintyParameters"] = []
                upar: libsbml.UncertParameter
                for upar in uncertainty.getListOfUncertParameters():
                    param_dict = {
                        "var":
                        upar.getVar() if upar.isSetVar() else None,
                        "value":
                        upar.getValue() if upar.isSetValue() else None,
                        "units":
                        upar.getUnits() if upar.isSetUnits() else None,
                        "type":
                        upar.getTypeAsString() if upar.isSetType() else None,
                        "definitionURL":
                        upar.getDefinitionURL()
                        if upar.isSetDefinitionURL() else None,
                        "math":
                        astnode_to_latex(upar.getMath())
                        if upar.isSetMath() else None,
                    }

                    u_dict["uncertaintyParameters"].append(param_dict)

                d["uncertainties"].append(u_dict)

        return d
示例#9
0
def test_astnode_to_latex(formula: str) -> None:
    astnode = mathml.formula_to_astnode(formula)
    latex = mathml.astnode_to_latex(astnode)
    assert latex
    assert isinstance(latex, str)