示例#1
0
def set_objective_function(expression,
                           maximize=None,
                           minimize=None,
                           model=None):
    """Sets the objective function to be used

    :param expression: the expression to be used as objective function, it can contain any display names of model
           elements. So for example to minimize an initial value of a global parameter `x` the expression would look like
           `Values[x].InitialValue`.

    :param maximize: optional boolean indicating whether the expression should be maximized

    :param minimize: optional boolean indicating whether the expression should be minimized

    :param model: the model to be used or None

    :return: None
    """
    if model is None:
        model = model_io.get_current_model()

    task = model.getTask(basico.T.OPTIMIZATION)
    assert (isinstance(task, COPASI.COptTask))
    problem = task.getProblem()
    assert (isinstance(problem, COPASI.COptProblem))

    if not problem.setObjectiveFunction(
            basico.model_info._replace_names_with_cns(expression,
                                                      model=model)):
        logging.error('invalid objective function: {0}'.format(expression))

    if maximize:
        problem.setMaximize(maximize)
    if minimize:
        problem.setMaximize(not minimize)
示例#2
0
def get_experiment_filenames(model=None):
    """Returns filenames of all experiments

    :param model: the model to get the data from
    :type model: COPASI.CDataModel or None
    :return: list of filenames of experimental data
    :rtype: [str]
    """
    if model is None:
        model = model_io.get_current_model()
    result = []

    task = model.getTask(TASK_PARAMETER_ESTIMATION)
    assert (isinstance(task, COPASI.CFitTask))

    problem = task.getProblem()
    assert (isinstance(problem, COPASI.CFitProblem))

    experiments = problem.getExperimentSet()
    assert (isinstance(experiments, COPASI.CExperimentSet))

    num_experiments = experiments.getExperimentCount()
    if num_experiments == 0:
        return result

    for i in range(num_experiments):
        experiment = experiments.getExperiment(i)
        result.append(_get_experiment_file(experiment))

    return result
示例#3
0
def get_experiment_names(**kwargs):
    """Returns the list of experiment names

    :param kwargs:

    - | `model`: to specify the data model to be used (if not specified
      | the one from :func:`.get_current_model` will be taken)

    :return: list of experiment names defined
    :rtype: [str]
    """
    model = kwargs.get('model', model_io.get_current_model())
    assert (isinstance(model, COPASI.CDataModel))

    task = model.getTask(TASK_PARAMETER_ESTIMATION)
    assert (isinstance(task, COPASI.CFitTask))

    problem = task.getProblem()
    assert (isinstance(problem, COPASI.CFitProblem))

    result = []
    for i in range(problem.getExperimentSet().size()):
        experiment = problem.getExperimentSet().getExperiment(i)
        result.append(experiment.getObjectName())
    return result
def get_experiment_data_from_model(model=None):
    # type: (COPASI.CDataModel) -> [pandas.DataFrame]
    if model is None:
        model = model_io.get_current_model()
    result = []

    task = model.getTask("Parameter Estimation")
    assert (isinstance(task, COPASI.CFitTask))

    problem = task.getProblem()
    assert (isinstance(problem, COPASI.CFitProblem))

    experiments = problem.getExperimentSet()
    assert (isinstance(experiments, COPASI.CExperimentSet))

    num_experiments = experiments.getExperimentCount()
    if num_experiments == 0:
        return result

    for i in range(num_experiments):
        experiment = experiments.getExperiment(i)
        df = get_data_from_experiment(experiment)
        result.append(df)

    return result
示例#5
0
def get_experiment_data_from_model(model=None):
    """Returns all experimental data from the model

    :param model: the model to get the data from
    :type model: COPASI.CDataModel or None
    :return: list of dataframes with experimental data (with columns renamed and unmapped columns dropped)
    :rtype: [pandas.DataFrame]
    """
    if model is None:
        model = model_io.get_current_model()
    result = []

    task = model.getTask(TASK_PARAMETER_ESTIMATION)
    assert (isinstance(task, COPASI.CFitTask))

    problem = task.getProblem()
    assert (isinstance(problem, COPASI.CFitProblem))

    experiments = problem.getExperimentSet()
    assert (isinstance(experiments, COPASI.CExperimentSet))

    num_experiments = experiments.getExperimentCount()
    if num_experiments == 0:
        return result

    for i in range(num_experiments):
        experiment = experiments.getExperiment(i)
        df = get_data_from_experiment(experiment, rename_headers=True)
        result.append(df)

    return result
