Example #1
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,
                'The model cannot be loaded because it fails to validate'):
            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)
Example #2
0
    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)
Example #3
0
    def test_read_write(self):
        fixture_filename = os.path.join(os.path.dirname(__file__), 'fixtures', 'example-model.xlsx')

        model = Reader().run(fixture_filename)[Model][0]
        self.assertEqual(model.validate(), None)

        # compare excel files
        Writer().run(self.filename, model, data_repo_metadata=False)
        original = read_workbook(fixture_filename)
        copy = read_workbook(self.filename)
        remove_ws_metadata(original)
        remove_ws_metadata(copy)
        original.pop('!!' + obj_tables.core.TOC_SHEET_NAME)
        copy.pop('!!' + obj_tables.core.TOC_SHEET_NAME)

        # note that models must be sorted by id for this assertion to hold
        for sheet in original.keys():
            for i_row, (copy_row, original_row) in enumerate(zip(copy[sheet], original[sheet])):
                self.assertEqual(copy_row, original_row,
                                 msg='Rows {} of {} sheets are not equal'.format(i_row, sheet))
            self.assertEqual(copy[sheet], original[sheet], msg='{} sheets are not equal'.format(sheet))

        self.assertEqual(copy, original)

        # compare models
        model2 = Reader().run(self.filename)[Model][0]
        self.assertTrue(model2.is_equal(model))
        self.assertTrue(model.difference(model2) == '')
Example #4
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)
Example #5
0
    def test_write_read(self):
        filename = os.path.join(self.tempdir, 'model.xlsx')

        Writer().run(filename, self.model, data_repo_metadata=False)
        model = Reader().run(filename)[Model][0]
        self.assertEqual(model.validate(), None)

        self.assertTrue(model.is_equal(self.model))
        self.assertEqual(self.model.difference(model), '')
Example #6
0
    def test(self):
        test_model = Model(id='model', version='0.0.1', wc_lang_version='0.0.1')
        submodel = test_model.submodels.create(id='submodel')

        filename_yaml = os.path.join(self.tempdir, 'model.yaml')
        Writer().run(filename_yaml, test_model)
        model = Reader().run(filename_yaml)[Model][0]
        self.assertEqual(model.validate(), None)

        self.assertTrue(model.is_equal(test_model))
        self.assertEqual(test_model.difference(model), '')
Example #7
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), '')
Example #8
0
    def test_convert_to_sbml(self):
        from wc_lang.sbml import io as sbml_io
        from wc_lang.io import Reader, Writer
        from wc_sim.testing.utils import read_model_for_test
        for model_name in self.models:
            print(f'converting {model_name}')
            dirname = os.path.join(os.path.dirname(__file__), 'fixtures', 'dynamic_tests')
            model_filename = os.path.join(dirname, f'{model_name}.xlsx')
            integration_framework = 'ordinary_differential_equations'
            model = read_model_for_test(model_filename, integration_framework=f'WC:{integration_framework}')

            # write wc_lang file
            sbml_dirname = os.path.join(dirname, f'{model_name}_sbml')
            if not os.path.isdir(sbml_dirname):
                os.makedirs(sbml_dirname)

            lang_filename = os.path.join(sbml_dirname, f'{model_name}.xlsx')
            print(f'writing {lang_filename}')
            Writer().run(lang_filename, model)
            model_from_file = Reader().run(lang_filename)[Model][0]
            assert model_from_file.validate() is None

            # write SBML file
            sbml_io.SbmlWriter().run(model_from_file, sbml_dirname)
Example #9
0
    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)