Example #1
0
    def test_version_selection(self):
        # Test choosing between CellML versions

        e = formats.exporter('cellml')
        model = myokit.Model('hello')
        t = model.add_component('env').add_variable('time')
        t.set_binding('time')
        t.set_rhs(0)

        # Write to 1.0 model
        with TemporaryDirectory() as d:
            path = d.path('test.cellml')
            e.model(path, model, version='1.0')
            with open(path, 'r') as f:
                self.assertIn('cellml/1.0#', f.read())

        # Write to 1.1 model
        with TemporaryDirectory() as d:
            path = d.path('test.cellml')
            e.model(path, model, version='1.1')
            with open(path, 'r') as f:
                self.assertIn('cellml/1.1#', f.read())

        # Write to 2.0 model
        with TemporaryDirectory() as d:
            path = d.path('test.cellml')
            e.model(path, model, version='2.0')
            with open(path, 'r') as f:
                self.assertIn('cellml/2.0#', f.read())
Example #2
0
    def test_file_writing_no_screen_txt(self):
        # Repeat without screen output, outside of csv mode
        with StreamCapture() as c:
            with TemporaryDirectory() as d:
                filename = d.path('test.csv')
                log = pints.Logger()
                log.set_filename(filename, csv=False)
                log.set_stream(None)
                log.add_counter('#', width=2)
                log.add_float('Lat.', width=1)
                log.add_long_float('Number', file_only=True)
                log.add_int('Val', width=4)
                log.add_counter('Count', max_value=12345)
                log.add_time('Time')
                log.add_string('Q', 3)
                log.log(*data)
                with open(filename, 'r') as f:
                    out = f.read()
        self.assertOutput(expected='', returned=c.text())
        self.assertOutput(expected=out3, returned=out)

        # Unset file output
        with StreamCapture() as c:
            with TemporaryDirectory() as d:
                filename = d.path('test.csv')
                log = pints.Logger()
                log.set_filename(filename, csv=False)
                log.set_filename(None)
                log.set_stream(None)
                log.add_counter('#', width=2)
                log.log(1)
                self.assertFalse(os.path.isfile(filename))
        self.assertOutput(expected='', returned=c.text())
        self.assertOutput(expected=out3, returned=out)
Example #3
0
 def test_multiline_string_indent(self):
     """
     Test what happens when you load save a string that gets auto-indented.
     """
     # Create model with multi-line meta-data property
     d1 = 'First line\n\nSecond line'
     m1 = myokit.Model()
     m1.meta['desc'] = d1
     e = m1.add_component('engine')
     v = e.add_variable('time')
     v.set_binding('time')
     v.set_rhs(0)
     # Store to disk
     with TemporaryDirectory() as d:
         opath = d.path('multiline.mmt')
         myokit.save_model(opath, m1)
         # Load and compare the meta-data string
         m2 = myokit.load_model(opath)
         d2 = m2.meta['desc']
         self.assertEqual(d1, d2)
     # Create model with indented multi-line meta-data property
     d1 = '  First line\n\n  Second line'
     dr = 'First line\n\nSecond line'
     m1 = myokit.Model()
     m1.meta['desc'] = d1
     e = m1.add_component('engine')
     v = e.add_variable('time')
     v.set_binding('time')
     v.set_rhs(0)
     # Store to disk
     with TemporaryDirectory() as d:
         opath = d.path('multiline.mmt')
         myokit.save_model(opath, m1)
         # Load and compare the meta-data string
         m2 = myokit.load_model(opath)
         d2 = m2.meta['desc']
         self.assertEqual(d2, dr)
     # Create model with strangely indented multi-line meta-data property
     d1 = '  First line\n\n   Second line'
     dr = 'First line\n\n Second line'
     m1 = myokit.Model()
     m1.meta['desc'] = d1
     e = m1.add_component('engine')
     v = e.add_variable('time')
     v.set_binding('time')
     v.set_rhs(0)
     # Store to disk
     with TemporaryDirectory() as d:
         opath = d.path('multiline.mmt')
         myokit.save_model(opath, m1)
         # Load and compare the meta-data string
         m2 = myokit.load_model(opath)
         d2 = m2.meta['desc']
         self.assertEqual(d2, dr)
Example #4
0
    def test_easyml_exporter(self):
        # Tests exporting a model

        model1 = myokit.load_model('example')
        model2 = myokit.load_model(os.path.join(DIR_DATA, 'heijman-2011.mmt'))
        e = myokit.formats.easyml.EasyMLExporter()

        with TemporaryDirectory() as d:
            path = d.path('easy.model')

            # Test with simple model
            e.model(path, model1)

            # Test with model containing markov models
            with WarningCollector() as c:
                e.model(path, model2)
            self.assertIn('unsupported function: atan', c.text())
            self.assertIn('unsupported function: sin', c.text())
            self.assertEqual(c.count(), 6)

            # Test with extra bound variables
            model1.get('membrane.C').set_binding('hello')
            e.model(path, model1)

            # Test without V being a state variable
            v = model1.get('membrane.V')
            v.demote()
            v.set_rhs(3)
            e.model(path, model1)

            # Test with invalid model
            v.set_rhs('2 * V')
            self.assertRaisesRegex(myokit.ExportError, 'valid model', e.model,
                                   path, model1)
Example #5
0
    def test_save_frame_csv(self):
        # Test the save_frame_csv() method.

        w, h = 2, 3
        time = [1, 2, 3]
        b = myokit.DataBlock2d(w, h, time)
        x = np.array([  # Each 3 by 2 array is a point in time
            [[0, 1], [2, 3], [4, 5]],
            [[5, 4], [3, 2], [1, 0]],
            [[0, 0], [0, 0], [0, 0]],
        ])
        b.set2d('x', x)

        with TemporaryDirectory() as d:
            path = d.path('test.csv')
            b.save_frame_csv(path, 'x', 0)
            with open(path, 'r') as f:
                lines = [str(x) for x in f.readlines()]
            self.assertEqual(lines[0], '"x","y","value"\n')
            self.assertEqual(lines[1], '0,0,0\n')
            self.assertEqual(lines[2], '1,0,1\n')
            self.assertEqual(lines[3], '0,1,2\n')
            self.assertEqual(lines[4], '1,1,3\n')
            self.assertEqual(lines[5], '0,2,4\n')
            self.assertEqual(lines[6], '1,2,5')