示例#6
0
def get_experiment(experiment, **kwargs):
    """Returns the specified experiment.

    :param experiment: experiment name or index
    :type experiment: int or str or COPASI.CExperiment

    :param kwargs:

    - | `model`: to specify the data model to be used (if not specified
      | the one from :func:`.get_current_model` will be taken)

    :return: the experiment or an error if none existent
    """
    if not isinstance(experiment, COPASI.CExperiment):
        model = kwargs.get('model', model_io.get_current_model())
        assert (isinstance(model, COPASI.CDataModel))

        task = model.getTask(TASK_PARAMETER_ESTIMATION)
        assert (isinstance(task, COPASI.CFitTask))

        problem = task.getProblem()
        assert (isinstance(problem, COPASI.CFitProblem))
        exp_set = problem.getExperimentSet()

        if type(experiment) is int and experiment >= exp_set.size():
            raise ValueError('Experiment index out of bounds')
        exp = exp_set.getExperiment(experiment)
        if exp is not None:
            experiment = exp
        else:
            raise ValueError('No experiment for: {0}'.format(experiment))
    return experiment
示例#7
0
def set_fit_parameters(fit_parameters, model=None):
    """Replaces all existing fit items with the ones provided

    :param fit_parameters: the fit parameters as pandas data frame of list of dictionaries with keys:

           * 'name' str: the display name of the model element to map the column to.
           * 'lower': the lower bound of the parameter
           * 'upper': the upper bound of the parameter
           * 'start' (float, optional): the start value
           * 'cn' (str, optional): internal identifier

    :type fit_parameters: pandas.DataFrame or [{}]
    :param model: the model or None
    :type model: COPASI.CDataModel or None
    :return: None
    """
    # type: (pandas.DataFrame, COPASI.CDataModel)
    if model is None:
        model = model_io.get_current_model()

    if type(fit_parameters) is list:
        fit_parameters = pandas.DataFrame(data=fit_parameters)

    pe_task = model.getTask(TASK_PARAMETER_ESTIMATION)
    problem = pe_task.getProblem()
    assert (isinstance(problem, COPASI.CFitProblem))
    while problem.getOptItemSize() > 0:
        problem.removeOptItem(0)

    for i in range(len(fit_parameters)):
        item = fit_parameters.iloc[i]
        cn = None
        name = None

        if 'cn' in item:
            cn = COPASI.CCommonName(item.cn)

        if 'name' in item:
            name = item['name']
            if not cn:
                obj = model.findObjectByDisplayName(name)
                if obj:
                    cn = obj.getCN()
                    if _get_role_for_reference(
                            obj.getObjectName()) == COPASI.CExperiment.ignore:
                        cn = obj.getValueReference().getCN()

        if not cn:
            logging.warning('object {0} not found'.format(name))
            continue

        fit_item = problem.addFitItem(cn)
        assert (isinstance(fit_item, COPASI.CFitItem))
        if 'lower' in item:
            fit_item.setLowerBound(COPASI.CCommonName(str(item['lower'])))
        if 'upper' in item:
            fit_item.setUpperBound(COPASI.CCommonName(str(item['upper'])))
        if 'start' in item:
            fit_item.setStartValue(float(item['start']))
