Skip to content

Commit 4a12617

Browse files
committed
chore: debugged model changing
1 parent e9fba6d commit 4a12617

File tree

6 files changed

+70
-32
lines changed

6 files changed

+70
-32
lines changed

Dockerfile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222

2323
FROM python:3.9-slim-buster
2424

25-
ARG VERSION="0.1.14"
25+
ARG VERSION="0.1.15"
2626
ARG SIMULATOR_VERSION=2.6.0
2727

2828
# metadata

biosimulators_bionetgen/_version.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
__version__ = '0.1.14'
1+
__version__ = '0.1.15'

biosimulators_bionetgen/core.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@
88
"""
99

1010
from .io import read_task
11-
from .utils import (exec_bionetgen_task, preprocess_model_attribute_change, add_model_attribute_change_to_task, add_simulation_to_task,
11+
from .utils import (exec_bionetgen_task, preprocess_model_attribute_change, add_model_attribute_change_to_task,
12+
create_actions_for_simulation,
1213
get_variables_results_from_observable_results, add_variables_to_model)
1314
from .warnings import IgnoredBnglFileContentWarning
1415
from biosimulators_utils.combine.exec import exec_sedml_docs_in_archive
@@ -21,6 +22,7 @@
2122
UniformTimeCourseSimulation, Variable)
2223
from biosimulators_utils.sedml.exec import exec_sed_doc as base_exec_sed_doc
2324
from biosimulators_utils.utils.core import raise_errors_warnings
25+
import copy
2426
import warnings
2527

2628
__all__ = ['exec_sedml_docs_in_combine_archive', 'exec_sed_doc', 'exec_sed_task', 'preprocess_sed_task']
@@ -145,6 +147,8 @@ def exec_sed_task(task, variables, preprocessed_task=None, log=None, config=None
145147

146148
# read the model from the BNGL file
147149
bionetgen_task = preprocessed_task['bionetgen_task']
150+
preprocessed_actions = bionetgen_task.actions
151+
bionetgen_task.actions = copy.deepcopy(preprocessed_actions)
148152

149153
# validate and apply the model attribute changes to the BioNetGen task
150154
for change in task.model.changes:
@@ -154,6 +158,8 @@ def exec_sed_task(task, variables, preprocessed_task=None, log=None, config=None
154158
alg_kisao_id = preprocessed_task['algorithm_kisao_id']
155159

156160
# execute the task
161+
bionetgen_task.actions.extend(preprocessed_task['simulation_actions'])
162+
157163
observable_results = exec_bionetgen_task(bionetgen_task)
158164

159165
# get predicted values of the variables
@@ -168,6 +174,9 @@ def exec_sed_task(task, variables, preprocessed_task=None, log=None, config=None
168174
'actions': bionetgen_task.actions,
169175
}
170176

177+
# clean up
178+
bionetgen_task.actions = preprocessed_actions
179+
171180
# return the values of the variables and log
172181
return variable_results, log
173182

@@ -226,11 +235,12 @@ def preprocess_sed_task(task, variables, config=None):
226235
add_variables_to_model(bionetgen_task.model, variables)
227236

228237
# apply the SED algorithm and its parameters to the BioNetGen task
229-
alg_kisao_id = add_simulation_to_task(bionetgen_task, task.simulation)
238+
simulation_actions, alg_kisao_id = create_actions_for_simulation(task.simulation)
230239

231240
# return the values of the variables and log
232241
return {
233242
'bionetgen_task': bionetgen_task,
234243
'model_changes': model_changes,
244+
'simulation_actions': simulation_actions,
235245
'algorithm_kisao_id': alg_kisao_id,
236246
}

biosimulators_bionetgen/utils.py

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
'preprocess_model_attribute_change',
3030
'add_model_attribute_change_to_task',
3131
'add_variables_to_model',
32-
'add_simulation_to_task',
32+
'create_actions_for_simulation',
3333
'exec_bionetgen_task',
3434
'get_variables_results_from_observable_results',
3535
]
@@ -70,7 +70,8 @@ def preprocess_model_attribute_change(task, change):
7070
'type': 'replace_line_in_block',
7171
'block': block,
7272
'i_line': i_line,
73-
'new_line': lambda new_value: '{} {} {} {}'.format(obj_id, match.group(1), new_value, (match.group(3) or '').strip()).strip(),
73+
'new_line': lambda new_value: '{} {} {} {}'.format(
74+
obj_id, match.group(1), new_value, (match.group(3) or '').strip()).strip(),
7475
}
7576

7677
if not comp_changed:
@@ -241,11 +242,10 @@ def add_variables_to_model(model, variables):
241242
raise NotImplementedError(msg)
242243

243244

244-
def add_simulation_to_task(task, simulation, config=None):
245-
""" Add a SED simulation to a BioNetGen task
245+
def create_actions_for_simulation(simulation, config=None):
246+
""" Create BioNetGen actions for a SED simulation
246247
247248
Args:
248-
task (:obj:`Task`): BioNetGen task
249249
simulation (:obj:`UniformTimeCourseSimulation`): SED simulation
250250
config (:obj:`Config`, optional): configuration
251251
@@ -254,7 +254,10 @@ def add_simulation_to_task(task, simulation, config=None):
254254
algorithm parameters
255255
256256
Returns:
257-
:obj:`str`: KiSAO id of the algorithm that will be executed
257+
:obj:`tuple`:
258+
259+
* :obj:`list` of :obj:`str`: actions for SED simulation
260+
* :obj:`str`: KiSAO id of the algorithm that will be executed
258261
"""
259262
simulate_args = OrderedDict()
260263

