Skip to content

Commit c6916d8

Browse files
authored
Import libsbml as libsbml (#2680)
Previously this was `sbml`, which was confusing because the global `sbml` was libsbml, and `SBMLImporter.sbml` was `libsbml.Model`. Now it's also consistent across modules.
1 parent 48d21bd commit c6916d8

File tree

1 file changed

+48
-50
lines changed

1 file changed

+48
-50
lines changed

python/sdist/amici/sbml_import.py

Lines changed: 48 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
from collections.abc import Callable
2121
from collections.abc import Iterable, Sequence
2222

23-
import libsbml as sbml
23+
import libsbml
2424
import numpy as np
2525
import sympy as sp
2626
from sympy.logic.boolalg import BooleanFalse, BooleanTrue
@@ -133,7 +133,7 @@ class SbmlImporter:
133133

134134
def __init__(
135135
self,
136-
sbml_source: str | Path | sbml.Model,
136+
sbml_source: str | Path | libsbml.Model,
137137
show_sbml_warnings: bool = False,
138138
from_file: bool = True,
139139
discard_annotations: bool = False,
@@ -156,10 +156,10 @@ def __init__(
156156
:param discard_annotations:
157157
discard information contained in AMICI SBML annotations (debug).
158158
"""
159-
if isinstance(sbml_source, sbml.Model):
160-
self.sbml_doc: sbml.Document = sbml_source.getSBMLDocument()
159+
if isinstance(sbml_source, libsbml.Model):
160+
self.sbml_doc: libsbml.Document = sbml_source.getSBMLDocument()
161161
else:
162-
self.sbml_reader: sbml.SBMLReader = sbml.SBMLReader()
162+
self.sbml_reader: libsbml.SBMLReader = libsbml.SBMLReader()
163163
if from_file:
164164
sbml_doc = self.sbml_reader.readSBMLFromFile(str(sbml_source))
165165
else:
@@ -171,7 +171,7 @@ def __init__(
171171
# process document
172172
self._process_document()
173173

174-
self.sbml: sbml.Model = self.sbml_doc.getModel()
174+
self.sbml: libsbml.Model = self.sbml_doc.getModel()
175175

176176
# Long and short names for model components
177177
self.symbols: dict[SymbolId, dict[sp.Symbol, dict[str, Any]]] = {}
@@ -188,9 +188,9 @@ def __init__(
188188

189189
# https://sbml.org/software/libsbml/5.18.0/docs/formatted/python-api/classlibsbml_1_1_l3_parser_settings.html#ab30d7ed52ca24cbb842d0a7fed7f4bfd
190190
# all defaults except disable unit parsing
191-
self.sbml_parser_settings = sbml.L3ParserSettings()
191+
self.sbml_parser_settings = libsbml.L3ParserSettings()
192192
self.sbml_parser_settings.setModel(self.sbml)
193-
self.sbml_parser_settings.setParseUnits(sbml.L3P_NO_UNITS)
193+
self.sbml_parser_settings.setParseUnits(libsbml.L3P_NO_UNITS)
194194

195195
self._discard_annotations: bool = discard_annotations
196196

@@ -212,7 +212,7 @@ def _process_document(self) -> None:
212212
for i_plugin in range(self.sbml_doc.getNumPlugins())
213213
):
214214
# see libsbml CompFlatteningConverter for options
215-
conversion_properties = sbml.ConversionProperties()
215+
conversion_properties = libsbml.ConversionProperties()
216216
conversion_properties.addOption("flatten comp", True)
217217
conversion_properties.addOption("leave_ports", False)
218218
conversion_properties.addOption("performValidation", False)
@@ -221,7 +221,7 @@ def _process_document(self) -> None:
221221
log_execution_time("flattening hierarchical SBML", logger)(
222222
self.sbml_doc.convert
223223
)(conversion_properties)
224-
!= sbml.LIBSBML_OPERATION_SUCCESS
224+
!= libsbml.LIBSBML_OPERATION_SUCCESS
225225
):
226226
raise SBMLException(
227227
"Required SBML comp extension is currently not supported "
@@ -236,15 +236,13 @@ def _process_document(self) -> None:
236236
# apply several model simplifications that make our life substantially
237237
# easier
238238
if self.sbml_doc.getModel().getNumFunctionDefinitions():
239-
convert_config = (
240-
sbml.SBMLFunctionDefinitionConverter().getDefaultProperties()
241-
)
239+
convert_config = libsbml.SBMLFunctionDefinitionConverter().getDefaultProperties()
242240
log_execution_time("converting SBML functions", logger)(
243241
self.sbml_doc.convert
244242
)(convert_config)
245243

246244
convert_config = (
247-
sbml.SBMLLocalParameterConverter().getDefaultProperties()
245+
libsbml.SBMLLocalParameterConverter().getDefaultProperties()
248246
)
249247
log_execution_time("converting SBML local parameters", logger)(
250248
self.sbml_doc.convert
@@ -595,9 +593,9 @@ def _build_ode_model(
595593

596594
self._reset_symbols()
597595
self.sbml_parser_settings.setParseLog(
598-
sbml.L3P_PARSE_LOG_AS_LOG10
596+
libsbml.L3P_PARSE_LOG_AS_LOG10
599597
if log_as_log10
600-
else sbml.L3P_PARSE_LOG_AS_LN
598+
else libsbml.L3P_PARSE_LOG_AS_LN
601599
)
602600
self._process_sbml(
603601
constant_parameters=constant_parameters,
@@ -822,7 +820,7 @@ def check_support(self) -> None:
822820
rule.isRate()
823821
and not isinstance(
824822
self.sbml.getElementBySId(rule.getVariable()),
825-
sbml.Compartment | sbml.Species | sbml.Parameter,
823+
libsbml.Compartment | libsbml.Species | libsbml.Parameter,
826824
)
827825
for rule in self.sbml.getListOfRules()
828826
):
@@ -1117,7 +1115,7 @@ def _process_rate_rules(self):
11171115
# equations during the _replace_in_all_expressions call inside
11181116
# _process_rules
11191117
for rule in rules:
1120-
if rule.getTypeCode() != sbml.SBML_RATE_RULE:
1118+
if rule.getTypeCode() != libsbml.SBML_RATE_RULE:
11211119
continue
11221120

11231121
variable = symbol_with_assumptions(rule.getVariable())
@@ -1407,10 +1405,10 @@ def _process_rules(self) -> None:
14071405
"""
14081406
for rule in self.sbml.getListOfRules():
14091407
# rate rules are processed in _process_species
1410-
if rule.getTypeCode() == sbml.SBML_RATE_RULE:
1408+
if rule.getTypeCode() == libsbml.SBML_RATE_RULE:
14111409
continue
14121410

1413-
if rule.getTypeCode() == sbml.SBML_ALGEBRAIC_RULE:
1411+
if rule.getTypeCode() == libsbml.SBML_ALGEBRAIC_RULE:
14141412
if self.sbml_doc.getLevel() < 3:
14151413
# not interested in implementing level 2 boundary condition
14161414
# shenanigans, see test 01787 in the sbml testsuite
@@ -1433,7 +1431,7 @@ def _process_rules(self) -> None:
14331431
)
14341432
)
14351433

1436-
def _process_rule_algebraic(self, rule: sbml.AlgebraicRule):
1434+
def _process_rule_algebraic(self, rule: libsbml.AlgebraicRule):
14371435
formula = self._sympy_from_sbml_math(rule)
14381436
if formula is None:
14391437
return
@@ -1461,7 +1459,7 @@ def _process_rule_algebraic(self, rule: sbml.AlgebraicRule):
14611459
# must not be determined by reactions, which means that it
14621460
# must either have the attribute boundaryCondition=“false”
14631461
# or else not be involved in any reaction at all.
1464-
is_species = isinstance(sbml_var, sbml.Species)
1462+
is_species = isinstance(sbml_var, libsbml.Species)
14651463
is_boundary_condition = (
14661464
is_species
14671465
and sbml_var.isSetBoundaryCondition()
@@ -1561,13 +1559,13 @@ def _process_rule_algebraic(self, rule: sbml.AlgebraicRule):
15611559

15621560
self.symbols[SymbolId.ALGEBRAIC_STATE][var] = symbol
15631561

1564-
def _process_rule_assignment(self, rule: sbml.AssignmentRule):
1562+
def _process_rule_assignment(self, rule: libsbml.AssignmentRule):
15651563
sbml_var = self.sbml.getElementBySId(rule.getVariable())
15661564
sym_id = symbol_with_assumptions(rule.getVariable())
15671565

15681566
# Check whether this rule is a spline rule.
15691567
if not self._discard_annotations:
1570-
if rule.getTypeCode() == sbml.SBML_ASSIGNMENT_RULE:
1568+
if rule.getTypeCode() == libsbml.SBML_ASSIGNMENT_RULE:
15711569
annotation = AbstractSpline.get_annotation(rule)
15721570
if annotation is not None:
15731571
spline = AbstractSpline.from_annotation(
@@ -1590,14 +1588,14 @@ def _process_rule_assignment(self, rule: sbml.AssignmentRule):
15901588
if formula is None:
15911589
return
15921590

1593-
if isinstance(sbml_var, sbml.Species):
1591+
if isinstance(sbml_var, libsbml.Species):
15941592
self.species_assignment_rules[sym_id] = formula
15951593

1596-
elif isinstance(sbml_var, sbml.Compartment):
1594+
elif isinstance(sbml_var, libsbml.Compartment):
15971595
self.compartment_assignment_rules[sym_id] = formula
15981596
self.compartments[sym_id] = formula
15991597

1600-
elif isinstance(sbml_var, sbml.Parameter):
1598+
elif isinstance(sbml_var, libsbml.Parameter):
16011599
self.parameter_assignment_rules[sym_id] = formula
16021600

16031601
self.symbols[SymbolId.EXPRESSION][sym_id] = {
@@ -2788,7 +2786,7 @@ def _clean_reserved_symbols(self) -> None:
27882786
}
27892787

27902788
def _sympy_from_sbml_math(
2791-
self, var_or_math: [sbml.SBase, str]
2789+
self, var_or_math: [libsbml.SBase, str]
27922790
) -> sp.Expr | float | None:
27932791
"""
27942792
Sympify Math of SBML variables with all sanity checks and
@@ -2799,8 +2797,8 @@ def _sympy_from_sbml_math(
27992797
:return:
28002798
sympfified symbolic expression
28012799
"""
2802-
if isinstance(var_or_math, sbml.SBase):
2803-
math_string = sbml.formulaToL3StringWithSettings(
2800+
if isinstance(var_or_math, libsbml.SBase):
2801+
math_string = libsbml.formulaToL3StringWithSettings(
28042802
var_or_math.getMath(), self.sbml_parser_settings
28052803
)
28062804
ele_name = var_or_math.element_name
@@ -2860,7 +2858,7 @@ def _get_element_initial_assignment(
28602858
sym = self._make_initial(sym)
28612859
return sym
28622860

2863-
def _get_element_stoichiometry(self, ele: sbml.SBase) -> sp.Expr:
2861+
def _get_element_stoichiometry(self, ele: libsbml.SBase) -> sp.Expr:
28642862
"""
28652863
Computes the stoichiometry of a reactant or product of a reaction
28662864
@@ -2887,7 +2885,7 @@ def _get_element_stoichiometry(self, ele: sbml.SBase) -> sp.Expr:
28872885

28882886
return sp.Integer(1)
28892887

2890-
def is_assignment_rule_target(self, element: sbml.SBase) -> bool:
2888+
def is_assignment_rule_target(self, element: libsbml.SBase) -> bool:
28912889
"""
28922890
Checks if an element has a valid assignment rule in the specified
28932891
model.
@@ -2901,7 +2899,7 @@ def is_assignment_rule_target(self, element: sbml.SBase) -> bool:
29012899
a = self.sbml.getAssignmentRuleByVariable(element.getId())
29022900
return a is not None and self._sympy_from_sbml_math(a) is not None
29032901

2904-
def is_rate_rule_target(self, element: sbml.SBase) -> bool:
2902+
def is_rate_rule_target(self, element: libsbml.SBase) -> bool:
29052903
"""
29062904
Checks if an element has a valid assignment rule in the specified
29072905
model.
@@ -2985,7 +2983,7 @@ def _transform_dxdt_to_concentration(
29852983

29862984

29872985
def _check_lib_sbml_errors(
2988-
sbml_doc: sbml.SBMLDocument, show_warnings: bool = False
2986+
sbml_doc: libsbml.SBMLDocument, show_warnings: bool = False
29892987
) -> None:
29902988
"""
29912989
Checks the error log in the current self.sbml_doc.
@@ -2996,17 +2994,17 @@ def _check_lib_sbml_errors(
29962994
:param show_warnings:
29972995
display SBML warnings
29982996
"""
2999-
num_warning = sbml_doc.getNumErrors(sbml.LIBSBML_SEV_WARNING)
3000-
num_error = sbml_doc.getNumErrors(sbml.LIBSBML_SEV_ERROR)
3001-
num_fatal = sbml_doc.getNumErrors(sbml.LIBSBML_SEV_FATAL)
2997+
num_warning = sbml_doc.getNumErrors(libsbml.LIBSBML_SEV_WARNING)
2998+
num_error = sbml_doc.getNumErrors(libsbml.LIBSBML_SEV_ERROR)
2999+
num_fatal = sbml_doc.getNumErrors(libsbml.LIBSBML_SEV_FATAL)
30023000

30033001
if num_warning + num_error + num_fatal:
30043002
for i_error in range(sbml_doc.getNumErrors()):
30053003
error = sbml_doc.getError(i_error)
30063004
# we ignore any info messages for now
3007-
if error.getSeverity() >= sbml.LIBSBML_SEV_ERROR or (
3005+
if error.getSeverity() >= libsbml.LIBSBML_SEV_ERROR or (
30083006
show_warnings
3009-
and error.getSeverity() >= sbml.LIBSBML_SEV_WARNING
3007+
and error.getSeverity() >= libsbml.LIBSBML_SEV_WARNING
30103008
):
30113009
logger.error(
30123010
f"libSBML {error.getCategoryAsString()} "
@@ -3065,7 +3063,7 @@ def _parse_event_trigger(trigger: sp.Expr) -> sp.Expr:
30653063

30663064

30673065
def assignmentRules2observables(
3068-
sbml_model: sbml.Model, filter_function: Callable = lambda *_: True
3066+
sbml_model: libsbml.Model, filter_function: Callable = lambda *_: True
30693067
):
30703068
"""
30713069
Turn assignment rules into observables.
@@ -3086,7 +3084,7 @@ def assignmentRules2observables(
30863084
"""
30873085
observables = {}
30883086
for rule in sbml_model.getListOfRules():
3089-
if rule.getTypeCode() != sbml.SBML_ASSIGNMENT_RULE:
3087+
if rule.getTypeCode() != libsbml.SBML_ASSIGNMENT_RULE:
30903088
continue
30913089
parameter_id = rule.getVariable()
30923090
if (p := sbml_model.getParameter(parameter_id)) and filter_function(p):
@@ -3143,7 +3141,7 @@ def _add_conservation_for_constant_species(
31433141
return species_solver
31443142

31453143

3146-
def _get_species_compartment_symbol(species: sbml.Species) -> sp.Symbol:
3144+
def _get_species_compartment_symbol(species: libsbml.Species) -> sp.Symbol:
31473145
"""
31483146
Generate compartment symbol for the compartment of a specific species.
31493147
This function will always return the same unique python object for a
@@ -3157,7 +3155,7 @@ def _get_species_compartment_symbol(species: sbml.Species) -> sp.Symbol:
31573155
return symbol_with_assumptions(species.getCompartment())
31583156

31593157

3160-
def _get_identifier_symbol(var: sbml.SBase) -> sp.Symbol:
3158+
def _get_identifier_symbol(var: libsbml.SBase) -> sp.Symbol:
31613159
"""
31623160
Generate identifier symbol for a sbml variable.
31633161
This function will always return the same unique python object for a
@@ -3171,7 +3169,7 @@ def _get_identifier_symbol(var: sbml.SBase) -> sp.Symbol:
31713169
return symbol_with_assumptions(var.getId())
31723170

31733171

3174-
def get_species_initial(species: sbml.Species) -> sp.Expr:
3172+
def get_species_initial(species: libsbml.Species) -> sp.Expr:
31753173
"""
31763174
Extract the initial concentration from a given species
31773175
@@ -3202,8 +3200,8 @@ def get_species_initial(species: sbml.Species) -> sp.Expr:
32023200

32033201

32043202
def _get_list_of_species_references(
3205-
sbml_model: sbml.Model,
3206-
) -> list[sbml.SpeciesReference]:
3203+
sbml_model: libsbml.Model,
3204+
) -> list[libsbml.SpeciesReference]:
32073205
"""
32083206
Extracts list of species references as SBML doesn't provide a native
32093207
function for this.
@@ -3242,7 +3240,7 @@ def replace_logx(math_str: str | float | None) -> str | float | None:
32423240

32433241

32443242
def _collect_event_assignment_parameter_targets(
3245-
sbml_model: sbml.Model,
3243+
sbml_model: libsbml.Model,
32463244
) -> list[sp.Symbol]:
32473245
targets = []
32483246
sbml_parameters = sbml_model.getListOfParameters()
@@ -3320,11 +3318,11 @@ def _check_symbol_nesting(
33203318
)
33213319

33223320

3323-
def _non_const_conservation_laws_supported(sbml_model: sbml.Model) -> bool:
3321+
def _non_const_conservation_laws_supported(sbml_model: libsbml.Model) -> bool:
33243322
"""Check whether non-constant conservation laws can be handled for the
33253323
given model."""
33263324
if any(
3327-
rule.getTypeCode() == sbml.SBML_RATE_RULE
3325+
rule.getTypeCode() == libsbml.SBML_RATE_RULE
33283326
for rule in sbml_model.getListOfRules()
33293327
):
33303328
# see SBML semantic test suite, case 33 for an example
@@ -3337,7 +3335,7 @@ def _non_const_conservation_laws_supported(sbml_model: sbml.Model) -> bool:
33373335
return False
33383336

33393337
if any(
3340-
rule.getTypeCode() == sbml.SBML_ASSIGNMENT_RULE
3338+
rule.getTypeCode() == libsbml.SBML_ASSIGNMENT_RULE
33413339
and sbml_model.getSpecies(rule.getVariable())
33423340
for rule in sbml_model.getListOfRules()
33433341
):

0 commit comments

Comments
 (0)