|
1 | 1 | """Private utility functions for SBML handling.""" |
2 | 2 |
|
3 | 3 | import libsbml |
| 4 | +import sympy as sp |
| 5 | +from sbmlmath.mathml_printer import SBMLMathMLPrinter |
4 | 6 |
|
5 | 7 | retval_to_str = { |
6 | 8 | getattr(libsbml, attr): attr |
@@ -49,3 +51,32 @@ def add_sbml_parameter( |
49 | 51 | check(param.setConstant(constant)) |
50 | 52 |
|
51 | 53 | return param |
| 54 | + |
| 55 | + |
| 56 | +def set_initial_assignment( |
| 57 | + model: libsbml.Model, |
| 58 | + symbol_id: str, |
| 59 | + expr: sp.Expr, |
| 60 | + literals_dimensionless: bool = True, |
| 61 | +) -> libsbml.InitialAssignment: |
| 62 | + """Set the initial assignment for the given symbol. |
| 63 | +
|
| 64 | + Overwrites any existing initial assignment for that symbol. |
| 65 | +
|
| 66 | + :param literals_dimensionless: |
| 67 | + Whether to annotate numeric literals as dimensionless. |
| 68 | + (`sbmlmath` can't read back, e.g., ``10^x`` with a dimensionless |
| 69 | + base.) |
| 70 | + """ |
| 71 | + if (ia := model.getInitialAssignmentBySymbol(symbol_id)) is None: |
| 72 | + ia = model.createInitialAssignment() |
| 73 | + check(ia.setSymbol(symbol_id)) |
| 74 | + mathml = SBMLMathMLPrinter( |
| 75 | + sbml_level=model.getLevel(), |
| 76 | + sbml_version=model.getVersion(), |
| 77 | + literals_dimensionless=literals_dimensionless, |
| 78 | + ).doprint(expr) |
| 79 | + if (ast := libsbml.readMathMLFromString(mathml)) is None: |
| 80 | + raise ValueError(f"Failed to convert `{expr}' to MathML.") |
| 81 | + check(ia.setMath(ast)) |
| 82 | + return ia |
0 commit comments