示例#8
0
def set_opt_parameters(opt_parameters, model=None):
    """Replaces all existing opt items with the ones provided

    :param opt_parameters: the optimization parameters as pandas data frame of list of dictionaries with keys:

           * 'name' str: the display name of the model element to map the column to.
           * 'lower': the lower bound of the parameter
           * 'upper': the upper bound of the parameter
           * 'start' (float, optional): the start value
           * 'cn' (str, optional): internal identifier

    :type opt_parameters: pandas.DataFrame or [{}]
    :param model: the model or None
    :type model: COPASI.CDataModel or None
    :return: None
    """
    # type: (pandas.DataFrame, COPASI.CDataModel)
    if model is None:
        model = model_io.get_current_model()

    if type(opt_parameters) is list:
        opt_parameters = pandas.DataFrame(data=opt_parameters)

    task = model.getTask(basico.T.OPTIMIZATION)
    problem = task.getProblem()
    assert (isinstance(problem, COPASI.COptProblem))
    while problem.getOptItemSize() > 0:
        problem.removeOptItem(0)

    for i in range(len(opt_parameters)):
        item = opt_parameters.iloc[i]
        cn = None
        name = None

        if 'cn' in item:
            cn = COPASI.CCommonName(item.cn)

        if 'name' in item:
            name = item['name']
            if not cn:
                obj = model.findObjectByDisplayName(name)
                if obj:
                    if 'Reference' not in obj.getObjectType():
                        cn = obj.getInitialValueReference().getCN()
                    else:
                        cn = obj.getCN()

        if not cn:
            logging.warning('object {0} not found'.format(name))
            continue

        opt_item = problem.addOptItem(cn)
        assert (isinstance(opt_item, COPASI.COptItem))
        if 'lower' in item:
            opt_item.setLowerBound(COPASI.CCommonName(str(item['lower'])))
        if 'upper' in item:
            opt_item.setUpperBound(COPASI.CCommonName(str(item['upper'])))
        if 'start' in item:
            opt_item.setStartValue(float(item['start']))
示例#9
0
def get_fit_item_template(include_local=False,
                          include_global=False,
                          default_lb=0.001,
                          default_ub=1000,
                          model=None):
    """Returns a template list of items to be used for the parameter estimation

    :param include_local: boolean, indicating whether to include local parameters
    :type include_local: bool

    :param include_global:  boolean indicating whether to include global parameters
    :type include_global: bool

    :param default_lb: default lower bound to be used
    :type default_lb: float

    :param default_ub: default upper bound to be used
    :type default_ub: float

    :param model: the model or None
    :type model: COPASI.CDataModel or None

    :return: List of dictionaries, with the local / global parameters in the format needed by:
             :func:`set_fit_parameters`.
    :rtype: [{}]
    """

    if model is None:
        model = model_io.get_current_model()

    result = []

    if include_global:

        for mv in model.getModel().getModelValues():
            result.append({
                'name': mv.getObjectDisplayName(),
                'lower': default_lb,
                'upper': default_ub
            })

    if include_local:

        from . import model_info
        local_params = model_info.get_reaction_parameters().reset_index()
        for name, local in zip(local_params['name'], local_params['type']):

            if local == 'local':
                result.append({
                    'name': name,
                    'lower': default_lb,
                    'upper': default_ub
                })

    return result
def num_experiment_files(**kwargs):
    model = kwargs.get('model', model_io.get_current_model())
    assert (isinstance(model, COPASI.CDataModel))

    task = model.getTask("Parameter Estimation")
    assert (isinstance(task, COPASI.CFitTask))

    problem = task.getProblem()
    assert (isinstance(problem, COPASI.CFitProblem))

    return problem.getExperimentSet().size()
示例#11
0
def _get_experiment_keys(**kwargs):
    model = kwargs.get('model', model_io.get_current_model())
    assert (isinstance(model, COPASI.CDataModel))

    task = model.getTask(TASK_PARAMETER_ESTIMATION)
    assert (isinstance(task, COPASI.CFitTask))

    problem = task.getProblem()
    assert (isinstance(problem, COPASI.CFitProblem))

    result = []
    for i in range(problem.getExperimentSet().size()):
        experiment = problem.getExperimentSet().getExperiment(i)
        result.append(experiment.getKey())
    return result
