示例#1
0
def pysb_example_presimulation_module():
    """PySB example_presimulation model module fixture"""

    constant_parameters = ['DRUG_0', 'KIN_0']

    pysb.SelfExporter.cleanup()  # reset pysb
    pysb.SelfExporter.do_export = True

    model_path = os.path.join(os.path.dirname(__file__), '..',
                              'examples', 'example_presimulation')

    with amici.add_path(model_path):
        if 'createModelPresimulation' in sys.modules:
            importlib.reload(sys.modules['createModelPresimulation'])
            model_module = sys.modules['createModelPresimulation']
        else:
            model_module = importlib.import_module('createModelPresimulation')
    model = copy.deepcopy(model_module.model)

    model.name = 'test_model_presimulation_pysb'
    outdir = model.name
    pysb2amici(model, outdir, verbose=True,
               observables=['pPROT_obs'],
               constant_parameters=constant_parameters)

    with amici.add_path(outdir):
        model_module_pysb = importlib.import_module(outdir)

    yield model_module_pysb

    shutil.rmtree(outdir, ignore_errors=True)
示例#2
0
def test_compare_to_pysb_simulation(example):
    pysb = pytest.importorskip("pysb")

    atol = 1e-8
    rtol = 1e-8

    with amici.add_path(os.path.dirname(pysb.examples.__file__)):
        with amici.add_path(
                os.path.join(os.path.dirname(__file__), '..', 'tests',
                             'pysb_test_models')):

            if example == 'earm_1_3' \
                    and platform.sys.version_info[0] == 3 \
                    and platform.sys.version_info[1] < 7:
                return

            # load example

            pysb.SelfExporter.cleanup()  # reset pysb
            pysb.SelfExporter.do_export = True

            module = importlib.import_module(example)
            pysb_model = module.model
            pysb_model.name = pysb_model.name.replace('pysb.examples.', '')
            # avoid naming clash for custom pysb models
            pysb_model.name += '_amici'

            # pysb part

            tspan = np.linspace(0, 100, 101)
            sim = ScipyOdeSimulator(pysb_model,
                                    tspan=tspan,
                                    integrator_options={
                                        'rtol': rtol,
                                        'atol': atol
                                    },
                                    compiler='python')
            pysb_simres = sim.run()

            # amici part

            outdir = pysb_model.name

            if pysb_model.name in ['move_connected_amici']:
                with pytest.raises(Exception):
                    pysb2amici(pysb_model,
                               outdir,
                               verbose=logging.INFO,
                               compute_conservation_laws=True)
                compute_conservation_laws = False
            else:
                compute_conservation_laws = True

            pysb2amici(pysb_model,
                       outdir,
                       verbose=logging.INFO,
                       compute_conservation_laws=compute_conservation_laws)
            sys.path.insert(0, outdir)

            amici_model_module = importlib.import_module(pysb_model.name)

            model_pysb = amici_model_module.getModel()

            model_pysb.setTimepoints(tspan)

            solver = model_pysb.getSolver()
            solver.setMaxSteps(int(1e5))
            solver.setAbsoluteTolerance(atol)
            solver.setRelativeTolerance(rtol)
            rdata = amici.runAmiciSimulation(model_pysb, solver)

            # check agreement of species simulation

            assert np.isclose(rdata['x'], pysb_simres.species, 1e-4,
                              1e-4).all()

            shutil.rmtree(outdir, ignore_errors=True)