Example #6
0
 def test_save_model(self):
     """
     Test if the correct parts are saved/loaded from disk using the
     ``save_model()`` method.
     """
     ipath = os.path.join(DIR_DATA, 'lr-1991.mmt')
     # Test example loading
     m = myokit.load_model('example')
     self.assertIsInstance(m, myokit.Model)
     # Test file loading
     m = myokit.load_model(ipath)
     self.assertIsInstance(m, myokit.Model)
     with TemporaryDirectory() as d:
         opath = d.path('loadsave.mmt')
         myokit.save_model(opath, m)
         # Test no other parts were written
         with open(opath, 'r') as f:
             text = f.read()
         self.assertTrue('[[model]]' in text)
         self.assertFalse('[[protocol]]' in text)
         self.assertFalse('[[script]]' in text)
         # Test reloading
         mm = myokit.load_model(opath)
         self.assertIsInstance(mm, myokit.Model)
         self.assertEqual(mm.code(), m.code())
Example #7
0
    def test_pack_snapshot(self):
        # Test if the pack_snapshot method runs without exceptions.

        with TemporaryDirectory() as d:
            # Run!
            path = d.path('pack.zip')
            new_path = myokit.pack_snapshot(path)
            self.assertTrue(os.path.isfile(new_path))
            self.assertTrue(os.path.getsize(new_path) > 500000)

            # Run with same location --> error
            self.assertRaises(IOError,
                              myokit.pack_snapshot,
                              path,
                              overwrite=False)

            # Run with overwrite switch is ok
            myokit.pack_snapshot(path, overwrite=True)

            # Write to directory: finds own filename
            path = d.path('')
            new_path = myokit.pack_snapshot(path)
            self.assertEqual(new_path[:len(path)], path)
            self.assertTrue(len(new_path) - len(path) > 5)

            # Write to directory again without overwrite --> error
            self.assertRaises(IOError,
                              myokit.pack_snapshot,
                              path,
                              overwrite=False)

            # Run with overwrite switch is ok
            myokit.pack_snapshot(path, overwrite=True)
Example #8
0
 def test_save_script(self):
     """
     Test if the correct parts are saved/loaded from disk using the
     ``save_script()`` method.
     """
     ipath = os.path.join(DIR_DATA, 'lr-1991.mmt')
     # Test example loading
     x = myokit.load_script('example')
     self.assertTrue(isinstance(x, basestring))
     # Test file loading
     x = myokit.load_script(ipath)
     self.assertTrue(isinstance(x, basestring))
     with TemporaryDirectory() as d:
         opath = d.path('test.mmt')
         myokit.save_script(opath, x)
         # Test no other parts were written
         with open(opath, 'r') as f:
             text = f.read()
         self.assertFalse('[[model]]' in text)
         self.assertFalse('[[protocol]]' in text)
         self.assertTrue('[[script]]' in text)
         # Test reloading
         xx = myokit.load_script(opath)
         self.assertTrue(isinstance(xx, basestring))
         self.assertEqual(x, xx)
Example #9
0
    def test_no_output(self):
        # Repeat without any output
        with StreamCapture() as c:
            log = pints.Logger()
            log.set_stream(None)
            log.add_counter('#', width=2)
            log.add_float('Lat.', width=1)
            log.add_long_float('Number', file_only=True)
            log.add_int('Val', width=4)
            log.add_counter('Count', max_value=12345)
            log.add_time('Time')
            log.add_string('Q', 3)
            log.log(*data)
        self.assertOutput(expected='', returned=c.text())

        # Repeat on stderr
        with StreamCapture(stdout=True, stderr=True) as c:
            with TemporaryDirectory() as d:
                filename = d.path('test.csv')
                log = pints.Logger()
                log.set_filename(filename, csv=False)
                log.set_stream(sys.stderr)
                log.add_counter('#', width=2)
                log.add_float('Lat.', width=1)
                log.add_long_float('Number', file_only=True)
                log.add_int('Val', width=4)
                log.add_counter('Count', max_value=12345)
                log.add_time('Time')
                log.add_string('Q', 3)
                log.log(*data)
                with open(filename, 'r') as f:
                    out = f.read()
        self.assertOutput(expected='', returned=c.text()[0])
        self.assertOutput(expected=out2, returned=c.text()[1])
        self.assertOutput(expected=out3, returned=out)
Example #10
0
    def test_export_reused_variable(self):
        # Tests exporting when an `inf` or other special variable is used twice

        # Create model re-using tau and inf
        m = myokit.parse_model("""
            [[model]]
            m.V = -80
            c.x = 0.1
            c.y = 0.1

            [m]
            time = 0 bind time
            i_ion = c.I
            dot(V) = -i_ion

            [c]
            inf = 0.5
            tau = 3
            dot(x) = (inf - x) / tau
            dot(y) = (inf - y) / tau
            I = x * y * (m.V - 50)
            """)

        # Export, and read back in
        e = myokit.formats.easyml.EasyMLExporter()
        with TemporaryDirectory() as d:
            path = d.path('easy.model')
            e.model(path, m)
            with open(path, 'r') as f:
                x = f.read()

        self.assertIn('x_inf =', x)
        self.assertIn('y_inf =', x)
        self.assertIn('tau_x =', x)
        self.assertIn('tau_y =', x)
