Exemple #1
0
    def test_write_read_sloppy(self):
        filename = os.path.join(self.tempdir, 'model.xlsx')

        Writer().run(filename, self.model, data_repo_metadata=False)

        wb = read_workbook(filename)
        row = wb['!!Model'].pop(3)
        wb['!!Model'].insert(4, row)
        write_workbook(filename, wb)

        with self.assertRaisesRegex(
                ValueError,
                "The rows of worksheet '!!Model' must be defined in this order"
        ):
            Reader().run(filename)

        env = EnvironmentVarGuard()
        env.set('CONFIG__DOT__wc_lang__DOT__io__DOT__strict', '0')
        with env:
            model = Reader().run(filename)[Model][0]
        self.assertEqual(model.validate(), None)

        self.assertTrue(model.is_equal(self.model))
        self.assertEqual(self.model.difference(model), '')
Exemple #2
0
    def test(self):
        model1 = Model(id='model1',
                       name='test model',
                       version='0.0.1a',
                       wc_lang_version='0.0.1')
        model2 = Model(id='model2',
                       name='test model',
                       version='0.0.1a',
                       wc_lang_version='0.0.1')
        filename = os.path.join(self.tempdir, 'model.xlsx')
        obj_tables.io.WorkbookWriter().run(filename, [model1, model2],
                                           models=Writer.MODELS,
                                           include_all_attributes=False)

        with self.assertRaisesRegex(ValueError, ' should define one model$'):
            Reader().run(filename)
Exemple #3
0
    def test_write_with_repo_metadata(self):
        # create temp git repo & write file into it
        test_repo_name = 'test_wc_lang_test_io'
        test_github_repo = GitHubRepoForTests(test_repo_name)
        repo = test_github_repo.make_test_repo(self.tempdir)

        # write data repo metadata in data_file
        data_file = os.path.join(self.tempdir, 'test.xlsx')
        Writer().run(data_file, self.model, data_repo_metadata=True)
        # deliberately read metadata
        objs_read = Reader().run(data_file, [utils.DataRepoMetadata] + list(Writer.MODELS))
        data_repo_metadata = objs_read[utils.DataRepoMetadata][0]
        self.assertTrue(data_repo_metadata.url.startswith('https://github.com/'))
        self.assertEqual(data_repo_metadata.branch, 'master')
        self.assertEqual(len(data_repo_metadata.revision), 40)

        test_github_repo.delete_test_repo()
Exemple #4
0
    def test_update_version_metadata(self):
        filename = path.join(self.tempdir, 'model.xlsx')

        model = Model(id='model',
                      name='test model',
                      version='0.0.1a',
                      wc_lang_version='0.0.0')
        self.assertNotEqual(model.wc_lang_version, wc_lang.__version__)
        Writer().run(filename, model, data_repo_metadata=False)

        with __main__.App(argv=[
                'update-version-metadata', filename, '--ignore-repo-metadata'
        ]) as app:
            app.run()

        model = Reader().run(filename)[Model][0]
        self.assertEqual(model.wc_lang_version, wc_lang.__version__)
Exemple #5
0
    def __init__(self, model):
        """
        Args:
            model (:obj:`str` or `Model`): either a path to file(s) describing a `wc_lang` model, or
                a `Model` instance

        Raises:
            :obj:`MultialgorithmError`: if `model` is invalid
        """
        if isinstance(model, Model):
            self.model_path = None
            self.model = model
        elif isinstance(model, str):
            # read model
            self.model_path = os.path.abspath(os.path.expanduser(model))
            self.model = Reader().run(self.model_path)[Model][0]
        else:
            raise MultialgorithmError(
                "model must be a `wc_lang Model` or a pathname for a model, "
                "but its type is {}".format(type(model)))
Exemple #6
0
    def _default(self):
        args = self.app.pargs

        if not args.transforms:
            raise SystemExit('Please select at least one transform')

        # read model
        model = Reader().run(args.source)[Model][0]

        # apply transforms
        transforms = transform.get_transforms()
        for id in args.transforms:
            cls = transforms[id]
            instance = cls()
            instance.run(model)

        # write model
        Writer().run(args.dest,
                     model,
                     data_repo_metadata=False,
                     protected=(not args.unprotected))
Exemple #7
0
class TestSkeletonSubmodel(unittest.TestCase):

    def setUp(self):
        warnings.simplefilter("ignore")
        self.MODEL_FILENAME = os.path.join(os.path.dirname(__file__), 'fixtures',
                                           'test_submodel_no_shared_species.xlsx')
        self.model = Reader().run(self.MODEL_FILENAME)[Model][0]
        prepare_model(self.model)

    def make_sim_w_skeleton_submodel(self, lang_submodel, behavior):
        self.simulator = SimulationEngine()
        # concatenate tuples in fn call for Py 2.7: see https://stackoverflow.com/a/12830036
        skeleton_submodel = SkeletonSubmodel(
            *(make_dynamic_submodel_params(self.model, lang_submodel) + (behavior,)))
        self.simulator.add_object(skeleton_submodel)
        self.simulator.initialize()
        return skeleton_submodel

    def test_skeleton_submodel(self):
        behavior = {SkeletonSubmodel.INTER_REACTION_TIME: 2}
        lang_submodel = self.model.get_submodels()[0]
        for conc in self.model.distribution_init_concentrations:
            conc.std = 0

        time_max = 100
        skeleton_submodel = self.make_sim_w_skeleton_submodel(lang_submodel, behavior)
        self.assertEqual(self.simulator.simulate(time_max),
                         time_max / behavior[SkeletonSubmodel.INTER_REACTION_TIME])

        behavior = {SkeletonSubmodel.INTER_REACTION_TIME: 2,
                    SkeletonSubmodel.REACTION_TO_EXECUTE: 0}    # reaction #0 makes one more 'species_1[c]'
        skeleton_submodel = self.make_sim_w_skeleton_submodel(lang_submodel, behavior)
        interval = 10
        pop_before = skeleton_submodel.local_species_population.read_one(0, 'species_1[c]')
        for time_max in range(interval, 5 * interval, interval):
            self.simulator.simulate(time_max)
            pop_after = skeleton_submodel.local_species_population.read_one(time_max, 'species_1[c]')
            delta = pop_after - pop_before
            self.assertEqual(delta, interval / behavior[SkeletonSubmodel.INTER_REACTION_TIME])
            pop_before = pop_after
Exemple #8
0
    def test_convert(self):
        filename_xls1 = os.path.join(self.tempdir, 'model1.xlsx')
        filename_xls2 = os.path.join(self.tempdir, 'model2.xlsx')
        filename_csv = os.path.join(self.tempdir, 'model-*.csv')

        Writer().run(filename_xls1, self.model, data_repo_metadata=False)

        convert(filename_xls1, filename_csv)
        self.assertTrue(os.path.isfile(os.path.join(self.tempdir, 'model-Model.csv')))
        self.assertTrue(os.path.isfile(os.path.join(self.tempdir, 'model-Taxon.csv')))
        model = Reader().run(filename_csv)[Model][0]
        self.assertTrue(model.is_equal(self.model))

        convert(filename_csv, filename_xls2)
        model = Reader().run(filename_xls2)[Model][0]
        self.assertTrue(model.is_equal(self.model))
Exemple #9
0
    def test_write_with_optional_args(self):
        # write model to file, passing models
        filename = os.path.join(self.tempdir, 'model.xlsx')
        Writer().run(filename, self.model, models=Writer.MODELS)

        # read model and verify that it validates
        model = Reader().run(filename)[Model][0]
        self.assertEqual(model.validate(), None)

        # write model to file, passing validate
        filename = os.path.join(self.tempdir, 'model.xlsx')
        Writer().run(filename, self.model, validate=True)

        # read model and verify that it validates
        model = Reader().run(filename)[Model][0]
        self.assertEqual(model.validate(), None)