示例#12
0
def get_parameters_solution(model=None):
    """Returns the solution found for the fit parameters as data frame

    The resulting data frame will have the columns:

    * `name`: the name of the parameter
    * `lower`: the parameters lower bound
    * `upper`: the parameters upper bound
    * `sol`: the solution found in the last run (or NaN, if not run yet, or no solution found)
    * `affected`: the experiments this parameter applies to (or an empty list if it applies to all)

    :param model: the model to use, or None
    :type model: COPASI.CDataModel or None
    :return: data frame as described
    :rtype: pandas.DataFrame
    """
    if model is None:
        model = model_io.get_current_model()
    pe_task = model.getTask(TASK_PARAMETER_ESTIMATION)
    problem = pe_task.getProblem()
    assert (isinstance(problem, COPASI.CFitProblem))
    solution = problem.getSolutionVariables()
    items = problem.getOptItemList()
    assert (solution.size() == len(items))
    data = []

    for i in range(solution.size()):
        item = items[i]
        sol = solution.get(i)
        obj = model.getObject(COPASI.CCommonName(item.getObjectCN()))
        if obj is None:
            logging.debug('fit item not in model, cn: {0}'.format(
                item.getObjectCN()))
            continue
        obj = obj.toObject().getObjectParent()
        name = obj.getObjectDisplayName()
        data.append({
            'name': name,
            'lower': item.getLowerBound(),
            'upper': item.getUpperBound(),
            'sol': sol,
            'affected': _get_affected_experiments(item),
        })

    if not data:
        return pandas.DataFrame()

    return pandas.DataFrame(data=data).set_index('name')
示例#13
0
def get_fit_parameters(model=None):
    """Returns a data frame with all fit parameters

    The resulting dataframe will have the following columns:

    * `name`: the name of the fit parameter
    * `lower`: the lower bound of the parameter
    * `upper`: the upper bound of the parameter
    * `start`: the start value
    * | `affected`: a list of all experiments (names) the fit parameter should apply to. If empty the parameter should
      | be varied for all experiments.
    * `cn`: internal identifier

    :param model: the model to get the fit parameters from
    :type model: COPASI.CDataModel or None

    :return: data frame with the fit parameters
    :rtype: pandas.DataFrame
    """
    if model is None:
        model = model_io.get_current_model()

    pe_task = model.getTask(TASK_PARAMETER_ESTIMATION)
    problem = pe_task.getProblem()
    assert (isinstance(problem, COPASI.CFitProblem))
    items = problem.getOptItemList()
    data = []

    for i in range(len(items)):
        item = items[i]
        obj = model.getObject(COPASI.CCommonName(
            item.getObjectCN())).toObject().getObjectParent()
        name = obj.getObjectDisplayName()
        data.append({
            'name': name,
            'lower': item.getLowerBound(),
            'upper': item.getUpperBound(),
            'start': item.getStartValue(),
            'affected': _get_affected_experiments(item),
            'cn': item.getObjectCN(),
        })

    if not data:
        return None

    return pandas.DataFrame(data=data).set_index('name')
示例#14
0
def get_opt_solution(model=None):
    """Returns the solution found for the optimization parameters as data frame

    The resulting data frame will have the columns:

    * `name`: the name of the parameter
    * `lower`: the parameters lower bound
    * `upper`: the parameters upper bound
    * `sol`: the solution found in the last run (or NaN, if not run yet, or no solution found)

    :param model: the model to use, or None
    :type model: COPASI.CDataModel or None
    :return: data frame as described
    :rtype: pandas.DataFrame
    """
    if model is None:
        model = model_io.get_current_model()
    task = model.getTask(basico.T.OPTIMIZATION)
    problem = task.getProblem()
    assert (isinstance(problem, COPASI.COptProblem))
    solution = problem.getSolutionVariables()
    items = problem.getOptItemList()
    assert (solution.size() == len(items))
    data = []

    for i in range(solution.size()):
        item = items[i]
        sol = solution.get(i)
        obj = model.getObject(COPASI.CCommonName(item.getObjectCN()))
        if obj is None:
            logging.debug('opt item not in model, cn: {0}'.format(
                item.getObjectCN()))
            continue
        obj = obj.toObject().getObjectParent()
        name = obj.getObjectDisplayName()
        data.append({
            'name': name,
            'lower': item.getLowerBound(),
            'upper': item.getUpperBound(),
            'sol': sol,
        })

    if not data:
        return pandas.DataFrame()

    return pandas.DataFrame(data=data).set_index('name')
