Skip to content

Commit

Permalink
work on odefactory
Browse files Browse the repository at this point in the history
  • Loading branch information
matthiaskoenig committed Aug 13, 2024
1 parent 9221472 commit 593a463
Show file tree
Hide file tree
Showing 8 changed files with 66 additions and 29 deletions.
62 changes: 46 additions & 16 deletions src/sbmlutils/converters/odefac.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,20 +54,35 @@ def __init__(self, doc: libsbml.SBMLDocument):
"""
self.doc: libsbml.SBMLDocument = doc

self.names: Dict[str, str] = {}
self.units: Dict[str, Optional[str]] = {} # model units

# --- fixed model entities ---
# p: constants (parameters, compartments, species)
# x: initial values (state variables)

# assignments
# p=: assignment rules (species, parameters, compartments)
# x0=: initial values

# kinetics dx/dt
# x: state variables (species, parameters, compartments)

self.x0: Dict = {} # initial amounts/concentrations
self.a_ast: Dict = {} # initial assignments
self.dx: Dict = {}
self.dx_ast: Dict = {} # state variables x (odes)
self.x_units: Dict = {} # state variables x units
self.x_compartments: Dict = {} # compartments of species
self.x_: Set = set() # species state variables as concentrations

self.p: Dict = {} # parameters p (constants)
self.p_units: Dict = {} # parameter units

self.y_ast: Dict = {} # assigned variables
self.yids_ordered: List[str] # yids in order of math dependencies
self.y_units: Dict = {} # y units
self.names: Dict[str, str] = {}


# create name dictionary
sbase: libsbml.SBase
Expand Down Expand Up @@ -417,56 +432,71 @@ def create_ordered_variables(
yids = create_ordered_variables(g)
return yids

def to_python(self, py_file: Path) -> None:
def to_python(self, py_file: Optional[Path]=None) -> str:
"""Write ODEs to python."""
content = self._render_template(
template_file="odefac_template.pytemp",
index_offset=0,
replace_symbols=True,
)
with open(py_file, "w") as f:
f.write(content)
if py_file:
with open(py_file, "w") as f:
f.write(content)

def to_tex(self, tex_file: Path) -> None:
return content

def to_tex(self, tex_file: Optional[Path]=None) -> str:
"""Write ODEs to tex/latex."""
content = self._render_template(
template_file="odefac_template.tex",
index_offset=0,
replace_symbols=False,
)
with open(tex_file, "w") as f:
f.write(content)
if tex_file:
with open(tex_file, "w") as f:
f.write(content)

return content

def to_R(self, r_file: Path) -> None:
def to_R(self, r_file: Optional[Path]=None) -> str:
"""Write ODEs to R."""
content = self._render_template(
template_file="odefac_template.R",
index_offset=1,
replace_symbols=True,
)
with open(r_file, "w") as f:
f.write(content)
if r_file:
with open(r_file, "w") as f:
f.write(content)

def to_markdown(self, md_file: Path) -> None:
return content

def to_markdown(self, md_file: Optional[Path]=None) -> str:
"""Write ODEs to markdown."""
content = self._render_template(
template_file="odefac_template.md",
index_offset=0,
replace_symbols=False,
)
with open(md_file, "w") as f:
f.write(content)
if md_file:
with open(md_file, "w") as f:
f.write(content)

return content

def to_custom_template(self, output_file: Path, template_file: Path) -> None:
def to_custom_template(self, template_file: Path, output_file: Optional[Path]=None) -> str:
"""Write ODEs to custom template."""
content = self._render_template(
template_file=template_file.name,
index_offset=0,
replace_symbols=False,
template_dir=template_file.parent,
)
with open(output_file, "w") as f:
f.write(content)
if output_file:
with open(output_file, "w") as f:
f.write(content)

return content

def _render_template(
self,
Expand Down
11 changes: 9 additions & 2 deletions src/sbmlutils/examples/assignment.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
"""AssignmentRule and InitialAssignment example."""
from sbmlutils.console import console
from sbmlutils.converters import odefac
from sbmlutils.examples import templates
from sbmlutils.factory import *

Expand Down Expand Up @@ -90,7 +92,7 @@ class U(Units):
"Cve",
"A/Vblood",
U.mg_per_l,
name="rule to calulate concentration",
name="rule to calculate concentration",
notes="""
Assignment rule to calculate the concentration `Cve` in [mg/l] from the
species `A` and the volume `Vblood`.
Expand All @@ -106,4 +108,9 @@ class U(Units):
if __name__ == "__main__":
from sbmlutils.resources import EXAMPLES_DIR

create_model(model=model, filepath=EXAMPLES_DIR / f"{model.sid}.xml")
results: FactoryResult = create_model(model=model, filepath=EXAMPLES_DIR / f"{model.sid}.xml")
factory = odefac.SBML2ODE.from_file(sbml_file=results.sbml_path)
md_str = factory.to_markdown()
from rich.markdown import Markdown
console.print(Markdown(md_str))