Exemple #10
0
    def _default(self):
        args = self.app.pargs

        # read model
        model = Reader().run(args.in_file)[Model][0]

        # split submodels into separate models
        core, submodels = model.submodels.gen_models()

        # create output directory, if it doesn't exist
        if not os.path.isdir(args.out_dir):
            os.makedirs(args.out_dir)

        # save separated submodels to file
        Writer().run(os.path.join(args.out_dir, 'core.xlsx'),
                     core,
                     data_repo_metadata=False,
                     protected=(not args.unprotected))
        for submodel in submodels:
            Writer().run(os.path.join(
                args.out_dir, '{}.xlsx'.format(submodel.submodels[0].id)),
                         submodel,
                         data_repo_metadata=False,
                         protected=(not args.unprotected))
Exemple #11
0
    def test_read_without_validation(self):
        # write model to file
        filename = os.path.join(self.tempdir, 'model.xlsx')
        Writer().run(filename, self.model, data_repo_metadata=False)

        # read model and verify that it validates
        model = Reader().run(filename)[Model][0]
        self.assertEqual(model.validate(), None)

        # introduce error into model file
        wb = read_workbook(filename)
        wb['!!Model'][4][1] = '1000'
        write_workbook(filename, wb)

        # read model and verify that it doesn't validate
        with self.assertRaisesRegex(ValueError, 'does not match pattern'):
            Reader().run(filename)

        env = EnvironmentVarGuard()
        env.set('CONFIG__DOT__wc_lang__DOT__io__DOT__validate', '0')
        with env:
            model = Reader().run(filename)[Model][0]

        self.assertNotEqual(model.validate(), None)
    def test_make_test_model(self):
        '''
        Simple SSA model tests:
            no reactions: simulation terminates immediately
            1 species:
                one reaction consume species, at constant rate: consume all reactant, in time given by rate
            2 species:
                one reaction: convert all reactant into product, in time given by rate
                a pair of symmetrical reactions with constant rates: maintain steady state, on average
                a pair of symmetrical reactions rates given by reactant population: maintain steady state, on average
                a pair of symmetrical reactions rates given by product population: exhaust on species,
                    with equal chance for each species
            ** ring of futile reactions with balanced rates: maintain steady state, on average
        '''

        # test get_model_type_params
        expected_params_list = [(0, 0, False, RateLawType.constant),
                                (1, 1, False, RateLawType.constant),
                                (2, 1, False, RateLawType.constant),
                                (2, 1, True, RateLawType.constant),
                                (2, 1, True, RateLawType.reactant_pop),
                                (2, 1, True, RateLawType.product_pop)]
        for model_type, expected_params in zip(self.model_types,
                                               expected_params_list):
            params = MakeModel.get_model_type_params(model_type)
            self.assertEqual(params, expected_params)

        # test make_test_model
        for model_type in self.model_types:
            for num_submodels in [1, 10]:
                model = MakeModel.make_test_model(
                    model_type,
                    num_submodels=num_submodels,
                    transform_prep_and_check=False)
                self.assertEqual(model.validate(), None)

                # test round-tripping
                file = model_type.replace(' ', '_').replace(',', '')
                file = "{}_{}_submodels.xlsx".format(file, num_submodels)
                filename = os.path.join(self.test_dir, file)
                Writer().run(filename, model, data_repo_metadata=False)
                round_trip_model = Reader().run(filename)[Model][0]
                self.assertEqual(round_trip_model.validate(), None)
                self.assertTrue(round_trip_model.is_equal(model, tol=1e-8))
                self.assertEqual(model.difference(round_trip_model, tol=1e-8),
                                 '')

        # unittest one of the models made
        # TODO (ARTHUR): test with multiple submodels
        # TODO (ARTHUR): test observables
        # TODO (ARTHUR): test functions
        model = MakeModel.make_test_model(self.model_types[4])
        self.assertEqual(model.id, 'test_model')
        comp = model.compartments[0]
        self.assertEqual(comp.id, 'compt_1')
        species_type_ids = set([st.id for st in model.species_types])
        self.assertEqual(species_type_ids, set(['spec_type_0', 'spec_type_1']))
        species_ids = set([s.id for s in comp.species])
        self.assertEqual(species_ids,
                         set(['spec_type_0[compt_1]', 'spec_type_1[compt_1]']))
        submodel = model.submodels[0]

        # reaction was split by SplitReversibleReactionsTransform
        ratelaw_elements = set()
        for r in submodel.reactions:
            self.assertFalse(r.reversible)
            rl = r.rate_laws[0]
            ratelaw_elements.add((rl.direction, rl.expression.expression))
        expected_rate_laws = set([
            # direction, expression.expression
            (RateLawDirection.forward,
             'k_cat_1_1_for * spec_type_0[compt_1] / Avogadro / volume_compt_1'
             ),  # forward
            (RateLawDirection.forward,
             'k_cat_1_1_bck * spec_type_1[compt_1] / Avogadro / volume_compt_1'
             ),  # backward, but reversed
        ])
        self.assertEqual(ratelaw_elements, expected_rate_laws)

        participant_elements = set()
        for r in submodel.reactions:
            r_list = []
            for part in r.participants:
                r_list.append((part.species.id, part.coefficient))
            participant_elements.add(tuple(sorted(r_list)))
        expected_participants = set([
            # id, coefficient
            tuple(
                sorted((('spec_type_0[compt_1]', -1), ('spec_type_1[compt_1]',
                                                       1)))),  # forward
            tuple(
                sorted((('spec_type_1[compt_1]', -1), ('spec_type_0[compt_1]',
                                                       1)))),  # reversed
        ])
        self.assertEqual(participant_elements, expected_participants)

        # test exceptions
        with self.assertRaises(ValueError):
            MakeModel.make_test_model('3 reactions')

        with self.assertRaises(ValueError):
            MakeModel.make_test_model(self.model_types[0], num_submodels=0)
Exemple #13
0
 def setUp(self):
     self.dirname = tempfile.mkdtemp()
     # read and initialize a model
     self.model = Reader().run(self.MODEL_FILENAME)[Model][0]