Example #11
0
    def test_logging(self):
        """ Tests logging to screen and file. """

        # No logging
        with StreamCapture() as c:
            sampler = pints.NestedEllipsoidSampler(self.log_likelihood,
                                                   self.log_prior)
            sampler.set_posterior_samples(2)
            sampler.set_rejection_samples(5)
            sampler.set_iterations(10)
            sampler.set_active_points_rate(10)
            sampler.set_log_to_screen(False)
            sampler.set_log_to_file(False)
            samples, margin = sampler.run()
        self.assertEqual(c.text(), '')

        # Log to screen
        with StreamCapture() as c:
            sampler = pints.NestedEllipsoidSampler(self.log_likelihood,
                                                   self.log_prior)
            sampler.set_posterior_samples(2)
            sampler.set_rejection_samples(5)
            sampler.set_iterations(20)
            sampler.set_active_points_rate(10)
            sampler.set_log_to_screen(True)
            sampler.set_log_to_file(False)
            samples, margin = sampler.run()
        lines = c.text().splitlines()
        self.assertEqual(lines[0], 'Running nested rejection sampling')
        self.assertEqual(lines[1], 'Number of active points: 10')
        self.assertEqual(lines[2], 'Total number of iterations: 20')
        self.assertEqual(lines[3], 'Enlargement factor: 1.5')
        self.assertEqual(lines[4], 'Total number of posterior samples: 2')
        self.assertEqual(lines[5], 'Iter. Eval. Time m:s')
        pattern = re.compile('[0-9]+[ ]+[0-9]+[ ]+[0-9]{1}:[0-9]{2}.[0-9]{1}')
        for line in lines[6:]:
            self.assertTrue(pattern.match(line))
        self.assertEqual(len(lines), 12)

        # Log to file
        with StreamCapture() as c:
            with TemporaryDirectory() as d:
                filename = d.path('test.txt')
                sampler = pints.NestedEllipsoidSampler(self.log_likelihood,
                                                       self.log_prior)
                sampler.set_posterior_samples(2)
                sampler.set_rejection_samples(5)
                sampler.set_iterations(10)
                sampler.set_active_points_rate(10)
                sampler.set_log_to_screen(False)
                sampler.set_log_to_file(filename)
                samples, margin = sampler.run()
                with open(filename, 'r') as f:
                    lines = f.read().splitlines()
            self.assertEqual(c.text(), '')
        self.assertEqual(len(lines), 6)
        self.assertEqual(lines[0], 'Iter. Eval. Time m:s')
        pattern = re.compile('[0-9]+[ ]+[0-9]+[ ]+[0-9]{1}:[0-9]{2}.[0-9]{1}')
        for line in lines[5:]:
            self.assertTrue(pattern.match(line))
Example #12
0
    def test_warnings_1_0(self):
        # Tests warnings are logged

        # Create model that will generate warnings
        x = ('<?xml version="1.0" encoding="UTF-8"?>'
             '<model name="test" xmlns="http://www.cellml.org/cellml/1.0#">'
             '<component name="a">'
             '  <variable name="hello" units="ampere"'
             '            public_interface="in"/>'
             '</component>'
             '</model>')

        # Write to disk and import
        with TemporaryDirectory() as d:
            path = d.path('test.celllml')
            with open(path, 'w') as f:
                f.write(x)

            # Import
            i = formats.importer('cellml')
            with WarningCollector() as w:
                i.model(path)

            # Check warning was raised
            self.assertIn('not connected', w.text())
Example #13
0
    def test_temporary_directory(self):
        """
        Tests the temporary directory class.
        """
        with TemporaryDirectory() as d:
            # Test dir creation
            tempdir = d.path('')
            self.assertTrue(os.path.isdir(tempdir))

            # Test file creation
            text = 'Hello\nWorld'
            filename = d.path('test.txt')
            with open(filename, 'w') as f:
                f.write(text)
            with open(filename, 'r') as f:
                self.assertTrue(f.read() == text)
            self.assertTrue(os.path.isfile(filename))

            # Test invalid file creation
            self.assertRaises(ValueError, d.path, '../illegal.txt')

        # Test file and dir removal
        self.assertFalse(os.path.isfile(filename))
        self.assertFalse(os.path.isdir(tempdir))

        # Test runtime error when used outside of context
        self.assertRaises(RuntimeError, d.path, 'hello.txt')
Example #14
0
    def test_stan_exporter(self):
        # Basic test
        self._test(myokit.formats.exporter('stan'))

        # Test with parameters and output variable specified

        # Load model
        m = myokit.load_model('example')

        # Guess parameters
        parameters = []
        for v in m.get('ina').variables(const=True):
            if v.name()[:1] == 'p':
                parameters.append(v)
        parameters.sort(key=lambda v: myokit._natural_sort_key(v.name()))

        # Set output
        output = 'ina.INa'

        # Export to stan
        e = myokit.formats.stan.StanExporter()
        with TemporaryDirectory() as d:
            dpath = d.path('out')
            ret = e.runnable(dpath, m, parameters=parameters, output=output)
            self.assertIsNone(ret)
            self.assertTrue(os.path.isdir(dpath))
            self.assertTrue(len(os.listdir(dpath)) > 0)
Example #15
0
    def test_logging(self):
        # Tests logging to screen and file.

        # No logging
        with StreamCapture() as c:
            sampler = pints.NestedController(self.log_likelihood,
                                             self.log_prior)
            sampler.set_n_posterior_samples(2)
            sampler.set_iterations(10)
            sampler.set_log_to_screen(False)
            sampler.set_log_to_file(False)
            samples, margin = sampler.run()
        self.assertEqual(c.text(), '')

        # Log to screen
        with StreamCapture() as c:
            sampler = pints.NestedController(self.log_likelihood,
                                             self.log_prior)
            sampler.set_n_posterior_samples(2)
            sampler.set_iterations(20)
            sampler.set_log_to_screen(True)
            sampler.set_log_to_file(False)
            samples, margin = sampler.run()
        lines = c.text().splitlines()
        self.assertEqual(lines[0], 'Running Nested ellipsoidal sampler')
        self.assertEqual(lines[1], 'Number of active points: 400')
        self.assertEqual(lines[2], 'Total number of iterations: 20')
        self.assertEqual(lines[3], 'Total number of posterior samples: 2')
        self.assertEqual(
            lines[4],
            ('Iter. Eval. Time m:s Delta_log(z) ' + 'Acceptance rate'))
        pattern = re.compile('[0-9]+[ ]+[0-9]+[ ]+[0-9]{1}:[0-9]{2}.[0-9]{1}')
        for line in lines[5:]:
            self.assertTrue(pattern.match(line))
        self.assertEqual(len(lines), 28)

        # Log to file
        with StreamCapture() as c:
            with TemporaryDirectory() as d:
                filename = d.path('test.txt')
                sampler = pints.NestedController(self.log_likelihood,
                                                 self.log_prior)
                sampler.set_n_posterior_samples(2)
                sampler.set_iterations(10)
                sampler.set_log_to_screen(False)
                sampler.set_log_to_file(filename)
                samples, margin = sampler.run()
                with open(filename, 'r') as f:
                    lines = f.read().splitlines()
            self.assertEqual(c.text(), '')
        self.assertEqual(len(lines), 23)
        self.assertEqual(
            lines[0],
            ('Iter. Eval. Time m:s Delta_log(z) ' + 'Acceptance rate'))
        pattern = re.compile('[0-9]+[ ]+[0-9]+[ ]+[0-9]{1}:[0-9]{2}.[0-9]{1}')
        for line in lines[5:]:
            self.assertTrue(pattern.match(line))
