Skip to content

Commit

Permalink
- consistently use default handler and capture messages
Browse files Browse the repository at this point in the history
  • Loading branch information
fbergmann committed Dec 6, 2023
1 parent 68ae881 commit 2b65bb7
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 55 deletions.
28 changes: 22 additions & 6 deletions basico/task_optimization.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@
except ValueError:
import model_io

from . import model_info
from .callbacks import get_default_handler

logger = logging.getLogger(__name__)

def get_opt_parameters(model=None):
Expand Down Expand Up @@ -458,12 +461,22 @@ def run_optimization(expression=None, output=None, settings=None, **kwargs):
dh, cols = basico.task_timecourse.create_data_handler(output, after=output, model=model)
model.addInterface(dh)

if not task.initializeRaw(COPASI.CCopasiTask.OUTPUT_UI):
logger.warning("Couldn't initialize optimization task")

num_messages_before = COPASI.CCopasiMessage.size()
use_initial_values = kwargs.get('use_initial_values', True)
if not task.processRaw(use_initial_values):
logger.warning("Couldn't process optimization task")

task.setCallBack(get_default_handler())

result = task.initializeRaw(COPASI.CCopasiTask.OUTPUT_UI)
if not result:
logger.error("Couldn't initialize optimization task: " +
model_info.get_copasi_messages(num_messages_before, 'No output'))
else:
result = task.processRaw(use_initial_values)
if not result:
logger.error("Couldn't process optimization task: " +
model_info.get_copasi_messages(num_messages_before))

task.restore()

if dh:
model.removeInterface(dh)
Expand Down Expand Up @@ -503,5 +516,8 @@ def get_opt_statistic(**kwargs):
'failed_constraint_evals': problem.geFailedConstraintCounter(),
'cpu_time': problem.getExecutionTime(),
}
result['evals_per_sec'] = result['cpu_time'] / result['f_evals']
if result['f_evals'] == 0:
result['evals_per_sec'] = 0
else:
result['evals_per_sec'] = result['cpu_time'] / result['f_evals']
return result
23 changes: 11 additions & 12 deletions basico/task_parameterestimation.py
Original file line number Diff line number Diff line change
Expand Up @@ -1177,24 +1177,23 @@ def run_parameter_estimation(**kwargs):
if 'settings' in kwargs:
basico.set_task_settings(task, kwargs['settings'])

num_messages_before = COPASI.CCopasiMessage.size()

task.setCallBack(get_default_handler())
result = task.initializeRaw(COPASI.CCopasiTask.OUTPUT_UI)
can_run = True
if not result:
message = COPASI.CCopasiMessage.getLastMessage().getText()
can_run = False
if message.endswith("CCopasiTask (5): No output file defined for report of task 'Parameter Estimation'."):
can_run = True
if not can_run:
logger.error("Error while initializing parameter estimation: " + message)

if can_run:
logger.error("Error while initializing parameter estimation: " +
basico.model_info.get_copasi_messages(num_messages_before, 'No output'))
else:
result = task.processRaw(use_initial_values)
if not result:
logger.error("Error while running parameter estimation: " +
COPASI.CCopasiMessage.getLastMessage().getText())
task.setCallBack(None)
logger.error("Error while initializing parameter estimation: " +
basico.model_info.get_copasi_messages(num_messages_before))

task.restore()

problem.setCreateParameterSets(old_create_parameter_sets)

if not write_report:
task.getReport().setTarget(report_name)

Expand Down
10 changes: 8 additions & 2 deletions basico/task_steadystate.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import COPASI
from . import model_io
from . import model_info
from .callbacks import get_default_handler
import logging

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -80,14 +81,19 @@ def run_steadystate(**kwargs):
if 'settings' in kwargs:
model_info.set_task_settings(task, kwargs['settings'])

num_messages_before = COPASI.CCopasiMessage.size()