Exemple #14
0
class SbmlIoTestCase(unittest.TestCase):

    MODEL_FILENAME = os.path.join(os.path.dirname(__file__), '..', 'fixtures',
                                  'sbml-io.xlsx')

    def setUp(self):
        self.dirname = tempfile.mkdtemp()
        # read and initialize a model
        self.model = Reader().run(self.MODEL_FILENAME)[Model][0]

    def tearDown(self):
        shutil.rmtree(self.dirname)

    def test_export_import(self):
        model = PrepForSbmlTransform().run(self.model)
        core, submodels = model.submodels.gen_models()

        all_submodels = [core] + submodels
        all_submodels_2 = []
        for i_submodel, submodel in enumerate(all_submodels):

            sbml_doc = sbml_io.SbmlExporter.run(submodel)
            submodel_2 = sbml_io.SbmlImporter.run(sbml_doc)
            self.assertTrue(submodel_2.is_equal(submodel))
            all_submodels_2.append(submodel_2)

        model_2 = all_submodels_2[0]
        for submodel_2 in all_submodels_2[1:]:
            model_2.merge(submodel_2)
        self.assertTrue(model_2.is_equal(model))

    def test_SbmlExporter_error(self):
        model = Model(id='model')
        model.submodels.create(
            id='Metabolism',
            framework=onto['WC:dynamic_flux_balance_analysis'])
        model.submodels.create(
            id='Metabolism_2',
            framework=onto['WC:dynamic_flux_balance_analysis'])
        with self.assertRaisesRegex(ValueError,
                                    'Only 1 submodel can be encoded'):
            sbml_io.SbmlExporter.run(model)

        model = Model(id='model')
        submodel = model.submodels.create(
            id='Metabolism',
            framework=onto['WC:dynamic_flux_balance_analysis'])
        model.reactions.create(
            id='rxn_1',
            submodel=submodel,
            flux_bounds=FluxBounds(units=unit_registry.parse_units('M s^-1')))
        model.reactions.create(
            id='rxn_1',
            submodel=submodel,
            flux_bounds=FluxBounds(units=unit_registry.parse_units('M s^-1')))
        with self.assertRaisesRegex(sbml_util.LibSbmlError,
                                    'Document is invalid'):
            with self.assertWarnsRegex(WcLangWarning, 'Model is invalid'):
                sbml_io.SbmlExporter.run(model)

    def test_write_read(self):
        shutil.rmtree(self.dirname)

        sbml_io.SbmlWriter().run(self.model, self.dirname)
        model = sbml_io.SbmlReader().run(self.dirname)

        sbml_compat_model = PrepForSbmlTransform().run(self.model.copy())
        self.assertTrue(model.is_equal(sbml_compat_model))

    def test_export_another_model(self):
        filename = 'tests/sbml/fixtures/static-model.xlsx'
        model = Reader().run(filename)[Model][0]
        self.assertEqual(model.validate(), None)

        # write SBML file
        sbml_io.SbmlWriter().run(model, self.dirname)

    def test_writer_errors(self):
        model = Model(version=None)
        with self.assertWarnsRegex(WcLangWarning, 'Model is invalid:'):
            sbml_io.SbmlWriter().run(model, self.dirname)

        with mock.patch('libsbml.writeSBMLToFile', return_value=False):
            with self.assertRaisesRegex(ValueError,
                                        ' could not be written to '):
                sbml_io.SbmlWriter().run(self.model, self.dirname)
Exemple #15
0
 def test_read(self):
     filename = os.path.join(self.tempdir, 'model.xlsx')
     obj_tables.io.WorkbookWriter().run(filename, [Submodel(id='submodel')], models=Writer.MODELS, include_all_attributes=False)
     with self.assertRaisesRegex(ValueError, 'should define one model'):
         Reader().run(filename)
Exemple #16
0
 def test_create_template(self):
     create_template(self.filename, data_repo_metadata=False)
     self.assertIsInstance(Reader().run(self.filename), dict)
     self.assertIsInstance(Reader().run(self.filename)[Model][0], Model)
class TestModelUtilities(unittest.TestCase):
    def get_submodel(self, model, id_val):
        return model.submodels.get_one(id=id_val)

    MODEL_FILENAME = os.path.join(os.path.dirname(__file__), 'fixtures',
                                  'test_model.xlsx')

    def setUp(self):
        # read a model
        self.model = Reader().run(self.MODEL_FILENAME,
                                  ignore_extra_models=True)[wc_lang.Model][0]

    def test_find_private_species(self):
        # since set() operations are being used, this test does not ensure that the methods being
        # tested are deterministic and repeatable; repeatability should be tested by running the
        # code under different circumstances and ensuring identical output
        private_species = ModelUtilities.find_private_species(self.model)

        submodel_1_exp_species_ids = [
            'species_1[c]', 'species_1[e]', 'species_2[e]'
        ]
        mod1_expected_species = wc_lang.Species.get(submodel_1_exp_species_ids,
                                                    self.model.get_species())
        self.assertEqual(
            set(private_species[self.get_submodel(self.model, 'submodel_1')]),
            set(mod1_expected_species))

        submodel_2_exp_species_ids = [
            'species_5[c]', 'species_4[c]', 'species_6[c]'
        ]
        mod2_expected_species = wc_lang.Species.get(submodel_2_exp_species_ids,
                                                    self.model.get_species())
        self.assertEqual(
            set(private_species[self.get_submodel(self.model, 'submodel_2')]),
            set(mod2_expected_species))

        private_species = ModelUtilities.find_private_species(self.model,
                                                              return_ids=True)
        self.assertEqual(set(private_species['submodel_1']),
                         set(submodel_1_exp_species_ids))
        self.assertEqual(set(private_species['submodel_2']),
                         set(submodel_2_exp_species_ids))

    def test_find_shared_species(self):
        self.assertEqual(
            set(ModelUtilities.find_shared_species(self.model)),
            set(
                wc_lang.Species.get(
                    ['species_2[c]', 'species_3[c]', 'H2O[e]', 'H2O[c]'],
                    self.model.get_species())))

        self.assertEqual(
            set(ModelUtilities.find_shared_species(self.model,
                                                   return_ids=True)),
            set(['species_2[c]', 'species_3[c]', 'H2O[e]', 'H2O[c]']))

    def test_sample_copy_num_from_concentration(self):
        model = wc_lang.Model()

        submodel = model.submodels.create(
            id='submodel',
            framework=onto['WC:stochastic_simulation_algorithm'])

        compartment_c = model.compartments.create(
            id='c', init_volume=wc_lang.InitVolume(mean=1.))

        structure = wc_lang.ChemicalStructure(molecular_weight=10.)

        species_types = {}
        cus_species_types = {}
        for cu in wc_lang.DistributionInitConcentration.units.choices:
            id = str(cu).replace(' ', '_')
            species_types[id] = model.species_types.create(id=id,
                                                           structure=structure)
            cus_species_types[id] = cu

        for other in ['no_units', 'no_concentration', 'no_std']:
            species_types[other] = model.species_types.create(
                id=other, structure=structure)

        species = {}
        for key, species_type in species_types.items():
            species[key] = wc_lang.Species(species_type=species_type,
                                           compartment=compartment_c)
            species[key].id = species[key].gen_id()

        conc_value = 2_000.
        std_value = 0.
        for key, sp in species.items():
            if key in cus_species_types:
                wc_lang.DistributionInitConcentration(
                    species=sp,
                    mean=conc_value,
                    std=std_value,
                    units=cus_species_types[key])
            elif key == 'no_units':
                wc_lang.DistributionInitConcentration(species=sp,
                                                      mean=conc_value,
                                                      std=std_value)
            elif key == 'no_std':
                wc_lang.DistributionInitConcentration(
                    species=sp,
                    mean=conc_value,
                    std=float('NaN'),
                    units=cus_species_types['molecule'])
            elif key == 'no_concentration':
                continue

        conc_to_molecules = ModelUtilities.sample_copy_num_from_concentration
        random_state = numpy.random.RandomState()
        copy_number = conc_to_molecules(
            species['molecule'],
            species['molecule'].compartment.init_volume.mean, random_state)
        self.assertEqual(copy_number, conc_value)
        copy_number = conc_to_molecules(
            species['molar'], species['molar'].compartment.init_volume.mean,
            random_state)
        self.assertEqual(copy_number, conc_value * Avogadro)
        copy_number = conc_to_molecules(
            species['no_units'],
            species['no_units'].compartment.init_volume.mean, random_state)
        self.assertEqual(copy_number, conc_value * Avogadro)
        copy_number = conc_to_molecules(
            species['millimolar'],
            species['millimolar'].compartment.init_volume.mean, random_state)
        self.assertEqual(copy_number, 10**-3 * conc_value * Avogadro)
        copy_number = conc_to_molecules(
            species['micromolar'],
            species['micromolar'].compartment.init_volume.mean, random_state)
        self.assertEqual(copy_number, 10**-6 * conc_value * Avogadro)
        copy_number = conc_to_molecules(
            species['nanomolar'],
            species['nanomolar'].compartment.init_volume.mean, random_state)
        self.assertEqual(copy_number, 10**-9 * conc_value * Avogadro)
        copy_number = conc_to_molecules(
            species['picomolar'],
            species['picomolar'].compartment.init_volume.mean, random_state)
        self.assertEqual(copy_number, 10**-12 * conc_value * Avogadro)
        copy_number = conc_to_molecules(
            species['femtomolar'],
            species['femtomolar'].compartment.init_volume.mean, random_state)
        self.assertAlmostEqual(copy_number,
                               10**-15 * conc_value * Avogadro,
                               delta=1)
        copy_number = conc_to_molecules(
            species['attomolar'],
            species['attomolar'].compartment.init_volume.mean, random_state)
        self.assertAlmostEqual(copy_number,
                               10**-18 * conc_value * Avogadro,
                               delta=1)
        copy_number = conc_to_molecules(
            species['no_concentration'],
            species['no_concentration'].compartment.init_volume.mean,
            random_state)
        self.assertEqual(copy_number, 0)
        conc = species['no_std'].distribution_init_concentration
        copy_number = conc_to_molecules(
            species['no_std'], species['no_std'].compartment.init_volume.mean,
            random_state)
        self.assertNotEqual(copy_number, conc_value)

        with self.assertRaises(KeyError):
            conc_to_molecules(
                species['mol dm^-2'],
                species['no_concentration'].compartment.init_volume.mean,
                random_state)

        species_tmp = wc_lang.Species(species_type=species_type,
                                      compartment=compartment_c)
        species_tmp.id = species_tmp.gen_id()
        wc_lang.DistributionInitConcentration(
            species=species_tmp,
            mean=conc_value,
            std=std_value,
            units='not type(unit_registry.Unit)')
        with self.assertRaisesRegex(ValueError, 'Unsupported unit type'):
            conc_to_molecules(species_tmp,
                              species_tmp.compartment.init_volume.mean,
                              random_state)

        species_tmp2 = wc_lang.Species(species_type=species_type,
                                       compartment=compartment_c)
        species_tmp2.id = species_tmp2.gen_id()
        wc_lang.DistributionInitConcentration(
            species=species_tmp2,
            mean=conc_value,
            std=std_value,
            units=wc_lang.InitVolume.units.choices[0])
        with self.assertRaisesRegex(ValueError, 'Unsupported unit'):
            conc_to_molecules(species_tmp2,
                              species_tmp2.compartment.init_volume.mean,
                              random_state)

    def test_get_species_types(self):
        self.assertEqual(ModelUtilities.get_species_types([]), [])

        species_type_ids = [
            species_type.id for species_type in self.model.get_species_types()
        ]
        species_ids = [
            species.serialize() for species in self.model.get_species()
        ]
        self.assertEqual(sorted(ModelUtilities.get_species_types(species_ids)),
                         sorted(species_type_ids))

    def test_get_species_types(self):
        self.assertEqual(
            ModelUtilities.parse_species_id('species_type_id[compartment_id]'),
            ('species_type_id', 'compartment_id'))
        with self.assertRaisesRegex(ValueError, 'Species id format should be'):
            ModelUtilities.parse_species_id('compartment_id]')
        with self.assertRaisesRegex(ValueError, 'Species id format should be'):
            ModelUtilities.parse_species_id('[compartment_id]')
        with self.assertRaisesRegex(ValueError, 'Species id format should be'):
            ModelUtilities.parse_species_id('species_type_id[]')
        with self.assertRaisesRegex(ValueError, 'Species id format should be'):
            ModelUtilities.parse_species_id(
                'species_type_id[compartment_id]extra')