Example #16
0
    def test_stimulus_generation(self):
        # Tests if protocols allow a stimulus current to be added

        e = formats.exporter('cellml')
        i = formats.importer('cellml')

        # Load input model
        m1, p1, _ = myokit.load('example')
        org_code = m1.code()

        # 1. Export without a protocol
        with TemporaryDirectory() as d:
            path = d.path('model.cellml')
            with WarningCollector() as w:
                e.model(path, m1)
            m2 = i.model(path)
        self.assertFalse(w.has_warnings())
        self.assertTrue(isinstance(m2.get('engine.pace').rhs(), myokit.Number))

        # 2. Export with protocol, but without variable bound to pacing
        m1.get('engine.pace').set_binding(None)
        with TemporaryDirectory() as d:
            path = d.path('model.cellml')
            with WarningCollector() as w:
                e.model(path, m1, p1)
            m2 = i.model(path)
        self.assertTrue(w.has_warnings())
        self.assertTrue(isinstance(m2.get('engine.pace').rhs(), myokit.Number))

        # 3. Export with protocol and variable bound to pacing
        m1.get('engine.pace').set_binding('pace')
        with TemporaryDirectory() as d:
            path = d.path('model.cellml')
            with WarningCollector() as w:
                e.model(path, m1, p1)
            m2 = i.model(path)
        self.assertFalse(w.has_warnings())
        rhs = m2.get('membrane.i_stim').rhs()
        self.assertTrue(rhs, myokit.Multiply)
        self.assertTrue(isinstance(rhs[0], myokit.Piecewise))

        # Check original model is unchanged
        self.assertEqual(org_code, m1.code())
Example #17
0
 def parse_in_file(self, xml):
     """
     Inserts the given ``xml`` into a <model> element, writes it to a
     temporary file, parses it, and returns the result.
     """
     with TemporaryDirectory() as d:
         path = d.path('test.cellml')
         with open(path, 'w') as f:
             f.write(self.wrap(xml))
         return v1.parse_file(path)
Example #18
0
    def test_write_file(self):
        # Tests write_file

        m1 = cellml.Model('ernie')
        with TemporaryDirectory() as d:
            path = d.path('test.cellml')
            cellml.write_file(path, m1)
            m2 = cellml.parse_file(path)

        self.assertEqual(m2.name(), 'ernie')
        self.assertEqual(len(m2), 0)
Example #19
0
    def test_accessors(self):
        # Test various accessor methods of :class:`AtfFile`.

        with TemporaryDirectory() as d:
            # Create data log
            log = myokit.DataLog()
            log.set_time_key('time')
            log['time'] = np.arange(10)
            log['sint'] = np.sin(log['time'])
            log['cost'] = np.cos(log['time'])

            # Write atf file
            path = d.path('test.atf')
            axon.save_atf(log, path)

            # Read atf file
            atf = myokit.formats.axon.AtfFile(path)

            # Test filename()
            self.assertEqual(atf.filename(), path)

            # Test iter and getitem
            self.assertEqual(len(list(iter(atf))), 3)
            self.assertTrue(np.all(atf['time'] == log['time']))
            self.assertTrue(np.all(atf['sint'] == log['sint']))
            self.assertTrue(np.all(atf['cost'] == log['cost']))

            # Test items()
            items = list(atf.items())
            self.assertEqual(items[0][0], 'time')
            self.assertEqual(items[1][0], 'sint')
            self.assertEqual(items[2][0], 'cost')
            self.assertTrue(np.all(items[0][1] == log['time']))
            self.assertTrue(np.all(items[1][1] == log['sint']))
            self.assertTrue(np.all(items[2][1] == log['cost']))

            # Test keys()
            self.assertEqual(list(atf.keys()), ['time', 'sint', 'cost'])

            # Test values()
            values = list(atf.values())
            self.assertTrue(np.all(values[0] == log['time']))
            self.assertTrue(np.all(values[1] == log['sint']))
            self.assertTrue(np.all(values[2] == log['cost']))

            # Test len
            self.assertEqual(len(atf), 3)

            # Test info
            self.assertIn('myokit', atf.info())

            # Test version
            self.assertEqual(atf.version(), '1.0')
Example #20
0
    def test_version_specific_exporters(self):
        # Test the aliased exporters for specific versions

        model = myokit.Model('hello')
        t = model.add_component('env').add_variable('time')
        t.set_binding('time')
        t.set_rhs(0)

        # Write to 1.0 model
        e = formats.exporter('cellml1')
        with TemporaryDirectory() as d:
            path = d.path('test.cellml')
            e.model(path, model)
            with open(path, 'r') as f:
                self.assertIn('cellml/1.0#', f.read())

        # Write to 2.0 model
        e = formats.exporter('cellml2')
        with TemporaryDirectory() as d:
            path = d.path('test.cellml')
            e.model(path, model)
            with open(path, 'r') as f:
                self.assertIn('cellml/2.0#', f.read())
