def test_adjoint_pre_and_post_equilibration(edata_fixture): # get both models model_module = amici.import_model_module( 'model_constant_species', module_path=os.path.abspath('model_constant_species')) model = model_module.getModel() model_module_cl = amici.import_model_module( 'model_constant_species_cl', module_path=os.path.abspath('model_constant_species_cl')) model_cl = model_module_cl.getModel() # check gradient with and without state reinitialization for edata in edata_fixture: for reinit in [False, True]: # --- compare different ways of preequilibration, full rank Jacobian --------- # forward preequilibration, forward simulation rff_cl = get_results( model_cl, edata=edata, sensi_order=1, sensi_meth=amici.SensitivityMethod.forward, sensi_meth_preeq=amici.SensitivityMethod.forward, reinitialize_states=reinit) # forward preequilibration, adjoint simulation rfa_cl = get_results( model_cl, edata=edata, sensi_order=1, sensi_meth=amici.SensitivityMethod.adjoint, sensi_meth_preeq=amici.SensitivityMethod.forward, reinitialize_states=reinit) # adjoint preequilibration, adjoint simulation raa_cl = get_results( model_cl, edata=edata, sensi_order=1, sensi_meth=amici.SensitivityMethod.adjoint, sensi_meth_preeq=amici.SensitivityMethod.adjoint, reinitialize_states=reinit) # assert all are close assert np.isclose(rff_cl['sllh'], rfa_cl['sllh']).all() assert np.isclose(rfa_cl['sllh'], raa_cl['sllh']).all() assert np.isclose(raa_cl['sllh'], rff_cl['sllh']).all() # --- compare fully adjoint approach to simulation with singular Jacobian ---- raa = get_results(model, edata=edata, sensi_order=1, sensi_meth=amici.SensitivityMethod.adjoint, sensi_meth_preeq=amici.SensitivityMethod.adjoint, reinitialize_states=reinit) # assert gradients are close (quadrature tolerances are laxer) assert np.isclose(raa_cl['sllh'], raa['sllh'], 1e-5, 1e-5).all()
def generate_models(): # SBML model we want to import sbml_file = os.path.join(os.path.dirname(__file__), '..', 'examples', 'example_constant_species', 'model_constant_species.xml') sbml_importer = amici.SbmlImporter(sbml_file) # Name of the model that will also be the name of the python module model_name = model_output_dir = 'model_constant_species' model_name_cl = model_output_dir_cl = 'model_constant_species_cl' # Define constants, observables, sigmas constant_parameters = ['synthesis_substrate', 'init_enzyme'] observables = { 'observable_product': { 'name': '', 'formula': 'product' }, 'observable_substrate': { 'name': '', 'formula': 'substrate' }, } sigmas = {'observable_product': 1.0, 'observable_substrate': 1.0} # wrap models with and without conservations laws sbml_importer.sbml2amici(model_name_cl, model_output_dir_cl, observables=observables, constant_parameters=constant_parameters, sigmas=sigmas) sbml_importer.sbml2amici(model_name, model_output_dir, observables=observables, constant_parameters=constant_parameters, sigmas=sigmas, compute_conservation_laws=False) # load both models model_without_cl_module = amici.import_model_module( model_name, module_path=os.path.abspath(model_name)) model_with_cl_module = amici.import_model_module( model_name_cl, module_path=os.path.abspath(model_name_cl)) # get the models and return model_without_cl = model_without_cl_module.getModel() model_with_cl = model_with_cl_module.getModel() return model_with_cl, model_without_cl
def sbml_example_presimulation_module(): """SBML example_presimulation model module fixture""" sbml_file = os.path.join(os.path.dirname(__file__), '..', 'examples', 'example_presimulation', 'model_presimulation.xml') sbml_importer = amici.SbmlImporter(sbml_file) constant_parameters = ['DRUG_0', 'KIN_0'] observables = amici.assignmentRules2observables( sbml_importer.sbml, # the libsbml model object filter_function=lambda variable: variable.getName() == 'pPROT_obs' ) outdir = 'test_model_presimulation' module_name = 'test_model_presimulation' sbml_importer.sbml2amici( model_name=module_name, output_dir=outdir, verbose=False, observables=observables, constant_parameters=constant_parameters) model_module = amici.import_model_module(module_name=module_name, module_path=outdir) yield model_module shutil.rmtree(outdir, ignore_errors=True)
def main(): arg, suffix = parse_args() model_dir = os.path.join(os.curdir, 'CS_Signalling_ERBB_RAS_AKT', 'CS_Signalling_ERBB_RAS_AKT_petab' + suffix) model_name = 'CS_Signalling_ERBB_RAS_AKT_petab' if arg == 'import': run_import(model_name) return elif arg == 'compile': compile_model(model_name, model_dir) return else: model_module = amici.import_model_module(model_name, model_dir) model = model_module.getModel() solver = model.getSolver() # TODO edata = amici.ExpData(model) edata.setTimepoints([1e8]) edata.setObservedData([1.0]) edata.setObservedDataStdDev([1.0]) prepare_simulation(arg, model, solver, edata) rdata = amici.runAmiciSimulation(model, solver, edata) check_results(rdata)
def model_steadystate_module(): sbml_file = os.path.join(os.path.dirname(__file__), '..', 'examples', 'example_steadystate', 'model_steadystate_scaled.xml') sbml_importer = amici.SbmlImporter(sbml_file) observables = amici.assignmentRules2observables( sbml_importer.sbml, filter_function=lambda variable: variable.getId().startswith('observable_') and not variable.getId().endswith('_sigma') ) outdir = 'test_model_steadystate_scaled' module_name = 'test_model_steadystate_scaled' sbml_importer.sbml2amici( model_name=module_name, output_dir=outdir, observables=observables, constant_parameters=['k0'], sigmas={'observable_x1withsigma': 'observable_x1withsigma_sigma'}) model_module = amici.import_model_module(module_name=module_name, module_path=outdir) yield model_module shutil.rmtree(outdir, ignore_errors=True)
def _create_model(self) -> 'amici.Model': """Load model module and return the model, no checks/compilation.""" # load moduĺe module = amici.import_model_module(module_name=self.model_name, module_path=self.output_folder) model = module.getModel() return model
def model_units_module(): sbml_file = os.path.join(os.path.dirname(__file__), '..', 'examples', 'example_units', 'model_units.xml') sbml_importer = amici.SbmlImporter(sbml_file) outdir = 'test_model_units' module_name = 'test_model_units' sbml_importer.sbml2amici(model_name=module_name, output_dir=outdir) model_module = amici.import_model_module(module_name=module_name, module_path=outdir) yield model_module shutil.rmtree(outdir, ignore_errors=True)
def model_test_likelihoods(): sbml_file = os.path.join(os.path.dirname(__file__), '..', 'examples', 'example_steadystate', 'model_steadystate_scaled.xml') sbml_importer = amici.SbmlImporter(sbml_file) observables = amici.assignmentRules2observables( sbml_importer.sbml, filter_function=lambda variable: variable.getId().startswith('observable_') and not variable.getId().endswith('_sigma') ) # assign different noise models obs_keys = list(observables.keys()) # exponentiate observable formulas obs1 = observables[obs_keys[1]] obs3 = observables[obs_keys[3]] obs1['formula'] = '10^(' + obs1['formula'] + ')' obs3['formula'] = 'exp(' + obs3['formula'] + ')' # customize noise distributions noise_distributions = { obs_keys[0]: 'normal', obs_keys[1]: 'log-normal', obs_keys[2]: 'laplace', obs_keys[3]: 'log10-laplace', } module_name = 'test_likelihoods' outdir = 'test_likelihoods' sbml_importer.sbml2amici( model_name=module_name, output_dir=outdir, observables=observables, constant_parameters=['k0'], sigmas={'observable_x1withsigma': 'observable_x1withsigma_sigma'}, noise_distributions=noise_distributions ) yield amici.import_model_module(module_name=module_name, module_path=outdir) shutil.rmtree(outdir, ignore_errors=True)
def create_amici_model(sbml_model, model_name) -> AmiciModel: """ Import an sbml file and create an AMICI model from it """ sbml_test_models = Path('sbml_test_models') sbml_test_models_output_dir = sbml_test_models / 'amici_models' sbml_test_models_output_dir.mkdir(parents=True, exist_ok=True) sbml_importer = SbmlImporter(sbml_model) output_dir = sbml_test_models_output_dir / model_name sbml_importer.sbml2amici( model_name=model_name, output_dir=str(output_dir) ) model_module = import_model_module(model_name, str(output_dir.resolve())) model = model_module.getModel() return model
def test_sympy_exp_monkeypatch(): """ This model contains a removeable discontinuity at t=0 that requires monkeypatching sympy.Pow._eval_derivative in order to be able to compute non-nan sensitivities """ url = 'https://www.ebi.ac.uk/biomodels/model/download/BIOMD0000000529.2?' \ 'filename=BIOMD0000000529_url.xml' importer = amici.SbmlImporter(urlopen(url).read().decode('utf-8'), from_file=False) module_name = 'BIOMD0000000529' outdir = 'BIOMD0000000529' importer.sbml2amici(module_name, outdir) model_module = amici.import_model_module(module_name=module_name, module_path=outdir) model = model_module.getModel() model.setTimepoints(np.linspace(0, 8, 250)) model.requireSensitivitiesForAllParameters() model.setAlwaysCheckFinite(True) model.setParameterScale( amici.parameterScalingFromIntVector([ amici.ParameterScaling.none if re.match(r'n[0-9]+$', par_id) else amici.ParameterScaling.log10 for par_id in model.getParameterIds() ])) solver = model.getSolver() solver.setSensitivityMethod(amici.SensitivityMethod.forward) solver.setSensitivityOrder(amici.SensitivityOrder.first) rdata = amici.runAmiciSimulation(model, solver) # print sensitivity-related results assert rdata['status'] == amici.AMICI_SUCCESS check_derivatives(model, solver, None, assert_fun, atol=1e-2, rtol=1e-2, epsilon=1e-3)
def compile_model(path, test_id, model_dir): """Import the given test model to AMICI""" sbml_file = find_model_file(path, test_id) wrapper = amici.SbmlImporter(sbml_file) if not os.path.exists(model_dir): os.makedirs(model_dir) model_name = 'SBMLTest' + test_id wrapper.sbml2amici(model_name, output_dir=model_dir, generate_sensitivity_code=False) # settings model_module = amici.import_model_module(model_name, model_dir) model = model_module.getModel() solver = model.getSolver() return model, solver, wrapper
def load_model( pathway_name: str, force_compile: bool = True, add_observables: bool = False ) -> Tuple[amici.AmiciModel, amici.AmiciSolver]: model = load_pathway(pathway_name) outdir = os.path.join(basedir, 'amici_models', model.name) # extend observables if add_observables: for obs in model.observables: if re.match(r'[p|t][A-Z0-9]+[SYT0-9_]*', obs.name): offset = pysb.Parameter(obs.name + '_offset', 0.0) scale = pysb.Parameter(obs.name + '_scale', 1.0) pysb.Expression(obs.name + '_obs', sp.log(scale * (obs + offset))) if force_compile or not os.path.exists( os.path.join(outdir, model.name, model.name + '.py')): os.makedirs(outdir, exist_ok=True) amici.pysb_import.pysb2amici(model, outdir, verbose=logging.DEBUG, observables=[ expr.name for expr in model.expressions if expr.name.endswith('_obs') ], constant_parameters=[]) model_module = amici.import_model_module(model.name, outdir) amici_model = model_module.getModel() solver = amici_model.getSolver() solver.setMaxSteps(int(1e5)) solver.setAbsoluteToleranceSteadyState(1e-2) solver.setRelativeToleranceSteadyState(1e-8) return amici_model, solver
def model_test_likelihoods(): """Test model for various likelihood functions.""" # load sbml model sbml_file = os.path.join(os.path.dirname(__file__), '..', 'examples', 'example_steadystate', 'model_steadystate_scaled.xml') sbml_importer = amici.SbmlImporter(sbml_file) # define observables observables = { 'o1': {'formula': 'x1'}, 'o2': {'formula': '10^x1'}, 'o3': {'formula': '10^x1'}, 'o4': {'formula': 'x1'}, 'o5': {'formula': '10^x1'}, 'o6': {'formula': '10^x1'}, 'o7': {'formula': 'x1'} } # define different noise models noise_distributions = { 'o1': 'normal', 'o2': 'log-normal', 'o3': 'log10-normal', 'o4': 'laplace', 'o5': 'log-laplace', 'o6': 'log10-laplace', 'o7': lambda str_symbol: f'Abs({str_symbol} - m{str_symbol}) ' f'/ sigma{str_symbol}', } module_name = 'test_likelihoods' outdir = 'test_likelihoods' sbml_importer.sbml2amici( model_name=module_name, output_dir=outdir, observables=observables, constant_parameters=['k0'], noise_distributions=noise_distributions, ) yield amici.import_model_module(module_name=module_name, module_path=outdir) shutil.rmtree(outdir, ignore_errors=True)
def test_nosensi(simple_sbml_model): sbml_doc, sbml_model = simple_sbml_model sbml_importer = SbmlImporter(sbml_source=sbml_model, from_file=False) with TemporaryDirectory() as tmpdir: sbml_importer.sbml2amici(model_name="test", output_dir=tmpdir, observables=None, compute_conservation_laws=False, generate_sensitivity_code=False) model_module = amici.import_model_module(module_name='test', module_path=tmpdir) model = model_module.getModel() model.setTimepoints(np.linspace(0, 60, 61)) solver = model.getSolver() solver.setSensitivityOrder(amici.SensitivityOrder.first) solver.setSensitivityMethod(amici.SensitivityMethod.forward) rdata = amici.runAmiciSimulation(model, solver) assert rdata.status == amici.AMICI_ERROR
def model_special_likelihoods(): """Test model for special likelihood functions.""" # load sbml model sbml_file = os.path.join(os.path.dirname(__file__), '..', 'examples', 'example_steadystate', 'model_steadystate_scaled.xml') sbml_importer = amici.SbmlImporter(sbml_file) # define observables observables = { 'o1': { 'formula': '100*10^x1' }, 'o2': { 'formula': '100*10^x1' }, } # define different noise models noise_distributions = { 'o1': 'binomial', 'o2': 'negative-binomial', } module_name = 'test_special_likelihoods' outdir = 'test_special_likelihoods' sbml_importer.sbml2amici( model_name=module_name, output_dir=outdir, observables=observables, constant_parameters=['k0'], noise_distributions=noise_distributions, ) yield amici.import_model_module(module_name=module_name, module_path=outdir) shutil.rmtree(outdir, ignore_errors=True)
def conversion_reaction_model(): # read in sbml file model_name = 'conversion_reaction' example_dir = os.path.join(os.path.dirname(__file__), '..', '..', 'doc', 'example') sbml_file = os.path.join(example_dir, model_name, f'model_{model_name}.xml') model_output_dir = os.path.join(example_dir, 'tmp', f'{model_name}_enhanced') # try to import the exisiting model, if possible try: sys.path.insert(0, os.path.abspath(model_output_dir)) model_module = amici.import_model_module(model_name, model_output_dir) model = model_module.getModel() except ValueError: # read in and adapt the sbml slightly if os.path.abspath(model_output_dir) in sys.path: sys.path.remove(os.path.abspath(model_output_dir)) sbml_importer = amici.SbmlImporter(sbml_file) # add observables to sbml model def create_observable(sbml_model, obs_id): # create a parameter, which will get a rule assignmed as observable parameter = sbml_model.createParameter() parameter.setId(f'observable_{obs_id}') parameter.setName(f'observable_{obs_id}') parameter.constant = True rule = sbml_importer.sbml.createAssignmentRule() rule.setId(f'observable_{obs_id}') rule.setName(f'observable_{obs_id}') rule.setVariable(f'observable_{obs_id}') rule.setFormula(obs_id) # add initial assignments to sbml model def create_intial_assignment(sbml_model, spec_id): # create a parameter, which will get a rule assignmed as observable parameter = sbml_model.createParameter() parameter.setId(f'{spec_id}0') parameter.setName(f'{spec_id}0') parameter.constant = True assignment = sbml_importer.sbml.createInitialAssignment() assignment.setSymbol(f'{spec_id}') math = ('<math xmlns="http://www.w3.org/1998/Math/MathML"><ci>' f'{spec_id}0</ci></math>') assignment.setMath(libsbml.readMathMLFromString(math)) for spec in ('A', 'B'): create_observable(sbml_importer.sbml, spec) create_intial_assignment(sbml_importer.sbml, spec) # add constant parameters and observables to AMICI model constant_parameters = ['A0', 'B0'] observables = amici.assignmentRules2observables( sbml_importer.sbml, # the libsbml model object filter_function=lambda variable: variable.getId().startswith( 'observable_'), ) # generate the python module for the model. sbml_importer.sbml2amici( model_name, model_output_dir, verbose=False, observables=observables, constant_parameters=constant_parameters, ) # Importing the module and loading the model sys.path.insert(0, os.path.abspath(model_output_dir)) model_module = amici.import_model_module(model_name, model_output_dir) model = model_module.getModel() except RuntimeError as err: print('pyPESTO unit test ran into an error importing the conversion ' 'reaction enhanced model. This may happen due to an old version ' 'of this model being present in your python path (e.g., ' 'incorrect AMICI version comparing to the installed one). ' 'Delete the conversion_reaction_enhanced model from your python ' 'path and retry. Your python path is currently:') print(sys.path) print('Original error message:') raise err return model
NOTE: requires having run `make python-tests` in /build/ before to build the python modules for the test models. """ if case.startswith('sensi2'): model_name = sub_test + '_o2' else: model_name = sub_test model_swig_folder = \ os.path.join(os.path.dirname(__file__), '..', '..', 'build', 'tests', 'cpputest', f'external_{model_name}-prefix', 'src', f'external_{model_name}-build', 'swig') test_model_module = amici.import_model_module( module_name=model_name, module_path=model_swig_folder) model = test_model_module.getModel() solver = model.getSolver() amici.readModelDataFromHDF5(options_file, model.get(), f'/{sub_test}/{case}/options') amici.readSolverSettingsFromHDF5(options_file, solver.get(), f'/{sub_test}/{case}/options') edata = None if 'data' in expected_results[sub_test][case].keys(): edata = amici.readSimulationExpData(expected_results_file, f'/{sub_test}/{case}/data', model.get()) rdata = amici.runAmiciSimulation(model, solver, edata) check_derivative_opts = dict()
def import_petab_problem(petab_problem: petab.Problem, model_output_dir: str = None, model_name: str = None, force_compile: bool = False, **kwargs) -> 'amici.Model': """ Import model from petab problem. :param petab_problem: A petab problem containing all relevant information on the model. :param model_output_dir: Directory to write the model code to. Will be created if doesn't exist. Defaults to current directory. :param model_name: Name of the generated model. If model file name was provided, this defaults to the file name without extension, otherwise the SBML model ID will be used. :param force_compile: Whether to compile the model even if the target folder is not empty, or the model exists already. :param kwargs: Additional keyword arguments to be passed to :meth:`amici.sbml_import.SbmlImporter.sbml2amici`. :return: The imported model. """ # generate folder and model name if necessary if model_output_dir is None: if isinstance(petab_problem, PysbPetabProblem): raise ValueError("Parameter `model_output_dir` is required.") model_output_dir = \ _create_model_output_dir_name(petab_problem.sbml_model) else: model_output_dir = os.path.abspath(model_output_dir) if isinstance(petab_problem, PysbPetabProblem): if model_name is None: model_name = petab_problem.pysb_model.name else: raise ValueError( "Argument model_name currently not allowed for pysb models") elif model_name is None: model_name = _create_model_name(model_output_dir) # create folder if not os.path.exists(model_output_dir): os.makedirs(model_output_dir) # check if compilation necessary if not _can_import_model(model_name) or force_compile: # check if folder exists if os.listdir(model_output_dir) and not force_compile: raise ValueError( f"Cannot compile to {model_output_dir}: not empty. " "Please assign a different target or set `force_compile`.") # remove folder if exists if os.path.exists(model_output_dir): shutil.rmtree(model_output_dir) logger.info(f"Compiling model {model_name} to {model_output_dir}.") # compile the model if isinstance(petab_problem, PysbPetabProblem): import_model_pysb(petab_problem, model_output_dir=model_output_dir, **kwargs) else: import_model_sbml(sbml_model=petab_problem.sbml_model, condition_table=petab_problem.condition_df, observable_table=petab_problem.observable_df, measurement_table=petab_problem.measurement_df, model_name=model_name, model_output_dir=model_output_dir, **kwargs) # import model model_module = amici.import_model_module(model_name, model_output_dir) model = model_module.getModel() logger.info(f"Successfully loaded model {model_name} " f"from {model_output_dir}.") return model
def conversion_reaction_model(): # read in sbml file model_name = 'conversion_reaction' example_dir = os.path.join(os.path.dirname(__file__), '..', '..', 'doc', 'example') sbml_file = os.path.join(example_dir, model_name, f'model_{model_name}.xml') model_output_dir = os.path.join(example_dir, 'tmp', f'{model_name}_enhanced') # try to import the exisiting model, if possible try: sys.path.insert(0, os.path.abspath(model_output_dir)) model_module = amici.import_model_module(model_name, model_output_dir) model = model_module.getModel() except ValueError: # read in and adapt the sbml slightly if os.path.abspath(model_output_dir) in sys.path: sys.path.remove(os.path.abspath(model_output_dir)) sbml_importer = amici.SbmlImporter(sbml_file) # add observables to sbml model def create_observable(sbml_model, obs_id): # create a parameter, which will get a rule assignmed as observable parameter = sbml_model.createParameter() parameter.setId(f'observable_{obs_id}') parameter.setName(f'observable_{obs_id}') parameter.constant = True rule = sbml_importer.sbml.createAssignmentRule() rule.setId(f'observable_{obs_id}') rule.setName(f'observable_{obs_id}') rule.setVariable(f'observable_{obs_id}') rule.setFormula(obs_id) # add initial assignments to sbml model def create_intial_assignment(sbml_model, spec_id): # create a parameter, which will get a rule assignmed as observable parameter = sbml_model.createParameter() parameter.setId(f'{spec_id}0') parameter.setName(f'{spec_id}0') parameter.constant = True assignment = sbml_importer.sbml.createInitialAssignment() assignment.setSymbol(f'{spec_id}') math = '<math xmlns="http://www.w3.org/1998/Math/MathML"><ci>' \ f'{spec_id}0</ci></math>' assignment.setMath(libsbml.readMathMLFromString(math)) for spec in ('A', 'B'): create_observable(sbml_importer.sbml, spec) create_intial_assignment(sbml_importer.sbml, spec) # add constant parameters and observables to AMICI model constantParameters = ['A0', 'B0'] observables = amici.assignmentRules2observables( sbml_importer.sbml, # the libsbml model object filter_function=lambda variable: variable.getId().startswith( 'observable_')) # generate the python module for the model. sbml_importer.sbml2amici(model_name, model_output_dir, verbose=False, observables=observables, constantParameters=constantParameters) # Importing the module and loading the model sys.path.insert(0, os.path.abspath(model_output_dir)) model_module = amici.import_model_module(model_name, model_output_dir) model = model_module.getModel() return model
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)', globals={ 'model': model_pysb, 'solver': solver, 'amici': amici
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)