2 changes: 1 addition & 1 deletion src/sbmlutils/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,7 @@ def __init__(
def __str__(self) -> str:
"""Get string."""
field_str = ", ".join(
[str(getattr(self, f)) for f in self.fields if getattr(self, f)]
[str(getattr(self, f)) for f in self.fields if getattr(self, f) if f not in {"notes", "annotations"}]
)
return f"{self.__class__.__name__}({field_str})"

Expand Down
8 changes: 4 additions & 4 deletions src/sbmlutils/resources/converters/odefac_template.R
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# -----------------------------------------------------------
# Autogenerated ODE definition from SBML file with sbmlutils.
# ---------------------------------------------------------------------------------------------------------
# Autogenerated ODE definition from SBML file with sbmlutils (https://github.com/matthiaskoenig/sbmlutils).
#
# model: {{ model.getId() }}
# -----------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------

# -------------------
# ids
Expand Down Expand Up @@ -95,4 +95,4 @@ f_z <- function(times, X, p){
}
colnames(Z) <- c ("time", xids, yids)
Z
}
}
2 changes: 1 addition & 1 deletion src/sbmlutils/resources/converters/odefac_template.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# model: {{ model.getId() }}
Autogenerated ODE System from SBML with [sbmlutils](https://github.com/matthiaskoenig/sbmlutils.git).
Autogenerated ODE System from SBML with [sbmlutils](https://github.com/matthiaskoenig/sbmlutils).
```
time: [{{units["time"]}}]
substance: [{{units["substance"]}}]
Expand Down
2 changes: 1 addition & 1 deletion src/sbmlutils/resources/converters/odefac_template.pytemp
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""
Autogenerated ODE definition SBML file with sbmlutils (https://github.com/matthiaskoenig/sbmlutils.git).
Autogenerated ODE definition SBML file with sbmlutils (https://github.com/matthiaskoenig/sbmlutils).

model: {{ model.getId() }}

Expand Down
2 changes: 1 addition & 1 deletion src/sbmlutils/resources/converters/odefac_template.tex
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
% model: {{ model.getId() }}
% Autogenerated ODE System from SBML with sbmlutils (https://github.com/matthiaskoenig/sbmlutils.git).
% Autogenerated ODE System from SBML with sbmlutils (https://github.com/matthiaskoenig/sbmlutils).
%
% add the following packages:
% \usepackage{amsmath}
Expand Down
6 changes: 3 additions & 3 deletions src/sbmlutils/resources/examples/assignment.xml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<sbml xmlns="http://www.sbml.org/sbml/level3/version1/core" level="3" version="1">
<sbml xmlns="http://www.sbml.org/sbml/level3/version1/core" xmlns:comp="http://www.sbml.org/sbml/level3/version1/comp/version1" level="3" version="1" comp:required="true">
<notes>
<body xmlns="http://www.w3.org/1999/xhtml">
<p>Created with <a href="https://github.com/matthiaskoenig/sbmlutils">https://github.com/matthiaskoenig/sbmlutils</a>.
Expand All @@ -17,7 +17,7 @@ AssignmentRules are evaluated at every time point.</p>
<p>The content of this model has been carefully created in a manual research effort.
This file has been created by <a href="https://livermetabolism.com">Matthias König</a>
using <a href="https://github.com/matthiaskoenig/sbmlutils">sbmlutils</a>.
For questions contact <a href="mailto:koenigmx@hu-berlin.de">koenigmx@hu-berlin.de</a>. Copyright © 2022 Matthias König.</p>
For questions contact <a href="mailto:koenigmx@hu-berlin.de">koenigmx@hu-berlin.de</a>. Copyright © 2024 Matthias König.</p>
<a rel="license" href="http://creativecommons.org/licenses/by/4.0/">
<img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by/4.0/88x31.png"/>
</a>
Expand Down Expand Up @@ -123,7 +123,7 @@ An InitialAssignment is used to set the parameter.</p>
<parameter id="BW" name="body weight" value="70" units="kg" constant="true"/>
<parameter id="FVblood" name="fractional volume of the blood" value="0.05" units="l_per_kg" constant="true"/>
<parameter id="Vblood" name="blood volume" value="NaN" units="litre" constant="true"/>
<parameter id="Cve" name="rule to calulate concentration" value="NaN" units="mg_per_l" constant="false"/>
<parameter id="Cve" name="rule to calculate concentration" value="NaN" units="mg_per_l" constant="false"/>
</listOfParameters>
<listOfInitialAssignments>
<initialAssignment symbol="D">
Expand Down

0 comments on commit 593a463

Please sign in to comment.