Example #21
0
    def test_load_save_state(self):
        # Test :meth:`Model.save_state()` and :meth:`Model.load_state()`.

        m = myokit.load_model('example')
        s1 = m.state()
        with TemporaryDirectory() as d:
            path = d.path('state.csv')
            m.save_state(path)
            self.assertEqual(m.state(), s1)
            sx = list(s1)
            sx[0] = 10
            m.set_state(sx)
            self.assertNotEqual(m.state(), s1)
            m.load_state(path)
            self.assertEqual(m.state(), s1)
Example #22
0
    def test_load_save_state_bin(self):
        """ Test loading/saving state in binary format. """
        m, p, x = myokit.load('example')
        with TemporaryDirectory() as d:

            # Test save and load with double precision
            f = d.path('state.bin')
            myokit.save_state_bin(f, m.state())
            self.assertEqual(myokit.load_state_bin(f), m.state())

            # Test save and load with single precision
            f = d.path('state.bin')
            myokit.save_state_bin(f, m.state(), myokit.SINGLE_PRECISION)
            d = np.array(myokit.load_state_bin(f)) - np.array(m.state())
            self.assertTrue(np.all(np.abs(d) < 1e-5))  # Not very precise!
Example #23
0
        def run(chains):

            # Filter nones to get expected output
            expected = np.array([[x for x in chain if x is not None]
                                 for chain in chains])

            # Get initial position
            x0 = [chain[0] for chain in chains]

            # Create log pdf
            f = SumDistribution(len(x0[0]))

            # Get expected evaluations
            exp_evals = np.array([[[f(x)] for x in chain]
                                  for chain in expected])

            # Set up controller
            nc = len(x0)
            mcmc = pints.MCMCController(f, nc, x0, method=SingleListSampler)
            mcmc.set_log_to_screen(False)
            mcmc.set_max_iterations(len(expected[0]))

            # Pass chains to samplers
            for i, sampler in enumerate(mcmc.samplers()):
                sampler.set_chain(chains[i])

            # Run, while logging to disk
            with TemporaryDirectory() as d:
                # Store chains
                chain_path = d.path('chain.csv')
                mcmc.set_chain_filename(chain_path)

                # Store log pdfs
                evals_path = d.path('evals.csv')
                mcmc.set_log_pdf_filename(evals_path)

                # Run
                obtained = mcmc.run()

                # Load chains and log_pdfs
                disk_samples = np.array(pints.io.load_samples(chain_path, nc))
                disk_evals = np.array(pints.io.load_samples(evals_path, nc))

            # Return expected and obtained values
            return expected, obtained, disk_samples, exp_evals, disk_evals
Example #24
0
    def test_create(self):
        """
        Test if the `_create` method works.
        """
        # Import hidden _config module
        path = sys.path
        try:
            sys.path.append(myokit.DIR_MYOKIT)
            import _config as config
        finally:
            sys.path = path

        # Test _create
        with TemporaryDirectory() as d:
            filename = d.path('test.ini')
            config._create(filename)
            self.assertTrue(os.path.isfile(filename))
        self.assertFalse(os.path.isfile(filename))
Example #25
0
 def test_file_writing_csv(self):
     # Repeat in csv mode
     with StreamCapture() as c:
         with TemporaryDirectory() as d:
             filename = d.path('test.csv')
             log = pints.Logger()
             log.set_filename(filename, csv=True)
             log.add_counter('#', width=2)
             log.add_float('Lat.', width=1)
             log.add_long_float('Number', file_only=True)
             log.add_int('Val', width=4)
             log.add_counter('Count', max_value=12345)
             log.add_time('Time')
             log.add_string('Q', 3)
             log.log(*data)
             with open(filename, 'r') as f:
                 out = f.read()
     self.assertOutput(expected=out2, returned=c.text())
     self.assertOutput(expected=out4, returned=out)
Example #26
0
 def e(self, template, args, expected_error=None):
     """
     Runs a template, if an error is expected it checks if it's the right
     one.
     """
     with TemporaryDirectory() as d:
         path = d.path('template')
         with open(path, 'w') as f:
             f.write(template)
         e = myokit.pype.TemplateEngine()
         if expected_error is None:
             e.process(path, args)
         else:
             try:
                 e.process(path, args)
             except myokit.pype.PypeError:
                 # Check expected message in error details
                 self.assertIn(expected_error, e.error_details())
                 return
             raise RuntimeError('PypeError not raised.')
Example #27
0
    def test_writable_dir(self):
        """
        Test :meth:`_test_writable_dir` for existing paths.
        """
        m, p, x = myokit.load('example')
        e = myokit.formats.exporter('ansic')
        with TemporaryDirectory() as d:

            # Create in new dir
            path = d.path('new-dir')
            e.runnable(path, m, p)

            # Create again, in same dir (should be ok)
            e.runnable(path, m, p)

            # Create at location of file: not allowed!
            path = d.path('file')
            with open(path, 'w') as f:
                f.write('Hello')
            self.assertRaisesRegex(
                myokit.ExportError, 'file exists', e.runnable, path, m, p)
Example #28
0
    def test_load_save_state(self):
        """ Test loading/saving state. """
        m, p, x = myokit.load('example')
        with TemporaryDirectory() as d:
            # Test save and load without model
            f = d.path('state.txt')
            myokit.save_state(f, m.state())
            self.assertEqual(myokit.load_state(f), m.state())

            # Test save and load with model argument
            myokit.save_state(f, m.state(), m)
            self.assertEqual(myokit.load_state(f, m), m.state())

            # Save without, load with model
            myokit.save_state(f, m.state())
            self.assertEqual(myokit.load_state(f, m), m.state())

            # Save with model, load without
            # Loaded version is dict!
            myokit.save_state(f, m.state(), m)
            dct = dict(zip([v.qname() for v in m.states()], m.state()))
            self.assertEqual(myokit.load_state(f), dct)