@@ -311,15 +314,17 @@ def add_simulation_to_task(task, simulation, config=None):
311314
])
312315
warn(msg, BioSimulatorsWarning)
313316

314-
# if necessary add network generation to the BioNetGen task
317+
# if necessary create a network generation action
318+
actions = []
319+
315320
if simulation_method['generate_network']:
316-
task.actions.append("generate_network({overwrite => 1})")
321+
actions.append("generate_network({overwrite => 1})")
317322

318-
# add the simulation to the BioNetGen task
319-
task.actions.append('simulate({{{}}})'.format(', '.join('{} => {}'.format(key, val) for key, val in simulate_args.items())))
323+
# create a simulation action
324+
actions.append('simulate({{{}}})'.format(', '.join('{} => {}'.format(key, val) for key, val in simulate_args.items())))
320325

321-
# return the KiSAO id of the algorithm that will be executed
322-
return exec_kisao_id
326+
# return actions and the KiSAO id of the algorithm that will be executed
327+
return actions, exec_kisao_id
323328

324329

325330
def exec_bionetgen_task(task):

tests/test_core_main.py

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
from biosimulators_utils.simulator.exec import exec_sedml_docs_in_archive_with_containerized_simulator
2121
from biosimulators_utils.simulator.specs import gen_algorithms_from_specs
2222
from unittest import mock
23+
import copy
2324
import datetime
2425
import dateutil.tz
2526
import numpy
@@ -52,6 +53,25 @@ def test_exec_sed_task(self):
5253
self.assertEqual(variable_results['var_time'].size, sim.number_of_points + 1)
5354
numpy.testing.assert_allclose(variable_results['var_time'],
5455
numpy.linspace(sim.output_start_time, sim.output_end_time, sim.number_of_points + 1))
56+
numpy.testing.assert_allclose(variable_results['var_A'][0], 4, rtol=1e-1)
57+
58+
doc2 = copy.deepcopy(doc)
59+
doc2.tasks[0].model.changes.append(sedml_data_model.ModelAttributeChange(
60+
target='species.A().initialCount',
61+
new_value='5',
62+
))
63+
variable_results_2, _ = exec_sed_task(doc2.tasks[0], variables)
64+
numpy.testing.assert_allclose(variable_results_2['var_A'][0], 5, rtol=1e-1)
65+
self.assertGreater(variable_results_2['var_A'][0], variable_results['var_A'][0])
66+
67+
doc3 = copy.deepcopy(doc)
68+
doc3.tasks[0].model.changes.append(sedml_data_model.ModelAttributeChange(
69+
target='species.A().initialCount',
70+
new_value=6,
71+
))
72+
variable_results_3, _ = exec_sed_task(doc3.tasks[0], variables)
73+
numpy.testing.assert_allclose(variable_results_3['var_A'][0], 6, rtol=1e-1)
74+
self.assertGreater(variable_results_3['var_A'][0], variable_results_2['var_A'][0])
5575