示例#15
0
def get_opt_parameters(model=None):
    """Returns a data frame with all parameters to be varied during optimization

    The resulting dataframe will have the following columns:

    * `name`: the name of the fit parameter
    * `lower`: the lower bound of the parameter
    * `upper`: the upper bound of the parameter
    * `start`: the start value
    * `cn`: internal identifier

    :param model: the model to get the optitems from
    :type model: COPASI.CDataModel or None

    :return: data frame with the fit parameters
    :rtype: pandas.DataFrame
    """
    if model is None:
        model = model_io.get_current_model()

    pe_task = model.getTask(basico.T.OPTIMIZATION)
    problem = pe_task.getProblem()
    assert (isinstance(problem, COPASI.COptProblem))
    items = problem.getOptItemList()
    data = []

    for i in range(len(items)):
        item = items[i]
        obj = model.getObject(COPASI.CCommonName(
            item.getObjectCN())).toObject().getObjectParent()
        name = obj.getObjectDisplayName()
        data.append({
            'name': name,
            'lower': item.getLowerBound(),
            'upper': item.getUpperBound(),
            'start': item.getStartValue(),
            'cn': item.getObjectCN(),
        })

    if not data:
        return None

    return pandas.DataFrame(data=data).set_index('name')
示例#16
0
def num_experiment_files(**kwargs):
    """Return the number of experiment files defined.

    :param kwargs:

    - | `model`: to specify the data model to be used (if not specified
      | the one from :func:`.get_current_model` will be taken)

    :return: number of experiment files
    :rtype: int
    """
    model = kwargs.get('model', model_io.get_current_model())
    assert (isinstance(model, COPASI.CDataModel))

    task = model.getTask(TASK_PARAMETER_ESTIMATION)
    assert (isinstance(task, COPASI.CFitTask))

    problem = task.getProblem()
    assert (isinstance(problem, COPASI.CFitProblem))

    return problem.getExperimentSet().size()
示例#17
0
def set_opt_settings(settings, model=None):
    """Changes the optimization setup

    :param settings: a dictionary as returned by :func:`.get_opt_parameters`
    :param model: the model to be used, nor None
    :return:
    """
    if model is None:
        model = model_io.get_current_model()

    basico.set_task_settings(basico.T.OPTIMIZATION, settings, model=model)

    task = model.getTask(basico.T.OPTIMIZATION)
    assert (isinstance(task, COPASI.COptTask))
    problem = task.getProblem()
    assert (isinstance(problem, COPASI.COptProblem))

    if 'expression' in settings:
        set_objective_function(settings['expression'], model=model)

    if 'subtask' in settings:
        problem.setSubtaskType(basico.T.to_enum(settings['subtask']))
示例#18
0
def get_opt_settings(model=None, basic_only=True):
    """Returns a dictionary with the optimization setup

       The result int dictionary includes the objective function, and the subtask.

    :param model: the model or None for the current one
    :param basic_only: boolean flag indicating whether only basic settings should be returned
    :type basic_only: bool
    :return: dictionary with settings
    """
    if model is None:
        model = model_io.get_current_model()

    task = model.getTask(basico.T.OPTIMIZATION)
    assert (isinstance(task, COPASI.COptTask))
    problem = task.getProblem()
    assert (isinstance(problem, COPASI.COptProblem))

    settings = basico.get_task_settings(basico.T.OPTIMIZATION,
                                        model=model,
                                        basic_only=basic_only)
    settings['expression'] = basico.model_info._replace_cns_with_names(
        problem.getObjectiveFunction(), model=model)

    subtype = problem.getSubtaskType()
    if subtype == 15:
        st = model.getObject(problem.getParameter('Subtask').getCNValue())
        if st:
            subtask = st.getObjectName()
        else:
            subtask = basico.T.STEADY_STATE
    else:
        subtask = basico.T.from_enum(subtype)

    settings['subtask'] = subtask

    return settings