Example #29
0
    def test_model_2_0_errors(self):
        # CellML 2.0 files with errors should raise CellMLImporterErrors

        # Create model that will generate warnings
        x = ('<?xml version="1.0" encoding="UTF-8"?>'
             '<model name="test" xmlns="http://www.cellml.org/cellml/2.0#">'
             '<component name="a">'
             '  <variable name="hello" units="ampere"'
             '            public_interface="in"/>'
             '</component>'
             '</model>')

        # Write to disk and import
        with TemporaryDirectory() as d:
            path = d.path('test.celllml')
            with open(path, 'w') as f:
                f.write(x)

            # Import
            i = formats.importer('cellml')
            self.assertRaisesRegex(CellMLImporterError, 'Unexpected attribute',
                                   i.model, path)
Example #30
0
    def test_live_chain_and_eval_logging(self):

        np.random.seed(1)
        xs = []
        for i in range(3):
            f = 0.9 + 0.2 * np.random.rand()
            xs.append(np.array(self.real_parameters) * f)
        nchains = len(xs)

        # Test writing chains - not evals to disk (using LogPosterior)
        mcmc = pints.MCMCController(self.log_posterior, nchains, xs)
        mcmc.set_initial_phase_iterations(5)
        mcmc.set_max_iterations(20)
        mcmc.set_log_to_screen(True)
        mcmc.set_log_to_file(False)

        with StreamCapture() as c:
            with TemporaryDirectory() as d:
                cpath = d.path('chain.csv')
                p0 = d.path('chain_0.csv')
                p1 = d.path('chain_1.csv')
                p2 = d.path('chain_2.csv')
                epath = d.path('evals.csv')
                p3 = d.path('evals_0.csv')
                p4 = d.path('evals_1.csv')
                p5 = d.path('evals_2.csv')

                # Test files aren't created before mcmc runs
                mcmc.set_chain_filename(cpath)
                mcmc.set_log_pdf_filename(None)
                self.assertFalse(os.path.exists(cpath))
                self.assertFalse(os.path.exists(epath))
                self.assertFalse(os.path.exists(p0))
                self.assertFalse(os.path.exists(p1))
                self.assertFalse(os.path.exists(p2))
                self.assertFalse(os.path.exists(p3))
                self.assertFalse(os.path.exists(p4))
                self.assertFalse(os.path.exists(p5))

                # Test files are created afterwards
                chains1 = mcmc.run()
                self.assertFalse(os.path.exists(cpath))
                self.assertFalse(os.path.exists(epath))
                self.assertTrue(os.path.exists(p0))
                self.assertTrue(os.path.exists(p1))
                self.assertTrue(os.path.exists(p2))
                self.assertFalse(os.path.exists(p3))
                self.assertFalse(os.path.exists(p4))
                self.assertFalse(os.path.exists(p5))

                # Test files contain the correct chains
                import pints.io as io
                chains2 = np.array(io.load_samples(cpath, nchains))
                self.assertTrue(np.all(chains1 == chains2))

            text = c.text()
            self.assertIn('Writing chains to', text)
            self.assertIn('chain_0.csv', text)
            self.assertNotIn('Writing evaluations to', text)
            self.assertNotIn('evals_0.csv', text)

        # Test writing evals - not chains to disk (using LogPosterior)
        mcmc = pints.MCMCController(self.log_posterior, nchains, xs)
        mcmc.set_initial_phase_iterations(5)
        mcmc.set_max_iterations(20)
        mcmc.set_log_to_screen(True)
        mcmc.set_log_to_file(False)

        with StreamCapture() as c:
            with TemporaryDirectory() as d:
                cpath = d.path('chain.csv')
                p0 = d.path('chain_0.csv')
                p1 = d.path('chain_1.csv')
                p2 = d.path('chain_2.csv')
                epath = d.path('evals.csv')
                p3 = d.path('evals_0.csv')
                p4 = d.path('evals_1.csv')
                p5 = d.path('evals_2.csv')

                # Test files aren't created before mcmc runs
                mcmc.set_chain_filename(None)
                mcmc.set_log_pdf_filename(epath)
                self.assertFalse(os.path.exists(cpath))
                self.assertFalse(os.path.exists(epath))
                self.assertFalse(os.path.exists(p0))
                self.assertFalse(os.path.exists(p1))
                self.assertFalse(os.path.exists(p2))
                self.assertFalse(os.path.exists(p3))
                self.assertFalse(os.path.exists(p4))
                self.assertFalse(os.path.exists(p5))

                # Test files are created afterwards
                chains1 = mcmc.run()
                self.assertFalse(os.path.exists(cpath))
                self.assertFalse(os.path.exists(epath))
                self.assertFalse(os.path.exists(p0))
                self.assertFalse(os.path.exists(p1))
                self.assertFalse(os.path.exists(p2))
                self.assertTrue(os.path.exists(p3))
                self.assertTrue(os.path.exists(p4))
                self.assertTrue(os.path.exists(p5))

                # Test files contain the correct values
                import pints.io as io
                evals2 = np.array(io.load_samples(epath, nchains))
                evals1 = []
                for chain in chains1:
                    logpdfs = np.array([self.log_posterior(x) for x in chain])
                    logpriors = np.array([self.log_prior(x) for x in chain])
                    loglikelihoods = logpdfs - logpriors
                    evals = np.array([logpdfs, loglikelihoods, logpriors]).T
                    evals1.append(evals)
                evals1 = np.array(evals1)
                self.assertTrue(np.all(evals1 == evals2))

            text = c.text()
            self.assertNotIn('Writing chains to', text)
            self.assertNotIn('chain_0.csv', text)
            self.assertIn('Writing evaluations to', text)
            self.assertIn('evals_0.csv', text)

        # Test writing chains and evals to disk
        # With a LogPosterior - Single chain method
        mcmc = pints.MCMCController(self.log_posterior, nchains, xs)
        mcmc.set_initial_phase_iterations(5)
        mcmc.set_max_iterations(20)
        mcmc.set_log_to_screen(True)
        mcmc.set_log_to_file(False)

        with StreamCapture() as c:
            with TemporaryDirectory() as d:
                cpath = d.path('chain.csv')
                p0 = d.path('chain_0.csv')
                p1 = d.path('chain_1.csv')
                p2 = d.path('chain_2.csv')
                epath = d.path('evals.csv')
                p3 = d.path('evals_0.csv')
                p4 = d.path('evals_1.csv')
                p5 = d.path('evals_2.csv')

                # Test files aren't created before mcmc runs
                mcmc.set_chain_filename(cpath)
                mcmc.set_log_pdf_filename(epath)
                self.assertFalse(os.path.exists(cpath))
                self.assertFalse(os.path.exists(epath))
                self.assertFalse(os.path.exists(p0))
                self.assertFalse(os.path.exists(p1))
                self.assertFalse(os.path.exists(p2))
                self.assertFalse(os.path.exists(p3))
                self.assertFalse(os.path.exists(p4))
                self.assertFalse(os.path.exists(p5))

                # Test files are created afterwards
                chains1 = mcmc.run()
                self.assertFalse(os.path.exists(cpath))
                self.assertFalse(os.path.exists(epath))
                self.assertTrue(os.path.exists(p0))
                self.assertTrue(os.path.exists(p1))
                self.assertTrue(os.path.exists(p2))
                self.assertTrue(os.path.exists(p3))
                self.assertTrue(os.path.exists(p4))
                self.assertTrue(os.path.exists(p5))

                # Test chain files contain the correct values
                import pints.io as io
                chains2 = np.array(io.load_samples(cpath, nchains))
                self.assertTrue(np.all(chains1 == chains2))

                # Test eval files contain the correct values
                evals2 = np.array(io.load_samples(epath, nchains))
                evals1 = []
                for chain in chains1:
                    logpdfs = np.array([self.log_posterior(x) for x in chain])
                    logpriors = np.array([self.log_prior(x) for x in chain])
                    loglikelihoods = logpdfs - logpriors
                    evals = np.array([logpdfs, loglikelihoods, logpriors]).T
                    evals1.append(evals)
                evals1 = np.array(evals1)
                self.assertTrue(np.all(evals1 == evals2))

            text = c.text()
            self.assertIn('Writing chains to', text)
            self.assertIn('chain_0.csv', text)
            self.assertIn('Writing evaluations to', text)
            self.assertIn('evals_0.csv', text)

        # Test writing chains and evals to disk
        # With a LogPosterior - multi-chain method
        mcmc = pints.MCMCController(self.log_posterior,
                                    nchains,
                                    xs,
                                    method=pints.DifferentialEvolutionMCMC)
        mcmc.set_max_iterations(20)
        mcmc.set_log_to_screen(True)
        mcmc.set_log_to_file(False)

        with StreamCapture() as c:
            with TemporaryDirectory() as d:
                cpath = d.path('chain.csv')
                p0 = d.path('chain_0.csv')
                p1 = d.path('chain_1.csv')
                p2 = d.path('chain_2.csv')
                epath = d.path('evals.csv')
                p3 = d.path('evals_0.csv')
                p4 = d.path('evals_1.csv')
                p5 = d.path('evals_2.csv')

                # Test files aren't created before mcmc runs
                mcmc.set_chain_filename(cpath)
                mcmc.set_log_pdf_filename(epath)
                self.assertFalse(os.path.exists(cpath))
                self.assertFalse(os.path.exists(epath))
                self.assertFalse(os.path.exists(p0))
                self.assertFalse(os.path.exists(p1))
                self.assertFalse(os.path.exists(p2))
                self.assertFalse(os.path.exists(p3))
                self.assertFalse(os.path.exists(p4))
                self.assertFalse(os.path.exists(p5))

                # Test files are created afterwards
                chains1 = mcmc.run()
                self.assertFalse(os.path.exists(cpath))
                self.assertFalse(os.path.exists(epath))
                self.assertTrue(os.path.exists(p0))
                self.assertTrue(os.path.exists(p1))
                self.assertTrue(os.path.exists(p2))
                self.assertTrue(os.path.exists(p3))
                self.assertTrue(os.path.exists(p4))
                self.assertTrue(os.path.exists(p5))

                # Test chain files contain the correct values
                import pints.io as io
                chains2 = np.array(io.load_samples(cpath, nchains))
                self.assertTrue(np.all(chains1 == chains2))

                # Test eval files contain the correct values
                evals2 = np.array(io.load_samples(epath, nchains))
                evals1 = []
                for chain in chains1:
                    logpdfs = np.array([self.log_posterior(x) for x in chain])
                    logpriors = np.array([self.log_prior(x) for x in chain])
                    loglikelihoods = logpdfs - logpriors
                    evals = np.array([logpdfs, loglikelihoods, logpriors]).T
                    evals1.append(evals)
                evals1 = np.array(evals1)
                self.assertTrue(np.all(evals1 == evals2))

            text = c.text()
            self.assertIn('Writing chains to', text)
            self.assertIn('chain_0.csv', text)
            self.assertIn('Writing evaluations to', text)
            self.assertIn('evals_0.csv', text)

        # Test writing chains and evals to disk (with LogLikelihood)
        mcmc = pints.MCMCController(self.log_likelihood, nchains, xs)
        mcmc.set_initial_phase_iterations(5)
        mcmc.set_max_iterations(20)
        mcmc.set_log_to_screen(True)
        mcmc.set_log_to_file(False)

        with StreamCapture() as c:
            with TemporaryDirectory() as d:
                cpath = d.path('chain.csv')
                p0 = d.path('chain_0.csv')
                p1 = d.path('chain_1.csv')
                p2 = d.path('chain_2.csv')
                epath = d.path('evals.csv')
                p3 = d.path('evals_0.csv')
                p4 = d.path('evals_1.csv')
                p5 = d.path('evals_2.csv')

                # Test files aren't created before mcmc runs
                mcmc.set_chain_filename(cpath)
                mcmc.set_log_pdf_filename(epath)
                self.assertFalse(os.path.exists(cpath))
                self.assertFalse(os.path.exists(epath))
                self.assertFalse(os.path.exists(p0))
                self.assertFalse(os.path.exists(p1))
                self.assertFalse(os.path.exists(p2))
                self.assertFalse(os.path.exists(p3))
                self.assertFalse(os.path.exists(p4))
                self.assertFalse(os.path.exists(p5))

                # Test files are created afterwards
                chains1 = mcmc.run()
                self.assertFalse(os.path.exists(cpath))
                self.assertFalse(os.path.exists(epath))
                self.assertTrue(os.path.exists(p0))
                self.assertTrue(os.path.exists(p1))
                self.assertTrue(os.path.exists(p2))
                self.assertTrue(os.path.exists(p3))
                self.assertTrue(os.path.exists(p4))
                self.assertTrue(os.path.exists(p5))

                # Test chain files contain the correct values
                import pints.io as io
                chains2 = np.array(io.load_samples(cpath, nchains))
                self.assertTrue(np.all(chains1 == chains2))

                # Test eval files contain the correct values
                evals2 = np.array(io.load_samples(epath, nchains))
                evals1 = []
                for chain in chains1:
                    evals1.append(
                        np.array([self.log_likelihood(x) for x in chain]).T)
                evals1 = np.array(evals1).reshape(3, 20, 1)
                self.assertTrue(np.all(evals1 == evals2))

            text = c.text()
            self.assertIn('Writing chains to', text)
            self.assertIn('chain_0.csv', text)
            self.assertIn('Writing evaluations to', text)
            self.assertIn('evals_0.csv', text)

        # Test logging can be disabled again
        mcmc = pints.MCMCController(self.log_posterior, nchains, xs)
        mcmc.set_initial_phase_iterations(5)
        mcmc.set_max_iterations(20)
        mcmc.set_log_to_screen(True)
        mcmc.set_log_to_file(False)

        with StreamCapture() as c:
            with TemporaryDirectory() as d:
                cpath = d.path('chain.csv')
                p0 = d.path('chain_0.csv')
                p1 = d.path('chain_1.csv')
                p2 = d.path('chain_2.csv')
                epath = d.path('evals.csv')
                p3 = d.path('evals_0.csv')
                p4 = d.path('evals_1.csv')
                p5 = d.path('evals_2.csv')

                # Test files aren't created before mcmc runs
                mcmc.set_chain_filename(cpath)
                mcmc.set_log_pdf_filename(epath)
                self.assertFalse(os.path.exists(cpath))
                self.assertFalse(os.path.exists(epath))
                self.assertFalse(os.path.exists(p0))
                self.assertFalse(os.path.exists(p1))
                self.assertFalse(os.path.exists(p2))
                self.assertFalse(os.path.exists(p3))
                self.assertFalse(os.path.exists(p4))
                self.assertFalse(os.path.exists(p5))

                # Test files are not created afterwards
                mcmc.set_chain_filename(None)
                mcmc.set_log_pdf_filename(None)
                mcmc.run()
                self.assertFalse(os.path.exists(cpath))
                self.assertFalse(os.path.exists(epath))
                self.assertFalse(os.path.exists(p0))
                self.assertFalse(os.path.exists(p1))
                self.assertFalse(os.path.exists(p2))
                self.assertFalse(os.path.exists(p3))
                self.assertFalse(os.path.exists(p4))
                self.assertFalse(os.path.exists(p5))

            text = c.text()
            self.assertNotIn('Writing chains to', text)
            self.assertNotIn('chain_0.csv', text)
            self.assertNotIn('Writing evaluations to', text)
            self.assertNotIn('evals_0.csv', text)

        # Test with a single chain
        nchains = 1
        mcmc = pints.MCMCController(self.log_posterior, nchains, xs[:1])
        mcmc.set_initial_phase_iterations(5)
        mcmc.set_max_iterations(20)
        mcmc.set_log_to_screen(True)
        mcmc.set_log_to_file(False)

        with StreamCapture() as c:
            with TemporaryDirectory() as d:
                cpath = d.path('chain.csv')
                p0 = d.path('chain_0.csv')
                p1 = d.path('chain_1.csv')
                p2 = d.path('chain_2.csv')
                epath = d.path('evals.csv')
                p3 = d.path('evals_0.csv')
                p4 = d.path('evals_1.csv')
                p5 = d.path('evals_2.csv')

                # Test files aren't created before mcmc runs
                mcmc.set_chain_filename(cpath)
                mcmc.set_log_pdf_filename(epath)
                self.assertFalse(os.path.exists(cpath))
                self.assertFalse(os.path.exists(epath))
                self.assertFalse(os.path.exists(p0))
                self.assertFalse(os.path.exists(p1))
                self.assertFalse(os.path.exists(p2))
                self.assertFalse(os.path.exists(p3))
                self.assertFalse(os.path.exists(p4))
                self.assertFalse(os.path.exists(p5))

                # Test files are created afterwards
                chains1 = mcmc.run()
                self.assertFalse(os.path.exists(cpath))
                self.assertFalse(os.path.exists(epath))
                self.assertTrue(os.path.exists(p0))
                self.assertFalse(os.path.exists(p1))
                self.assertFalse(os.path.exists(p2))
                self.assertTrue(os.path.exists(p3))
                self.assertFalse(os.path.exists(p4))
                self.assertFalse(os.path.exists(p5))

                # Test chain files contain the correct values
                import pints.io as io
                chains2 = np.array(io.load_samples(cpath, nchains))
                self.assertTrue(np.all(chains1 == chains2))

                # Test eval files contain the correct values
                evals2 = np.array(io.load_samples(epath, nchains))
                evals1 = []
                for chain in chains1:
                    logpdfs = np.array([self.log_posterior(x) for x in chain])
                    logpriors = np.array([self.log_prior(x) for x in chain])
                    loglikelihoods = logpdfs - logpriors
                    evals = np.array([logpdfs, loglikelihoods, logpriors]).T
                    evals1.append(evals)
                evals1 = np.array(evals1)
                self.assertTrue(np.all(evals1 == evals2))

            text = c.text()
            self.assertIn('Writing chains to', text)
            self.assertIn('chain_0.csv', text)
            self.assertIn('Writing evaluations to', text)
            self.assertIn('evals_0.csv', text)