5676
def test_exec_sed_task_non_zero_initial_time(self):
5777
doc = self._build_sed_doc()
@@ -75,7 +95,7 @@ def test_exec_sedml_docs_in_combine_archive(self):
7595
out_dir = os.path.join(self.dirname, 'out')
7696

7797
config = get_config()
78-
config.REPORT_FORMATS = [report_data_model.ReportFormat.h5, report_data_model.ReportFormat.csv,]
98+
config.REPORT_FORMATS = [report_data_model.ReportFormat.h5, report_data_model.ReportFormat.csv]
7999
config.BUNDLE_OUTPUTS = True
80100
config.KEEP_INDIVIDUAL_OUTPUTS = True
81101

@@ -92,7 +112,7 @@ def test_exec_sedml_docs_in_combine_archive_with_all_algorithms(self):
92112
out_dir = os.path.join(self.dirname, alg.kisao_id)
93113

94114
config = get_config()
95-
config.REPORT_FORMATS = [report_data_model.ReportFormat.h5, report_data_model.ReportFormat.csv,]
115+
config.REPORT_FORMATS = [report_data_model.ReportFormat.h5, report_data_model.ReportFormat.csv]
96116
config.BUNDLE_OUTPUTS = True
97117
config.KEEP_INDIVIDUAL_OUTPUTS = True
98118

