Example #1
0
 def test_simulate(self):
     dm = basico.load_example('LM')
     data = basico.get_experiment_data_from_model()
     self.assertTrue(len(data) == 5)
     df = basico.run_time_course(100, automatic=False)
     self.assertTrue(df.shape == (101, 5))
     basico.remove_datamodel(dm)
Example #2
0
    def __call__(self, par):
        """Calls the time course and returns the selected result. 

        sets the method to gibson bruck, automatic step size
        """
        self.apply_parameters(par)
        tc = basico.run_time_course(
            self.max_t,
            model=self.dm,
            method=self.method,
            automatic=True,
            use_seed=False,
            use_numbers=self.use_numbers).reset_index()
        return {"t": tc.Time.to_numpy(), "X": tc[self.output].to_numpy()}
Example #3
0
    def __call__(self, pars: Dict[str, float], return_raw: bool = False):
        """Simulate data for given parameters.

        Calls the time course and returns the selected result.
        """
        # apply parameters to model
        self.apply_parameters(pars)

        # parse time args by basico's logic
        if self.t0 is not None:
            args = self.t0, self.duration, self.num_steps
        elif self.num_steps is not None:
            args = self.duration, self.num_steps
        else:
            args = (self.duration, )

        # simulate
        tc = basico.run_time_course(
            *args,
            model=self.dm,
            method=self.method,
            automatic=self.automatic,
            use_seed=False,
            use_numbers=self.use_numbers,
        ).reset_index()

        if return_raw:
            return tc

        # cache output columns
        if self.output is None:
            self.output = list(set(tc.columns) - {"Time"})

        return {
            "t": tc.Time.to_numpy(),
            "X": tc[self.output].to_numpy(),
        }
def get_simulation_results(values_only=False, **kwargs):
    """Runs the current solution statistics and returns result of simulation and experimental data

    :param values_only: if true, only time points at the measurements will be returned
    :type values_only: bool

    :param kwargs:

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

    - | `solution`: a solution data frame to use, if not specified a current solution
                    statistic will be computed

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

    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

    if 'solution' in kwargs:
        solution = kwargs['solution']
    else:
        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)
        columns = df.columns.to_list()
        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

            if name not in columns:
                # independent value is not found in df
                continue

            value = df.iloc[0][name]
            obj = dm.getObject(COPASI.CCommonName(cn))

            if obj is None:  # not found skip
                logging.debug(
                    'independent object not found for cn: {0}'.format(cn))
                continue

            if obj.getObjectName() == 'InitialConcentration':
                obj.getObjectParent().setInitialConcentration(value)
            else:
                obj.getObjectParent().setInitialValue(value)

            change_set.append(obj)
            logging.debug('set independent "{0}" to "{1}"'.format(cn, value))

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

        _update_fit_parameters_from(dm, solution, exp_name)

        if experiment.getExperimentType() == COPASI.CTaskEnum.Task_steadyState:
            # run steady state
            basico.run_steadystate(model=dm)
            data = basico.model_info._collect_data(cns=mapping[
                mapping.type == 'dependent']['cn'].to_list()).transpose()
        else:
            # run time course
            duration = df.iloc[-1].Time
            if values_only:
                data = basico.run_time_course(values=df.Time.to_list(),
                                              start_time=df.iloc[0].Time)
            else:
                data = basico.run_time_course(duration=duration)

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

    return exp_data, sim_data
Example #5
0
 def test_timecourse(self):
     data = basico.run_time_course()
     self.assertTrue(data.shape[1] == 2)
     basico.set_model_unit(substance_unit=1)
     data_stoch = basico.run_time_course(method='stochastic')
     self.assertTrue(data_stoch.shape[1] == 2)
Example #6
0
 def test_simulation(self):
     result = basico.run_time_course(duration=10)
     self.assertIsNotNone(result)
     result2 = basico.run_time_course_with_output(
         output_selection=['Time', '[X]', 'Y'], duration=10)
     self.assertIsNotNone(result2)
Example #7
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