示例#19
0
def add_experiment(name, data, **kwargs):
    """Adds a new experiment to the model.

    This method adds a new experiment file to the parameter estimation task. The provided
    data frame will be written into the current directory as `experiment_name.txt` unless a filename
    has been provided.

    The mapping between the columns and the model elements should be done by having the columns of the data
    frame be model element names in question. So for example `[A]` to note that the transient concentrations
    of a species `A` is to be mapped as dependent variable. or `[A]_0` to note that the initial concentration of
    a species `A` is to be mapped as independent variable.

    :param name: the name of the experiment
    :type name: str
    :param data: the data frame with the experimental data
    :type data: pandas.DataFrame
    :param kwargs:

    - | `model`: to specify the data model to be used (if not specified
      | the one from :func:`.get_current_model` will be taken)

    - | `file_name` (str): the file name to save the experimental data to (otherwise it will be name.txt)

    :return: the filename of the generated data file
    :rtype: str
    """
    model = kwargs.get('model', model_io.get_current_model())
    assert (isinstance(model, COPASI.CDataModel))
    task = model.getTask(TASK_PARAMETER_ESTIMATION)
    assert (isinstance(task, COPASI.CFitTask))
    problem = task.getProblem()
    assert (isinstance(problem, COPASI.CFitProblem))
    exp_set = problem.getExperimentSet()
    assert (isinstance(exp_set, COPASI.CExperimentSet))
    exp = exp_set.getExperiment(name)
    if exp is not None:
        logging.error(
            'An experiment with the name {0} already exists'.format(name))
        return None

    # save data as tsv

    file_name = os.path.abspath(os.path.join(os.path.curdir, name + '.txt'))
    if 'file_name' in kwargs:
        file_name = kwargs['file_name']

    assert (isinstance(data, pd.DataFrame))
    data.to_csv(file_name, sep='\t', header=True, index=False)
    # create experiment

    exp = COPASI.CExperiment(model)
    exp = exp_set.addExperiment(exp)
    info = COPASI.CExperimentFileInfo(exp_set)
    info.setFileName(file_name)
    info.sync()
    exp.setObjectName(name)
    exp.setFileName(file_name)
    exp.setHeaderRow(1)
    exp.setFirstRow(1)
    exp.setLastRow(len(data) + 1)

    columns = data.columns.to_list()
    if 'time' in [col.lower() for col in columns]:
        exp.setExperimentType(COPASI.CTaskEnum.Task_timeCourse)
    else:
        exp.setExperimentType(COPASI.CTaskEnum.Task_steadyState)

    obj_map = exp.getObjectMap()
    num_cols = len(columns)
    obj_map.setNumCols(num_cols)
    for i in range(num_cols):
        role = COPASI.CExperiment.ignore
        current = columns[i]
        if current.lower() == 'time':
            role = COPASI.CExperiment.time
        else:
            obj = model.findObjectByDisplayName(current)
            if obj is None:
                logging.warning(
                    "Can't find model element for {0}".format(current))
            else:
                role = _get_role_for_reference(obj.getObjectName())
                obj_map.setObjectCN(i, obj.getCN())
        obj_map.setRole(i, role)

    exp.calculateWeights()
    exp_set.compile(model.getModel().getMathContainer())

    return file_name
