Skip to content

Commit

Permalink
- progress making cns compatible with 4.43
Browse files Browse the repository at this point in the history
  • Loading branch information
fbergmann committed Apr 3, 2024
1 parent 361968c commit 4484b5b
Show file tree
Hide file tree
Showing 5 changed files with 41 additions and 17 deletions.
4 changes: 4 additions & 0 deletions basico/model_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -4943,6 +4943,10 @@ def set_task_settings(task, settings, **kwargs):
if r_def is not None:
report.setReportDefinition(r_def)

def _get_cn_string(cn):
if isinstance(cn, COPASI.CCommonName):
return cn.getString()
return str(cn)

def _collect_data(names=None, cns=None, **kwargs):
"""Collects data from the model, returning it as dataframe
Expand Down
39 changes: 26 additions & 13 deletions basico/task_parameterestimation.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"""
import shutil
import sys

import pandas
import COPASI
Expand All @@ -30,6 +31,8 @@
import yaml

import basico

from . import model_info
from basico.callbacks import get_default_handler

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -631,7 +634,6 @@ def get_fit_item_template(include_local=False, include_global=False, default_lb=

return result


def get_fit_parameters(model=None):
"""Returns a data frame with all fit parameters
Expand Down Expand Up @@ -666,11 +668,11 @@ def get_fit_parameters(model=None):
name = obj.getObjectDisplayName()
data.append({
'name': name,
'lower': item.getLowerBound(),
'upper': item.getUpperBound(),
'lower': model_info._get_cn_string(item.getLowerBound()),
'upper': model_info._get_cn_string(item.getUpperBound()),
'start': item.getStartValue(),
'affected': _get_affected_experiments(item),
'cn': item.getObjectCN(),
'cn': model_info._get_cn_string(item.getObjectCN()),
})

if not data:
Expand Down Expand Up @@ -712,11 +714,11 @@ def get_fit_constraints(model=None):
name = obj.getObjectDisplayName()
data.append({
'name': name,
'lower': item.getLowerBound(),
'upper': item.getUpperBound(),
'lower': model_info._get_cn_string(item.getLowerBound()),
'upper': model_info._get_cn_string(item.getUpperBound()),
'start': item.getStartValue(),
'affected': _get_affected_experiments(item),
'cn': item.getObjectCN(),
'cn': model_info._get_cn_string(item.getObjectCN()),
})

if not data:
Expand Down Expand Up @@ -767,9 +769,15 @@ def set_fit_parameters(fit_parameters, model=None):
name = None

if 'cn' in item:
cn = COPASI.CCommonName(item.cn)
if isinstance(item.cn, COPASI.CRegisteredCommonName):
cn_string = item.cn.getString()
else:
cn_string = str(item.cn)

elif 'name' in item:
if cn_string:
cn = COPASI.CRegisteredCommonName(cn_string)

if 'name' in item and cn is None:
name = item['name']
if not cn:
obj = basico.model_info._get_object(name, initial=True, model=model)
Expand Down Expand Up @@ -940,8 +948,8 @@ def get_parameters_solution(model=None):
name = obj.getObjectDisplayName()
data.append({
'name': name,
'lower': item.getLowerBound(),
'upper': item.getUpperBound(),
'lower': model_info._get_cn_string(item.getLowerBound()),
'upper': model_info._get_cn_string(item.getUpperBound()),
'sol': sol,
'affected': _get_affected_experiments(item),
})
Expand Down Expand Up @@ -1065,7 +1073,7 @@ def add_experiment(name, data, **kwargs):
except AttributeError:
logger.error("Cannot map the element {0}".format(current))
role = _get_role_for_reference(obj.getObjectName())
if not obj_map.setObjectCN(i, str(obj.getCN())):
if not obj_map.setObjectCN(i, obj.getCN()):
logger.error("Error while mapping data for for {0}".format(current))
obj_map.setRole(i, role)

Expand Down Expand Up @@ -1363,7 +1371,12 @@ def _get_value_from_bound(bound):
:rtype: float
"""
try:
value = float(bound)
if isinstance(bound, COPASI.CRegisteredCommonName):
value = basico.get_value(bound)
if value is None:
value = bound.getString()
else:
value = float(bound)
except ValueError:
value = basico.get_value(bound)
return value
Expand Down
5 changes: 3 additions & 2 deletions basico/task_profile_likelihood.py
Original file line number Diff line number Diff line change
Expand Up @@ -429,7 +429,7 @@ def _generate_scan_for_item(item, index, data_dir, update_model=False, lower=Fal
problem2.clearScanItems()
problem2.addScanItem(1, Arguments["scan_interval"])
scan_item = problem2.getScanItem(0)
scan_item.getParameter("Object").setCNValue(COPASI.CCommonName(item["cn"]))
scan_item.getParameter("Object").setCNValue(COPASI.CRegisteredCommonName(item["cn"]))

start_value = item["start_value"]
param_sd = kwargs.get('param_sds', {}).get(item["name"], None)
Expand Down Expand Up @@ -462,7 +462,8 @@ def _generate_scan_for_item(item, index, data_dir, update_model=False, lower=Fal
report.setConfirmOverwrite(False)
logger.debug("... Generate Plot")
plot = COPASI.COutputAssistant.createDefaultOutput(251, scan_task, _DataModel)
plot.setObjectName('{0} = {1}'.format('opt', start_value))
if plot is not None:
plot.setObjectName('{0} = {1}'.format('opt', start_value))
out_file = os.path.abspath("{0}/{1}_{2:05d}_{3}.cps".format(data_dir, Arguments['prefix'], index, middle))
logger.debug(f"Writing '{out_file}'.")
_DataModel.saveModel(out_file, True)
Expand Down
7 changes: 5 additions & 2 deletions basico/task_scan.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ def _scan_item_to_dict(item, model=None):
int_type = item.getParameter('Type').getIntValue()
type_name = _scan_type_to_name(int_type)
cn = item.getParameter('Object').getCNValue().getString() if item.getParameter('Object') else None
cn = model_info._get_cn_string(cn)
num_steps = item.getParameter('Number of steps').getIntValue() if item.getParameter('Number of steps') else None
min_val = item.getParameter('Minimum').getDblValue() if item.getParameter('Minimum') else None
max_val = item.getParameter('Maximum').getDblValue() if item.getParameter('Maximum') else None
Expand Down Expand Up @@ -176,9 +177,11 @@ def _scan_item_to_dict(item, model=None):
assert (isinstance(cn_group, COPASI.CCopasiParameterGroup))
parameter_sets = []
for i in range(cn_group.size()):
cn = cn_group.getParameter(i).getCNValue()
_cn = model_info._get_cn_string(cn_group.getParameter(i).getCNValue())
if not _cn:
continue
# resolve cn to name
obj = model.getObject(cn)
obj = model.getObject(COPASI.CCommonName(_cn))
if obj:
parameter_sets.append(obj.getObjectName())
current['parameter_sets'] = parameter_sets
Expand Down
3 changes: 3 additions & 0 deletions tests/test_optimization.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ def setUp(self):
basico.add_parameter('f', type='assignment',
expression='({Values[x].InitialValue}^2+{Values[y].InitialValue}-11)^2+({Values[x].InitialValue}+{Values[y].InitialValue}^2-7)^2')

def tearDown(self):
basico.remove_datamodel(self.dm)

def test_optitems(self):
self.assertIsNone(basico.get_opt_parameters())
template = basico.get_opt_item_template(include_global=True)
Expand Down

0 comments on commit 4484b5b

Please sign in to comment.