示例#3
0
def test_compare_to_pysb_simulation(example):
    pysb = pytest.importorskip("pysb")

    atol = 1e-8
    rtol = 1e-8

    with amici.add_path(os.path.dirname(pysb.examples.__file__)):
        with amici.add_path(
                os.path.join(os.path.dirname(__file__), '..', 'tests',
                             'pysb_test_models')):

            if example == 'earm_1_3' \
                    and platform.sys.version_info[0] == 3 \
                    and platform.sys.version_info[1] < 7:
                return

            # load example
            pysb.SelfExporter.cleanup()  # reset pysb
            pysb.SelfExporter.do_export = True

            module = importlib.import_module(example)
            pysb_model = module.model
            pysb_model.name = pysb_model.name.replace('pysb.examples.', '')
            # avoid naming clash for custom pysb models
            pysb_model.name += '_amici'

            # pysb part
            tspan = np.linspace(0, 100, 101)
            sim = ScipyOdeSimulator(pysb_model,
                                    tspan=tspan,
                                    integrator_options={
                                        'rtol': rtol,
                                        'atol': atol
                                    },
                                    compiler='python')
            pysb_simres = sim.run()

            # amici part

            outdir = pysb_model.name

            if pysb_model.name in ['move_connected_amici']:
                with pytest.raises(Exception):
                    pysb2amici(pysb_model,
                               outdir,
                               verbose=logging.INFO,
                               compute_conservation_laws=True)
                compute_conservation_laws = False
            else:
                compute_conservation_laws = True

            pysb2amici(pysb_model,
                       outdir,
                       verbose=logging.INFO,
                       compute_conservation_laws=compute_conservation_laws,
                       observables=list(pysb_model.observables.keys()))

            amici_model_module = amici.import_model_module(
                pysb_model.name, outdir)

            model_pysb = amici_model_module.getModel()

            model_pysb.setTimepoints(tspan)

            solver = model_pysb.getSolver()
            solver.setMaxSteps(int(1e6))
            solver.setAbsoluteTolerance(atol)
            solver.setRelativeTolerance(rtol)
            rdata = amici.runAmiciSimulation(model_pysb, solver)

            # check agreement of species simulation

            assert np.isclose(rdata['x'], pysb_simres.species, 1e-4,
                              1e-4).all()

            if example not in [
                    'fricker_2010_apoptosis', 'fixed_initial',
                    'bngwiki_egfr_simple_deletemolecules'
            ]:
                if example in [
                        'tyson_oscillator', 'bax_pore_sequential', 'bax_pore',
                        'kinase_cascade', 'bngwiki_egfr_simple',
                        'bngwiki_enzymatic_cycle_mm', 'bngwiki_simple'
                ]:
                    solver.setAbsoluteTolerance(1e-14)
                    solver.setRelativeTolerance(1e-14)
                    epsilon = 1e-4
                else:
                    solver.setAbsoluteTolerance(1e-10)
                    solver.setRelativeTolerance(1e-10)
                    epsilon = 1e-3
                model_pysb.setParameterScale(
                    parameterScalingFromIntVector([
                        ParameterScaling.log10
                        if p > 0 else ParameterScaling.none
                        for p in model_pysb.getParameters()
                    ]))
                check_derivatives(model_pysb,
                                  solver,
                                  epsilon=epsilon,
                                  rtol=1e-2,
                                  atol=1e-2,
                                  skip_zero_pars=True)

            shutil.rmtree(outdir, ignore_errors=True)
示例#4
0
def import_model_pysb(
        petab_problem: PysbPetabProblem,
        model_output_dir: Optional[str] = None,
        verbose: Optional[Union[bool, int]] = True,
        **kwargs
) -> None:
    """
    Create AMICI model from PySB-PEtab problem

    :param petab_problem:
        PySB PEtab problem

    :param model_output_dir:
        Directory to write the model code to. Will be created if doesn't
        exist. Defaults to current directory.

    :param verbose:
        Print/log extra information.

    :param kwargs:
        Additional keyword arguments to be passed to
        :meth:`amici.pysb_import.pysb2amici`.
    """

    set_log_level(logger, verbose)

    logger.info(f"Importing model ...")

    observable_table = petab_problem.observable_df
    pysb_model = petab_problem.pysb_model

    # For pysb, we only allow parameters in the condition table
    # those must be pysb model parameters (either natively, or output
    # parameters from measurement or condition table that have been added in
    # PysbPetabProblem
    model_parameters = [p.name for p in pysb_model.parameters]
    for x in petab_problem.condition_df.columns:
        if x == CONDITION_NAME:
            continue

        if x not in model_parameters:
            raise NotImplementedError(
                "For PySB PEtab import, only model parameters, but no states "
                "or compartments are allowed in the condition table."
                f"Offending column: {x}"
            )

    constant_parameters = petab_import.get_fixed_parameters(
        petab_problem.sbml_model, petab_problem.condition_df)

    if observable_table is None:
        observables = None
        sigmas = None
    else:
        observables = [expr.name for expr in pysb_model.expressions
                       if expr.name in observable_table.index]

        sigmas = {obs_id: f"{obs_id}_sigma" for obs_id in observables}

    from amici.pysb_import import pysb2amici
    pysb2amici(pysb_model, model_output_dir, verbose=True,
               observables=observables,
               sigmas=sigmas,
               constant_parameters=constant_parameters,
               **kwargs)