示例#20
0
def run_parameter_estimation(**kwargs):
    """Runs the parameter estimation task as specified:

    The following are valid methods to be used for the parameter estimation task.

        Current Solution:

            * `Current Solution Statistics`,

        Global Methods:

            * `Random Search`,
            * `Simulated Annealing`,
            * `Differential Evolution`,
            * `Scatter Search`,
            * `Genetic Algorithm`,
            * `Evolutionary Programming`,
            * `Genetic Algorithm SR`,
            * `Evolution Strategy (SRES)`,
            * `Particle Swarm`,

        Local Methods:

            * `Levenberg - Marquardt`,
            * `Hooke & Jeeves`,
            * `Nelder - Mead`,
            * `Steepest Descent`,
            * `NL2SOL`,
            * `Praxis`,
            * `Truncated Newton`,

    :param kwargs:

    - | `model`: to specify the data model to be used (if not specified
      | the one from :func:`.get_current_model` will be taken)

    - | `method` (str): one of the strings from above

    - | `randomize_start_values` (bool): if true, parameters will be randomized before starting otherwise the
      | parameters starting value will be taken.

    - | `calculate_statistics` (bool): if true, the statistics will be calculated at the end of the task

    - | `create_parametersets` (bool): if true, parameter sets will be created for all experiments

    - `use_initial_values` (bool): whether to use initial values

    - `scheduled` (bool): sets whether the task is scheduled or not

    - `update_model` (bool): sets whether the model should be updated, or reset to initial conditions.

    :return: the solution for the fit parameters see :func:`get_get_parameters_solution`.
    :rtype: pandas.DataFrame
    """
    model = kwargs.get('model', model_io.get_current_model())
    assert (isinstance(model, COPASI.CDataModel))

    task = model.getTask(TASK_PARAMETER_ESTIMATION)
    assert (isinstance(task, COPASI.CFitTask))

    if 'scheduled' in kwargs:
        task.setScheduled(kwargs['scheduled'])

    if 'update_model' in kwargs:
        task.setUpdateModel(kwargs['update_model'])

    problem = task.getProblem()
    assert (isinstance(problem, COPASI.CFitProblem))

    old_create_parameter_sets = problem.getCreateParameterSets()
    # old_calculate_statistics = problem.getCalculateStatistics()
    # old_randomize_start_values = problem.getRandomizeStartValues()

    problem.setCreateParameterSets(True)

    if 'method' in kwargs:
        method = kwargs['method']
        if isinstance(method, int):
            task.setMethodType(method)
        else:
            task.setMethodType(COPASI.CCopasiMethod_TypeNameToEnum(method))

    if 'randomize_start_values' in kwargs:
        problem.setRandomizeStartValues(bool(kwargs['randomize_start_values']))

    if 'calculate_statistics' in kwargs:
        problem.setCalculateStatistics(bool(kwargs['calculate_statistics']))

    if 'create_parametersets' in kwargs:
        problem.setCreateParameterSets(bool(kwargs['create_parametersets']))

    use_initial_values = kwargs.get('use_initial_values', True)

    result = task.initializeRaw(COPASI.CCopasiTask.OUTPUT_UI)
    if not result:
        logging.error("Error while initializing the simulation: " +
                      COPASI.CCopasiMessage.getLastMessage().getText())
    else:
        result = task.processRaw(use_initial_values)
        if not result:
            logging.error("Error while running the simulation: " +
                          COPASI.CCopasiMessage.getLastMessage().getText())

    problem.setCreateParameterSets(old_create_parameter_sets)

    return get_parameters_solution(model)