@@ -171,8 +191,8 @@ def _build_sed_doc(self, algorithm=None):
171191
changes=[
172192
sedml_data_model.ModelAttributeChange(target='functions.gfunc.expression', new_value='0.5*Atot^2/(10 + Atot^2)'),
173193
sedml_data_model.ModelAttributeChange(target='functions.gfunc().expression', new_value='0.5*Atot^2/(10 + Atot^2)'),
174-
sedml_data_model.ModelAttributeChange(target='species.A().initialCount', new_value='5'),
175-
sedml_data_model.ModelAttributeChange(target='parameters.g1.value', new_value='16.0'),
194+
sedml_data_model.ModelAttributeChange(target='species.A().initialCount', new_value='4'),
195+
sedml_data_model.ModelAttributeChange(target='parameters.g1.value', new_value='18.0'),
176196
],
177197
))
178198
doc.simulations.append(sedml_data_model.UniformTimeCourseSimulation(

tests/test_utils.py

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from biosimulators_bionetgen.data_model import Task
44
from biosimulators_bionetgen.utils import (add_model_attribute_change_to_task,
55
add_variables_to_model,
6-
add_simulation_to_task,
6+
create_actions_for_simulation,
77
exec_bionetgen_task,
88
get_variables_results_from_observable_results,)
99
from biosimulators_bionetgen.io import read_task, read_simulation_results, write_task
@@ -63,6 +63,10 @@ def test_add_model_attribute_change_to_task(self):
6363
add_model_attribute_change_to_task(task, change)
6464
self.assertEqual(task.actions[-1], 'setParameter("k_1", 1.0)')
6565

66+
change = ModelAttributeChange(target='parameters.k_1.value', new_value=2.0)
67+
add_model_attribute_change_to_task(task, change)
68+
self.assertEqual(task.actions[-1], 'setParameter("k_1", 2.0)')
69+
6670
change = ModelAttributeChange(target='species.GeneA_00().initialCount', new_value='1')
6771
add_model_attribute_change_to_task(task, change)
6872
self.assertEqual(task.actions[-1], 'setConcentration("GeneA_00()", 1)')
@@ -140,9 +144,8 @@ def test_add_variables_to_task(self):
140144
with self.assertRaisesRegex(NotImplementedError, 'targets are not supported'):
141145
add_variables_to_model(task.model, [Variable(id='X', target='x')])
142146

143-
def test_add_simulation_to_task(self):
147+
def test_create_actions_for_simulation(self):
144148
# CVODE
145-
task = Task()
146149
simulation = UniformTimeCourseSimulation(
147150
initial_time=0.,
148151
output_start_time=10.,
@@ -155,44 +158,44 @@ def test_add_simulation_to_task(self):
155158
]
156159
),
157160
)
158-
add_simulation_to_task(task, simulation)
159-
self.assertEqual(task.actions, [
161+
actions, _ = create_actions_for_simulation(simulation)
162+
self.assertEqual(actions, [
160163
'generate_network({overwrite => 1})',
161164
'simulate({t_start => 0.0, t_end => 20.0, n_steps => 20, method => "ode", atol => 1e-6})',
162165
])
163166

164167
# Error handling: non-integer steps
165168
simulation.output_end_time = 20.1
166169
with self.assertRaisesRegex(NotImplementedError, 'must specify an integer number of steps'):
167-
add_simulation_to_task(task, simulation)
170+
create_actions_for_simulation(simulation)
168171

169172
# Error handling: non-zero initial time
170173
simulation.output_end_time = 20.0
171174
simulation.initial_time = 5.
172175
simulation.algorithm.kisao_id = 'KISAO_0000019'
173-
add_simulation_to_task(task, simulation)
176+
create_actions_for_simulation(simulation)
174177

175178
simulation.initial_time = 5.
176179
simulation.algorithm.kisao_id = 'KISAO_0000263'
177180
with self.assertRaisesRegex(NotImplementedError, 'must be 0'):
178-
add_simulation_to_task(task, simulation)
181+
create_actions_for_simulation(simulation)
179182

180183
# Error handling: unknown algorithm
181184
simulation.algorithm.kisao_id = 'KISAO_0000448'
182185
with self.assertRaisesRegex(AlgorithmCannotBeSubstitutedException, 'No algorithm can be substituted'):
183-
add_simulation_to_task(task, simulation)
186+
create_actions_for_simulation(simulation)
184187

185188
# Error handling: unknown algorithm parameter
186189
simulation.algorithm.kisao_id = 'KISAO_0000019'
187190
simulation.algorithm.changes[0].kisao_id = 'KISAO_0000001'
188191

189192
with mock.patch.dict('os.environ', {'ALGORITHM_SUBSTITUTION_POLICY': 'NONE'}):
190193
with self.assertRaisesRegex(NotImplementedError, 'is not supported. Parameter must have'):
191-
add_simulation_to_task(task, simulation)
194+
create_actions_for_simulation(simulation)
192195

193196
with mock.patch.dict('os.environ', {'ALGORITHM_SUBSTITUTION_POLICY': 'SIMILAR_VARIABLES'}):
194197
with pytest.warns(BioSimulatorsWarning, match='is not supported. Parameter must have'):
195-
add_simulation_to_task(task, simulation)
198+
create_actions_for_simulation(simulation)
196199

197200
def test_exec_bionetgen_task(self):
198201
model_filename = os.path.join(os.path.dirname(__file__), 'fixtures', 'test.bngl')
@@ -273,7 +276,7 @@ def test_get_parameters_variables_outputs_for_simulation(self):
273276
model_filename_2 = os.path.join(self.dirname, 'task.bngl')
274277
write_task(task, model_filename_2)
275278

276-
changes_2, sim, variables_2,plots_2 = get_parameters_variables_outputs_for_simulation(
279+
changes_2, sim, variables_2, plots_2 = get_parameters_variables_outputs_for_simulation(
277280
model_filename_2, None, UniformTimeCourseSimulation, None)
278281
for change, change_2 in zip(changes, changes_2):
279282
self.assertTrue(change_2.is_equal(change))

0 commit comments

Comments
 (0)