result = task.initializeRaw(COPASI.CCopasiTask.OUTPUT_UI)
if not result:
logger.error("Error while initializing the simulation: " +
COPASI.CCopasiMessage.getLastMessage().getText())
model_info.get_copasi_messages(num_messages_before, 'No output'))
else:
task.setCallBack(get_default_handler())
result = task.processRaw(use_initial_values)
if not result:
logger.error("Error while running the simulation: " +
COPASI.CCopasiMessage.getLastMessage().getText())
model_info.get_copasi_messages(num_messages_before))

task.restore()

return task.getResult()
48 changes: 13 additions & 35 deletions basico/task_timecourse.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
logger = logging.getLogger(__name__)

def __build_result_from_ts(time_series, use_concentrations=True, use_sbml_id=False, model=None):
# type: (COPASI.CTimeSeries) -> pandas.DataFrame
# type: (COPASI.CTimeSeries, Optional[bool], Optional[bool], Optional[bool]) -> pandas.DataFrame
col_count = time_series.getNumVariables()
row_count = time_series.getRecordedSteps()

Expand Down Expand Up @@ -158,17 +158,22 @@ def run_time_course_with_output(output_selection, *args, **kwargs):
task, use_initial_values = _setup_timecourse(args, kwargs)

model.addInterface(dh)

# remember messages before running the task
num_messages_before = COPASI.CCopasiMessage.size()

result = task.initializeRaw(COPASI.CCopasiTask.OUTPUT_UI)
task.setCallBack(get_default_handler())
if not result:
logger.error("Error while initializing the simulation: " +
COPASI.CCopasiMessage.getLastMessage().getText())
model_info.get_copasi_messages(num_messages_before, 'No output'))
else:
task.setCallBack(get_default_handler())
result = task.processRaw(use_initial_values)
if not result:
logger.error("Error while running the simulation: " +
COPASI.CCopasiMessage.getLastMessage().getText())
task.setCallBack(COPASI.CProcessReport())
model_info.get_copasi_messages(num_messages_before))

task.restore()
df = get_data_from_data_handler(dh, columns)
model.removeInterface(dh)

Expand Down Expand Up @@ -317,19 +322,19 @@ def run_time_course(*args, **kwargs):

task, use_initial_values = _setup_timecourse(args, kwargs)

# clear error log
# remember messages before running the task
num_messages_before = COPASI.CCopasiMessage.size()

result = task.initializeRaw(COPASI.CCopasiTask.OUTPUT_UI)
if not result:
logger.error("Error while initializing the simulation: " +
_get_messages(num_messages_before, 'No output'))
model_info.get_copasi_messages(num_messages_before, 'No output'))
else:
task.setCallBack(get_default_handler())
result = task.processRaw(use_initial_values)
if not result:
logger.error("Error while running the simulation: " +
_get_messages(num_messages_before))
model_info.get_copasi_messages(num_messages_before))

use_concentrations = kwargs.get('use_concentrations', True)
if 'use_numbers' in kwargs and kwargs['use_numbers']:
Expand Down Expand Up @@ -406,30 +411,3 @@ def _setup_timecourse(args, kwargs):
if 'settings' in kwargs:
model_info.set_task_settings(task, kwargs['settings'])
return task, use_initial_values


def _get_messages(num_messages_before, filters=None):
""" Returns error messages that occurred while initializing or running the simulation
:param num_messages_before: number of messages before calling initialization or process
:param filters: optional list of filter expressions of what messages to ignore
:type filters: list of str or str or None
:return: error messages in form of a string
"""
messages = []
if filters is None:
filters = []
if type(filters) == str:
filters = [filters]
while COPASI.CCopasiMessage.size() > num_messages_before:
message = COPASI.CCopasiMessage.getLastMessage()
skip = False
for filter_text in filters:
if filter_text in message.getText():
skip = True
break
if not skip:
messages.insert(0, message.getText())
return "".join(messages)

0 comments on commit 2b65bb7

Please sign in to comment.