示例#21
0
def get_simulation_results(**kwargs):
    """Runs the current solution statistics and returns result of simulation and experimental data

    :param kwargs:

    - | `model`: to specify the data model to be used (if not specified
      | the one from :func:`.get_current_model` will be taken)

    :return: tuple of lists of experiment data, and a list of simulation data
    :rtype: ([pandas.DataFrame],[pandas.DataFrame])
    """
    import basico
    dm = kwargs.get('model', model_io.get_current_model())

    task = dm.getTask(TASK_PARAMETER_ESTIMATION)
    assert (isinstance(task, COPASI.CFitTask))

    problem = task.getProblem()
    assert (isinstance(problem, COPASI.CFitProblem))

    experiments = problem.getExperimentSet()
    assert (isinstance(experiments, COPASI.CExperimentSet))

    result = []
    num_experiments = experiments.getExperimentCount()
    if num_experiments == 0:
        return result

    solution = run_parameter_estimation(method='Current Solution Statistics')

    model = dm.getModel()

    exp_data = []
    sim_data = []

    for i in range(num_experiments):
        change_set = COPASI.DataObjectSet()
        experiment = experiments.getExperiment(i)
        exp_name = experiment.getObjectName()
        df = get_data_from_experiment(experiment, rename_headers=True)
        mapping = get_experiment_mapping(experiment)

        # set independent values for that experiment
        independent = mapping[mapping.type == 'independent']
        num_independent = independent.shape[0]
        for j in range(num_independent):
            name = independent.iloc[j].mapping
            cn = independent.iloc[j].cn
            value = df.iloc[0][name]
            obj = dm.getObject(COPASI.CCommonName(cn))
            if obj is not None:
                if cn.endswith('InitialConcentration'):
                    obj.getObjectParent().setInitialConcentration(value)
                else:
                    obj.getObjectParent().setInitialValue(value)
                change_set.append(obj)

        if change_set.size() > 0:
            model.updateInitialValues(change_set)

        for j in range(solution.shape[0]):
            name = solution.iloc[j].name
            value = solution.iloc[j].sol
            if np.isnan(value):
                continue
            affected = solution.iloc[j].affected
            if any(affected) and exp_name not in affected:
                continue

            basico.set_reaction_parameters(name, value=value)

        duration = df.iloc[-1].Time
        data = basico.run_time_course(duration=duration)

        exp_data.append(df)
        sim_data.append(data)

    return exp_data, sim_data
示例#22
0
def plot_per_dependent_variable(**kwargs):
    """
    This function creates a figure for each dependent variable, with traces for all experiments.

    :param kwargs:

    - | `model`: to specify the data model to be used (if not specified
      | the one from :func:`.get_current_model` will be taken)

    :return: array of tuples (fig, ax) for each figure created
    """
    dm = kwargs.get('model', model_io.get_current_model())

    task = dm.getTask(TASK_PARAMETER_ESTIMATION)
    assert (isinstance(task, COPASI.CFitTask))

    problem = task.getProblem()
    assert (isinstance(problem, COPASI.CFitProblem))

    experiments = problem.getExperimentSet()
    assert (isinstance(experiments, COPASI.CExperimentSet))

    result = []
    num_experiments = experiments.getExperimentCount()
    if num_experiments == 0:
        return result

    exp_data, sim_data = get_simulation_results(**kwargs)

    dependent_variables = {}

    for i in range(num_experiments):
        experiment = experiments.getExperiment(i)
        mapping = get_experiment_mapping(experiment)

        # set independent values for that experiment
        dependent = mapping[mapping.type == 'dependent']
        num_dependent = dependent.shape[0]
        for j in range(num_dependent):
            name = dependent.iloc[j].mapping
            if name not in dependent_variables:
                dependent_variables[name] = []
            dependent_variables[name].append(i)

    for dependent in dependent_variables:
        fig, ax = plt.subplots()
        cycler = plt.cycler("color", plt.cm.tab20c.colors)()
        ax.set_title(dependent)
        experiment_indices = dependent_variables[dependent]

        for i in experiment_indices:
            experiment = experiments.getExperiment(i)
            exp_name = experiment.getObjectName()
            nextval = next(cycler)['color']
            name = dependent
            if name not in sim_data[i].columns:
                name = name[1:-1]

            sim_data[i].reset_index().plot(x='Time',
                                           y=name,
                                           label="{0} Fit".format(exp_name),
                                           ax=ax,
                                           color=nextval)
            exp_data[i].plot.scatter(x='Time',
                                     y=dependent,
                                     ax=ax,
                                     color=nextval,
                                     label='{0} Measured'.format(exp_name))
        result.append((fig, ax))

    return result