Exemple #18
0
 def setUpClass(cls):
     cls.models = {}
     for model_file in [cls.MODEL_FILENAME, cls.DRY_MODEL_FILENAME]:
         cls.models[model_file] = Reader().run(
             model_file, ignore_extra_models=True)[Model][0]
 def setUp(self):
     # read a model
     self.model = Reader().run(self.MODEL_FILENAME,
                               ignore_extra_models=True)[wc_lang.Model][0]
from libsbml import writeSBMLToFile

from wc_lang.io import Reader
import wc_lang.sbml.io as sbml_io
from obj_model import utils
from wc_lang.prepare import PrepareModel

args = Namespace(end_time=1,
    time_step=1,
    test_submodel_id='Metabolism',
    wc_lang_model="example-model.xlsx")

MODEL_FILENAME = path.join(path.dirname(__file__), '../../..', 'wc_lang/tests/fixtures',
    args.wc_lang_model)
print('using:', MODEL_FILENAME)
model = Reader().run(MODEL_FILENAME)
PrepareModel(model).run()
submodel = utils.get_component_by_id(model.get_submodels(), args.test_submodel_id)
_, SBMLfile = tempfile.mkstemp()

def try_cobrapy(args):
    time = 0
    while time < args.end_time:
        print('time:', time)
        sbml_document = sbml_io.SBMLExchange.write_submodel(submodel)
        if not writeSBMLToFile(sbml_document, SBMLfile):
            raise ValueError("SBML document for submodel '{}' could not be written to '{}'.".format(
                args.test_submodel_id, SBMLfile))
        # cobra_model = cobra.io.read_sbml_model(SBMLfile)
        cobra_model = cobra.io.sbml3.read_sbml_model(SBMLfile)
        print('cobra_model', cobra_model)