示例#5
0
    def __init__(self,
                 model,
                 tspan=None,
                 initials=None,
                 param_values=None,
                 verbose=False,
                 **kwargs):

        if amici is None:
            raise ImportError('AmiciSimulator requires a working installation'
                              'of amici. You can install amici via `pip '
                              'install amici`.')

        super(AmiciSimulator, self).__init__(model,
                                             tspan=tspan,
                                             initials=initials,
                                             param_values=param_values,
                                             verbose=verbose,
                                             **kwargs)

        self.modeldir_is_temp = 'modeldir' not in kwargs
        self.modeldir = kwargs.pop('modeldir',
                                   mkdtemp(prefix=f'pysbamici_{model.name}_'))
        force_recompile = kwargs.pop('force_recompile', False)

        if kwargs:
            raise ValueError('Unknown keyword argument(s): {}'.format(
                ', '.join(kwargs.keys())))

        # Generate the equations for the model
        if force_recompile or not os.path.exists(
                os.path.join(self.modeldir, model.name, '__init__.py')):
            if not force_recompile and not self.modeldir_is_temp and \
                    os.path.exists(os.path.join(self.modeldir)):
                raise RuntimeError('Model directory already exists. Stopping '
                                   'to prevent data loss. To ignore this '
                                   'warning, pass `force_recompile=True`')

            pysb2amici(model,
                       self.modeldir,
                       verbose=False,
                       observables=[],
                       constant_parameters=[],
                       compute_conservation_laws=True)
            mode = 'compilation'
            help = 'file an issue at https://github.com/ICB-DCM/AMICI/issues.'
        else:
            pysb.bng.generate_equations(model)
            mode = 'loading'
            help = 'try recompiling the model by passing ' \
                   '`force_recompile=True`.'

        # Load the generated model package
        sys.path.insert(0, self.modeldir)
        try:
            modelModulePYSB = importlib.import_module(model.name)
        except Exception as e:
            raise RuntimeError(f'Model {mode} failed. Please {help}')

        self._model = model
        self.amici_model = modelModulePYSB.getModel()
        self.amici_solver = self.amici_model.getSolver()
        self.amici_model.setTimepoints(tspan if tspan is not None else [])
示例#6
0
                                         'sim': sim
                                     }).timeit(number=N_REPEATS) / N_REPEATS

            simulation_times[example]['pysb'] = time_pysb
            print(f'PySB average simulation time {example}: {time_pysb}')

            # amici part
            outdir = pysb_model.name

            if pysb_model.name in ['move_connected_amici']:
                compute_conservation_laws = False
            else:
                compute_conservation_laws = True

            pysb2amici(pysb_model,
                       outdir,
                       compute_conservation_laws=compute_conservation_laws,
                       observables=list(pysb_model.observables.keys()))

            amici_model_module = amici.import_model_module(
                pysb_model.name, outdir)

            model_pysb = amici_model_module.getModel()

            model_pysb.setTimepoints(tspan)

            solver = model_pysb.getSolver()
            solver.setMaxSteps(int(1e6))
            solver.setAbsoluteTolerance(atol)
            solver.setRelativeTolerance(rtol)
            time_amici = timeit.Timer(
                'rdata = amici.runAmiciSimulation(model, solver)',