Exemple #21
0
class TestMultialgorithmSimulationStatically(unittest.TestCase):

    MODEL_FILENAME = os.path.join(os.path.dirname(__file__), 'fixtures', 'test_model.xlsx')

    def setUp(self):
        # read and initialize a model
        self.model = Reader().run(self.MODEL_FILENAME, ignore_extra_models=True)[Model][0]
        for conc in self.model.distribution_init_concentrations:
            conc.std = 0.
        PrepForWcSimTransform().run(self.model)
        de_simulation_config = SimulationConfig(time_max=10)
        self.wc_sim_config = WCSimulationConfig(de_simulation_config, dfba_time_step=1)
        self.multialgorithm_simulation = MultialgorithmSimulation(self.model, self.wc_sim_config)
        self.test_dir = tempfile.mkdtemp()
        self.results_dir = tempfile.mkdtemp(dir=self.test_dir)

    def tearDown(self):
        shutil.rmtree(self.test_dir)

    def test_init(self):
        self.model.submodels = []
        with self.assertRaises(MultialgorithmError):
            MultialgorithmSimulation(self.model, self.wc_sim_config)

    def test_prepare_skipped_submodels(self):
        multialgorithm_simulation = MultialgorithmSimulation(self.model, self.wc_sim_config)
        self.assertEqual(multialgorithm_simulation.skipped_submodels(), set())
        submodels_to_skip = ['submodel_1']
        self.wc_sim_config.submodels_to_skip = submodels_to_skip
        multialgorithm_simulation = MultialgorithmSimulation(self.model, self.wc_sim_config)
        self.assertEqual(multialgorithm_simulation.skipped_submodels(), set(submodels_to_skip))

        submodels_to_skip = ['no_such_submodel']
        self.wc_sim_config.submodels_to_skip = submodels_to_skip
        with self.assertRaisesRegex(MultialgorithmError,
                                    "'submodels_to_skip' contains submodels that aren't in the model:"):
            MultialgorithmSimulation(self.model, self.wc_sim_config)

    def test_molecular_weights_for_species(self):
        multi_alg_sim = self.multialgorithm_simulation
        expected = {
            'species_6[c]': float('nan'),
            'H2O[c]': 18.0152
        }
        actual = multi_alg_sim.molecular_weights_for_species(set(expected.keys()))
        self.assertEqual(actual['H2O[c]'], expected['H2O[c]'])
        self.assertTrue(np.isnan(actual['species_6[c]']))

        # add a species_type without a structure
        species_type_wo_structure = self.model.species_types.create(
            id='st_wo_structure',
            name='st_wo_structure')
        cellular_compartment = self.model.compartments.get(**{'id': 'c'})[0]
        species_wo_structure = self.model.species.create(
            species_type=species_type_wo_structure,
            compartment=cellular_compartment)
        species_wo_structure.id = species_wo_structure.gen_id()

        actual = multi_alg_sim.molecular_weights_for_species([species_wo_structure.id])
        self.assertTrue(np.isnan(actual[species_wo_structure.id]))

        # test obtain weights for all species
        actual = multi_alg_sim.molecular_weights_for_species()
        self.assertEqual(actual['H2O[c]'], expected['H2O[c]'])
        self.assertTrue(np.isnan(actual['species_6[c]']))
        self.assertEqual(len(actual), len(self.model.get_species()))

    def test_create_dynamic_compartments(self):
        self.multialgorithm_simulation.create_dynamic_compartments()
        self.assertEqual(set(['c', 'e']), set(self.multialgorithm_simulation.temp_dynamic_compartments))
        for id, dynamic_compartment in self.multialgorithm_simulation.temp_dynamic_compartments.items():
            self.assertEqual(id, dynamic_compartment.id)
            self.assertTrue(0 < dynamic_compartment.init_density)

    def test_prepare_dynamic_compartments(self):
        self.multialgorithm_simulation.create_dynamic_compartments()
        self.multialgorithm_simulation.init_species_pop_from_distribution()
        self.multialgorithm_simulation.local_species_population = \
            self.multialgorithm_simulation.make_local_species_population(retain_history=False)
        self.multialgorithm_simulation.prepare_dynamic_compartments()
        for dynamic_compartment in self.multialgorithm_simulation.temp_dynamic_compartments.values():
            self.assertTrue(dynamic_compartment._initialized())
            self.assertTrue(0 < dynamic_compartment.accounted_mass())
            self.assertTrue(0 < dynamic_compartment.mass())

    def test_init_species_pop_from_distribution(self):
        self.multialgorithm_simulation.create_dynamic_compartments()
        self.multialgorithm_simulation.init_species_pop_from_distribution()
        species_wo_init_conc = ['species_1[c]', 'species_3[c]']
        for species_id in species_wo_init_conc:
            self.assertEqual(self.multialgorithm_simulation.init_populations[species_id], 0)
        for concentration in self.model.get_distribution_init_concentrations():
            self.assertTrue(0 <= self.multialgorithm_simulation.init_populations[concentration.species.id])

        # todo: statistically evaluate sampled population
        # ensure that over multiple runs of init_species_pop_from_distribution():
        # mean(species population) ~= mean(volume) * mean(concentration)

    def test_make_local_species_population(self):
        self.multialgorithm_simulation.create_dynamic_compartments()
        self.multialgorithm_simulation.init_species_pop_from_distribution()
        local_species_population = self.multialgorithm_simulation.make_local_species_population()
        self.assertEqual(local_species_population._molecular_weights,
            self.multialgorithm_simulation.molecular_weights_for_species())

        # test the initial population slopes
        # continuous adjustments are only allowed on species used by continuous submodels
        used_by_continuous_submodels = \
            ['species_1[e]', 'species_2[e]', 'species_1[c]', 'species_2[c]', 'species_3[c]']
        adjustments = {species_id: 0. for species_id in used_by_continuous_submodels}
        self.assertEqual(local_species_population.adjust_continuously(1, adjustments), None)
        not_in_a_reaction = ['H2O[e]', 'H2O[c]']
        used_by_discrete_submodels = ['species_4[c]', 'species_5[c]', 'species_6[c]']
        adjustments = {species_id: 0. for species_id in used_by_discrete_submodels + not_in_a_reaction}
        with self.assertRaises(DynamicSpeciesPopulationError):
            local_species_population.adjust_continuously(2, adjustments)

    def test_set_simultaneous_execution_priorities(self):
        expected_order_of_sim_obj_classes = [SsaSubmodel,
                                             NrmSubmodel,
                                             DsaSubmodel,
                                             DfbaSubmodel,
                                             OdeSubmodel,
                                             MultialgorithmicCheckpointingSimObj]
        self.multialgorithm_simulation.set_simultaneous_execution_priorities()
        # ensure that expected_order_of_sim_obj_classes are arranged in decreasing priority
        for i in range(len(expected_order_of_sim_obj_classes) - 1):
            simulation_object_class = expected_order_of_sim_obj_classes[i]
            next_simulation_object_class = expected_order_of_sim_obj_classes[i+1]
            self.assertLess(simulation_object_class.metadata.class_priority,
                            next_simulation_object_class.metadata.class_priority)

    def test_initialize_components(self):
        self.multialgorithm_simulation.initialize_components()
        self.assertTrue(isinstance(self.multialgorithm_simulation.local_species_population,
                        LocalSpeciesPopulation))
        for dynamic_compartment in self.multialgorithm_simulation.temp_dynamic_compartments.values():
            self.assertTrue(isinstance(dynamic_compartment.species_population, LocalSpeciesPopulation))

    def test_initialize_infrastructure(self):
        self.multialgorithm_simulation.initialize_components()
        self.multialgorithm_simulation.initialize_infrastructure()
        self.assertTrue(isinstance(self.multialgorithm_simulation.dynamic_model, DynamicModel))

        de_simulation_config = SimulationConfig(time_max=10, output_dir=self.results_dir)
        wc_sim_config = WCSimulationConfig(de_simulation_config, dfba_time_step=1, checkpoint_period=10)
        multialg_sim = MultialgorithmSimulation(self.model, wc_sim_config)
        multialg_sim.initialize_components()
        multialg_sim.initialize_infrastructure()
        self.assertEqual(multialg_sim.checkpointing_sim_obj.checkpoint_dir, self.results_dir)
        self.assertTrue(multialg_sim.checkpointing_sim_obj.access_state_object is not None)
        self.assertTrue(isinstance(multialg_sim.checkpointing_sim_obj, MultialgorithmicCheckpointingSimObj))
        self.assertTrue(isinstance(multialg_sim.dynamic_model, DynamicModel))

    def test_build_simulation(self):
        de_simulation_config = SimulationConfig(time_max=10, output_dir=self.results_dir)
        wc_sim_config = WCSimulationConfig(de_simulation_config, dfba_time_step=1, checkpoint_period=10)
        multialgorithm_simulation = MultialgorithmSimulation(self.model, wc_sim_config)
        simulation_engine, _ = multialgorithm_simulation.build_simulation()
        # 3 objects: 2 submodels, and the checkpointing obj:
        expected_sim_objs = set(['CHECKPOINTING_SIM_OBJ', 'submodel_1', 'submodel_2'])
        self.assertEqual(expected_sim_objs, set(list(simulation_engine.simulation_objects)))
        self.assertEqual(type(multialgorithm_simulation.checkpointing_sim_obj),
                         MultialgorithmicCheckpointingSimObj)
        self.assertEqual(multialgorithm_simulation.dynamic_model.get_num_submodels(), 2)

        # check that submodels receive options
        dfba_options = dict(dfba='fast but inaccurate')
        ssa_options = dict(ssa='accurate but slow')
        options = {'DfbaSubmodel': dict(options=dfba_options),
                   'SsaSubmodel': dict(options=ssa_options)
                  }
        multialgorithm_simulation = MultialgorithmSimulation(self.model, wc_sim_config, options)
        multialgorithm_simulation.build_simulation()
        dfba_submodel = multialgorithm_simulation.dynamic_model.dynamic_submodels['submodel_1']
        ssa_submodel = multialgorithm_simulation.dynamic_model.dynamic_submodels['submodel_2']
        self.assertEqual(dfba_submodel.options, dfba_options)
        self.assertEqual(ssa_submodel.options, ssa_options)

        # test skipped submodel
        submodels_to_skip = ['submodel_2']
        self.wc_sim_config.submodels_to_skip = submodels_to_skip
        ma_sim = MultialgorithmSimulation(self.model, self.wc_sim_config)
        _, dynamic_model = ma_sim.build_simulation()
        expected_dynamic_submodels = set([sm.id for sm in self.model.get_submodels()]) - ma_sim.skipped_submodels()
        self.assertEqual(expected_dynamic_submodels, set(dynamic_model.dynamic_submodels))

        submodel_1 = self.model.submodels.get(id='submodel_1')[0]
        # WC:modeling_framework is not an instance of a modeling framework
        submodel_1.framework = onto['WC:modeling_framework']
        ma_sim = MultialgorithmSimulation(self.model, self.wc_sim_config)
        with self.assertRaisesRegex(MultialgorithmError, 'Unsupported lang_submodel framework'):
            ma_sim.build_simulation()

    def test_get_dynamic_compartments(self):
        expected_compartments = dict(
            submodel_1=['c', 'e'],
            submodel_2=['c']
        )
        self.multialgorithm_simulation.build_simulation()
        for submodel_id in ['submodel_1', 'submodel_2']:
            submodel = self.model.submodels.get_one(id=submodel_id)
            submodel_dynamic_compartments = self.multialgorithm_simulation.get_dynamic_compartments(submodel)
            self.assertEqual(set(submodel_dynamic_compartments.keys()), set(expected_compartments[submodel_id]))

    def test_str(self):
        self.multialgorithm_simulation.create_dynamic_compartments()
        self.multialgorithm_simulation.init_species_pop_from_distribution()
        self.multialgorithm_simulation.local_species_population = \
            self.multialgorithm_simulation.make_local_species_population(retain_history=False)
        self.assertIn('species_1[e]', str(self.multialgorithm_simulation))
        self.assertIn('model:', str(self.multialgorithm_simulation))
Exemple #22
0
    def test_cut_submodels(self):
        timestamp = datetime.datetime(2018, 1, 1, 12, 0, 0)
        model = Model(id='model',
                      name='test model',
                      version='0.0.1a',
                      wc_lang_version='0.0.1',
                      created=timestamp,
                      updated=timestamp)
        model.submodels.create(id='submodel_1')
        model.submodels.create(id='submodel_2')
        model.references.create(id='ref_0')
        model.references.create(id='ref_1', submodels=model.submodels[0:1])
        model.references.create(id='ref_2', submodels=model.submodels[1:2])
        model.references.create(id='ref_3', submodels=model.submodels[0:2])

        in_path = path.join(self.tempdir, 'in.xlsx')
        Writer().run(in_path, model, data_repo_metadata=False)

        out_path = path.join(self.tempdir, 'out')
        with __main__.App(argv=['cut-submodels', in_path, out_path]) as app:
            app.run()

        model_0 = Reader().run(path.join(out_path, 'core.xlsx'))[Model][0]
        model_1 = Reader().run(path.join(out_path,
                                         'submodel_1.xlsx'))[Model][0]
        model_2 = Reader().run(path.join(out_path,
                                         'submodel_2.xlsx'))[Model][0]

        exp_model_0 = Model(id='model',
                            name='test model',
                            version='0.0.1a',
                            wc_lang_version='0.0.1',
                            created=timestamp,
                            updated=timestamp)
        exp_model_0.references.create(id='ref_0')
        self.assertTrue(model_0.is_equal(exp_model_0))

        exp_model_1 = Model(id='model',
                            name='test model',
                            version='0.0.1a',
                            wc_lang_version='0.0.1',
                            created=timestamp,
                            updated=timestamp)
        exp_model_1.submodels.create(id='submodel_1')
        exp_model_1.references.create(id='ref_1',
                                      submodels=exp_model_1.submodels)
        exp_model_1.references.create(id='ref_3',
                                      submodels=exp_model_1.submodels)
        self.assertTrue(model_1.is_equal(exp_model_1))

        exp_model_2 = Model(id='model',
                            name='test model',
                            version='0.0.1a',
                            wc_lang_version='0.0.1',
                            created=timestamp,
                            updated=timestamp)
        exp_model_2.submodels.create(id='submodel_2')
        exp_model_2.references.create(id='ref_2',
                                      submodels=exp_model_2.submodels)
        exp_model_2.references.create(id='ref_3',
                                      submodels=exp_model_2.submodels)
        self.assertTrue(model_2.is_equal(exp_model_2))
Exemple #23
0
    def test_successful_roundtrip(self):
        """
        Args:
            species_coefficient_creation_method (:obj:`str`): name of method to use to get or create
                an instance of :obj:`wc_lang.SpeciesCoefficient`
        """
        model = Model(id='test_model', version='0.0.0')
        comp = model.compartments.create(id='compartment_1')
        comp.init_density = model.parameters.create(
            id='density_compartment_1',
            value=1100,
            units=unit_registry.parse_units('g l^-1'))
        species_type_1 = model.species_types.create(
            id='species_type_1',
            structure=ChemicalStructure(
                empirical_formula=EmpiricalFormula('CHO'), charge=1))
        species_type_2 = model.species_types.create(
            id='species_type_2',
            structure=ChemicalStructure(
                empirical_formula=EmpiricalFormula('C3H3O3'), charge=3))
        species_1 = comp.species.create(species_type=species_type_1,
                                        model=model)
        species_2 = comp.species.create(species_type=species_type_2,
                                        model=model)
        species_1.id = species_1.gen_id()
        species_2.id = species_2.gen_id()
        submdl = model.submodels.create(id='submodel_1')

        # create a DistributionInitConcentration so that Species are provided to ExpressionAttribute.deserialize()
        species_1.distribution_init_concentration = DistributionInitConcentration(
            model=model, mean=1, units=unit_registry.parse_units('M'))
        species_1.distribution_init_concentration.id = species_1.distribution_init_concentration.gen_id(
        )
        objects = {Species: {}}
        objects[Species][species_1.id] = species_1
        observable_1 = Expression.make_obj(model, Observable, 'observable_1',
                                           species_1.id, objects)
        objects = {Observable: {'observable_1': observable_1}}
        observable_2 = Expression.make_obj(model, Observable, 'observable_2',
                                           'obs_1', objects)

        param_1 = model.parameters.create(
            id='param_1',
            value=1.,
            units=unit_registry.parse_units('dimensionless'))
        param_2 = model.parameters.create(
            id='param_2', value=1., units=unit_registry.parse_units('s^-1'))
        objects = {
            Parameter: {
                'param_1': param_1,
                'param_2': param_2,
            },
        }
        func_1 = Expression.make_obj(model, Function, 'func_1', 'param_1',
                                     objects)
        func_1.units = unit_registry.parse_units('dimensionless')

        rxn_species_coeffs = [
            species_1.species_coefficients.get_or_create(coefficient=-3.),
            species_2.species_coefficients.get_or_create(coefficient=1.),
        ]
        rxn = submdl.reactions.create(id='reaction_1', model=model)
        rxn.participants.extend(rxn_species_coeffs)
        rl = rxn.rate_laws.create(direction=RateLawDirection.forward,
                                  units=unit_registry.parse_units('s^-1'),
                                  model=model)
        rl.id = rl.gen_id()
        rl.expression, error = RateLawExpression.deserialize(
            'param_2', objects)
        self.assertEqual(error, None)

        errors = obj_tables.Validator().run(model, get_related=True)
        self.assertEqual(errors, None, str(errors))

        filename = os.path.join(self.tmp_dir, 'model.xlsx')
        Writer().run(filename, model, data_repo_metadata=False)
        model_2 = Reader().run(filename)[Model][0]

        self.assertEqual(model.difference(model_2), '')
        self.assertTrue(model_2.is_equal(model))
        self.assertTrue(model.is_equal(model_2))
Exemple #24
0
 def setUp(self):
     warnings.simplefilter("ignore")
     self.MODEL_FILENAME = os.path.join(os.path.dirname(__file__), 'fixtures',
                                        'test_submodel_no_shared_species.xlsx')
     self.model = Reader().run(self.MODEL_FILENAME)[Model][0]
Exemple #25
0
class TestDynamicSubmodelStatically(unittest.TestCase):

    def setUp(self, std_init_concentrations=None):

        self.MODEL_FILENAME = os.path.join(os.path.dirname(__file__), 'fixtures',
                                           'test_submodel_no_shared_species.xlsx')
        self.model = Reader().run(self.MODEL_FILENAME)[Model][0]
        prepare_model(self.model)

        if std_init_concentrations is not None:
            for conc in self.model.distribution_init_concentrations:
                conc.std = std_init_concentrations

        self.misconfigured_dynamic_submodels = {}
        self.dynamic_submodels = {}
        for lang_submodel in self.model.get_submodels():
            self.dynamic_submodels[lang_submodel.id] = DynamicSubmodel(
                *make_dynamic_submodel_params(self.model, lang_submodel))

            # create dynamic submodels that lack a dynamic compartment
            id, dynamic_model, reactions, species, dynamic_compartments, local_species_pop = \
                make_dynamic_submodel_params(self.model, lang_submodel)
            dynamic_compartments.popitem()
            self.misconfigured_dynamic_submodels[lang_submodel.id] = DynamicSubmodel(
                id, None, reactions, species, dynamic_compartments, local_species_pop)

    def test_get_state(self):
        for dynamic_submodel in self.dynamic_submodels.values():
            self.assertEqual(dynamic_submodel.get_state(), DynamicSubmodel.GET_STATE_METHOD_MESSAGE)

    def test_get_num_submodels(self):
        for dynamic_submodel in self.dynamic_submodels.values():
            self.assertEqual(dynamic_submodel.get_num_submodels(), 2)

    def expected_molar_conc(self, dynamic_submodel, species_id):
        species = list(filter(lambda s: s.id == species_id, dynamic_submodel.species))[0]
        init_volume = species.compartment.init_volume.mean
        copy_num = ModelUtilities.sample_copy_num_from_concentration(species, init_volume, RandomStateManager.instance())
        volume = dynamic_submodel.dynamic_compartments[species.compartment.id].volume()
        return copy_num / (volume * Avogadro)

    def test_calc_reaction_rates(self):
        # set standard deviation of initial conc. to 0
        self.setUp(std_init_concentrations=0.)
        de_simulation_config = SimulationConfig(time_max=10)
        wc_sim_config = WCSimulationConfig(de_simulation_config, dfba_time_step=1)
        multialgorithm_simulation = MultialgorithmSimulation(self.model, wc_sim_config)
        _, dynamic_model = multialgorithm_simulation.build_simulation()

        # rate law for reaction_4-forward: k_cat_4_for * max(species_4[c], p_4)
        k_cat_4_for = 1
        p_4 = 2
        species_4_c_pop = \
            multialgorithm_simulation.local_species_population.read_one(0, 'species_4[c]')
        expected_rate_reaction_4_forward = k_cat_4_for * max(species_4_c_pop, p_4)
        expected_rates = {
            'reaction_2': 0.0,
            'reaction_4': expected_rate_reaction_4_forward
        }
        for dynamic_submodel in multialgorithm_simulation.dynamic_model.dynamic_submodels.values():
            rates = dynamic_submodel.calc_reaction_rates()
            for index, rxn in enumerate(dynamic_submodel.reactions):
                if rxn.id in expected_rates:
                    self.assertAlmostEqual(list(rates)[index], expected_rates[rxn.id])

    expected_enabled = {
        'submodel_1': set([
            'reaction_1',
            'reaction_2',
            '__dfba_ex_submodel_1_species_1_e',
            '__dfba_ex_submodel_1_species_2_e',
        ]),
        'submodel_2': set([
            'reaction_4',
            'reaction_3_forward',
            'reaction_3_backward',
        ]),
    }

    def test_enabled_reaction(self):
        for dynamic_submodel in self.dynamic_submodels.values():
            enabled = set()
            for rxn in dynamic_submodel.reactions:
                if dynamic_submodel.enabled_reaction(rxn):
                    enabled.add(rxn.id)
            self.assertEqual(TestDynamicSubmodelStatically.expected_enabled[dynamic_submodel.id], enabled)

    def test_identify_enabled_reactions(self):
        for dynamic_submodel in self.dynamic_submodels.values():
            expected_set = TestDynamicSubmodelStatically.expected_enabled[dynamic_submodel.id]
            expected_array =\
                numpy.asarray([r.id in expected_set for r in dynamic_submodel.reactions]).astype(int)
            enabled = dynamic_submodel.identify_enabled_reactions()
            self.assertTrue(numpy.array_equal(enabled, expected_array))

    def test_execute_disabled_reactions(self):
        # test exception by executing reactions that aren't enabled
        enabled_rxn_ids = []
        for set_rxn_ids in TestDynamicSubmodelStatically.expected_enabled.values():
            enabled_rxn_ids.extend(list(set_rxn_ids))
        enabled_reactions = [get_component_by_id(self.model.get_reactions(), rxn_id)
                             for rxn_id in enabled_rxn_ids]
        for dynamic_submodel in self.dynamic_submodels.values():
            for reaction in dynamic_submodel.reactions:
                if reaction not in enabled_reactions:
                    with self.assertRaisesRegex(DynamicMultialgorithmError,
                                                "dynamic submodel .* cannot execute reaction"):
                        dynamic_submodel.execute_reaction(reaction)

    def do_test_execute_reaction(self, reaction_id, expected_adjustments):
        rxn = self.model.get_reactions(id=reaction_id)[0]
        dynamic_submodel = self.dynamic_submodels[rxn.submodel.id]
        before = dynamic_submodel.get_species_counts()
        dynamic_submodel.execute_reaction(rxn)
        after = dynamic_submodel.get_species_counts()
        for species_id, change in expected_adjustments.items():
            self.assertEqual(change, after[species_id] - before[species_id])

    def test_execute_reaction(self):
        # test reactions 'by hand'
        # reversible reactions have been split in two
        self.do_test_execute_reaction('reaction_3_forward',
                                      {'species_2[c]': -1, 'species_4[c]': -2, 'species_5[c]': 1})
        # test reaction in which a species appears multiple times
        self.do_test_execute_reaction('reaction_2', {'species_1[c]': 1, 'species_3[c]': 1})
Exemple #26
0
 def _default(self):
     args = self.app.pargs
     model = Reader().run(args.in_path)[Model][0]
     wc_lang.sbml.io.SbmlWriter().run(model, args.out_dir)
Exemple #27
0
    def test_write_error(self):
        model = Model(id='test_model', version='0.0.0')
        comp = model.compartments.create(id='compartment_1')
        comp.init_density = model.parameters.create(
            id='density_compartment_1',
            value=1100,
            units=unit_registry.parse_units('g l^-1'))
        species_type_1 = model.species_types.create(
            id='species_type_1',
            structure=ChemicalStructure(
                empirical_formula=EmpiricalFormula('CHO'), charge=1))
        species_type_2 = model.species_types.create(
            id='species_type_2',
            structure=ChemicalStructure(
                empirical_formula=EmpiricalFormula('C2H2O2'), charge=2))
        species_1 = comp.species.create(species_type=species_type_1,
                                        id='',
                                        model=model)
        species_2 = comp.species.create(species_type=species_type_2,
                                        id='',
                                        model=model)
        submdl = model.submodels.create(id='submodel_1')

        # create a DistributionInitConcentration so that Species are provided to ExpressionAttribute.deserialize()
        species_1.distribution_init_concentration = DistributionInitConcentration(
            model=model, mean=1, units=unit_registry.parse_units('M'))
        species_1.distribution_init_concentration.id = species_1.distribution_init_concentration.gen_id(
        )
        objects = {Species: {}}
        objects[Species][species_1.id] = species_1
        observable_1 = Expression.make_obj(model, Observable, 'observable_1',
                                           species_1.id, objects)

        rxn_species_coeffs = [
            species_1.species_coefficients.create(coefficient=-2.),
            species_2.species_coefficients.create(coefficient=1.),
        ]
        rxn = submdl.reactions.create(id='reaction_1', model=model)
        rxn.participants.extend(rxn_species_coeffs)
        rl = rxn.rate_laws.create(direction=RateLawDirection.forward,
                                  units=unit_registry.parse_units('s^-1'),
                                  model=model)
        rl.id = rl.gen_id()
        param_1 = model.parameters.create(
            id='param_1', value=1., units=unit_registry.parse_units('s^-1'))
        rl.expression, error = RateLawExpression.deserialize(
            'param_1', {Parameter: {
                'param_1': param_1
            }})
        self.assertEqual(error, None)

        errors = obj_tables.Validator().run(model, get_related=True)
        self.assertNotEqual(errors, None)

        filename = os.path.join(self.tmp_dir, 'model.xlsx')
        with pytest.warns(obj_tables.io.IoWarning,
                          match='objects are not valid'):
            Writer().run(filename, model, data_repo_metadata=False)
        with self.assertRaisesRegex(ValueError,
                                    re.escape('contains error(s)')):
            Reader().run(filename)
Exemple #28
0
class TestInitialDynamicComponentsComprehensively(unittest.TestCase):
    def setUp(self):
        self.model_file = os.path.join(os.path.dirname(__file__), 'fixtures',
                                       'test_dynamic_expressions.xlsx')
        self.model = Reader().run(self.model_file)[Model][0]
        de_simulation_config = SimulationConfig(time_max=10)
        wc_sim_config = WCSimulationConfig(de_simulation_config)
        multialgorithm_simulation = MultialgorithmSimulation(
            self.model, wc_sim_config)
        _, self.dynamic_model = multialgorithm_simulation.build_simulation()

    def test(self):
        # test all DynamicComponents that implement eval()

        ### Test DynamicExpressions ###
        # each one is tested using each of the objects it uses in some instance in self.model_file
        # DynamicFunction
        for id, dynamic_function in self.dynamic_model.dynamic_functions.items(
        ):
            expected_value = float(self.model.get_functions(id=id)[0].comments)
            numpy.testing.assert_approx_equal(dynamic_function.eval(0),
                                              expected_value)
        # test eval_dynamic_functions()
        for func_id, func_val in self.dynamic_model.eval_dynamic_functions(
                0).items():
            expected_value = float(
                self.model.get_functions(id=func_id)[0].comments)
            numpy.testing.assert_approx_equal(func_val, expected_value)
        a_func_id = list(self.dynamic_model.dynamic_functions)[0]
        for func_id, func_val in \
            self.dynamic_model.eval_dynamic_functions(0, functions_to_eval=[a_func_id]).items():
            expected_value = float(
                self.model.get_functions(id=func_id)[0].comments)
            numpy.testing.assert_approx_equal(func_val, expected_value)

        # DynamicStopCondition
        for id, dynamic_stop_condition in self.dynamic_model.dynamic_stop_conditions.items(
        ):
            expected_val_in_comment = self.model.get_stop_conditions(
                id=id)[0].comments
            if expected_val_in_comment == 'True':
                expected_value = True
            elif expected_val_in_comment == 'False':
                expected_value = False
            self.assertEqual(expected_value, dynamic_stop_condition.eval(0))

        # DynamicObservable
        for id, dynamic_observable in self.dynamic_model.dynamic_observables.items(
        ):
            expected_value = float(
                self.model.get_observables(id=id)[0].comments)
            numpy.testing.assert_approx_equal(dynamic_observable.eval(0),
                                              expected_value)
        # test eval_dynamic_observables()
        for obs_id, obs_val in self.dynamic_model.eval_dynamic_observables(
                0).items():
            expected_value = float(
                self.model.get_observables(id=obs_id)[0].comments)
            numpy.testing.assert_approx_equal(obs_val, expected_value)
        an_obs_id = list(self.dynamic_model.dynamic_observables)[0]
        for obs_id, obs_val in \
            self.dynamic_model.eval_dynamic_observables(0, observables_to_eval=[an_obs_id]).items():
            expected_value = float(
                self.model.get_observables(id=obs_id)[0].comments)
            numpy.testing.assert_approx_equal(obs_val, expected_value)

        # DynamicRateLaw
        for id, dynamic_rate_law in self.dynamic_model.dynamic_rate_laws.items(
        ):
            expected_value = float(self.model.get_rate_laws(id=id)[0].comments)
            numpy.testing.assert_approx_equal(dynamic_rate_law.eval(0),
                                              expected_value)

        ### Test DynamicComponents ###
        # DynamicCompartment
        for id, dynamic_compartment in self.dynamic_model.dynamic_compartments.items(
        ):
            expected_value = float(
                self.model.get_compartments(id=id)[0].comments)
            numpy.testing.assert_approx_equal(dynamic_compartment.eval(0),
                                              expected_value)

        # DynamicParameter
        for id, dynamic_parameter in self.dynamic_model.dynamic_parameters.items(
        ):
            expected_value = float(
                self.model.get_parameters(id=id)[0].comments)
            numpy.testing.assert_approx_equal(dynamic_parameter.eval(0),
                                              expected_value)

        # DynamicSpecies
        for id, dynamic_species in self.dynamic_model.dynamic_species.items():
            expected_value = float(self.model.get_species(id=id)[0].comments)
            numpy.testing.assert_approx_equal(dynamic_species.eval(0),
                                              expected_value)

    # FIX FOR DE-SIM CHANGES: need to make a few dynamic models to test all branches of get_stop_condition()
    # a dynamic model with no stop concitions
    # a dynamic model with stop condidtions that all evaluate false
    # a dynamic model with at least one stop condidtions that evaluates true
    def test_get_stop_condition(self):
        all_stop_conditions = self.dynamic_model.get_stop_condition()
        self.assertTrue(callable(all_stop_conditions))
        self.assertTrue(all_stop_conditions(0))