Exemplo n.º 1
0
    def test_parse_file(self):
        # Tests parse_file()

        # Supported level
        xml = self.wrap('<model id="a" name="a"/>', 3, 2)
        with WarningCollector() as w:
            self.p.parse_string(xml)
        self.assertNotIn('This version of SBML may not be supported', w.text())

        # Unsupported level
        xml = self.wrap('<model id="a" name="a"/>', 2, 2)
        with WarningCollector() as w:
            self.p.parse_string(xml)
        self.assertIn('This version of SBML may not be supported', w.text())

        # Unsupported version
        xml = self.wrap('<model id="a" name="a"/>', 3, 1)
        with WarningCollector() as w:
            self.p.parse_string(xml)
        self.assertIn('This version of SBML may not be supported', w.text())

        # Check whether error is thrown for invalid path
        path = 'some/path'
        message = 'Unable to parse XML: '
        self.assertRaisesRegex(
            SBMLParsingError,
            message,
            self.p.parse_file,
            path)

        # Check whether error is thrown for invalid xml
        self.assertBad('<model>', 'Unable to parse XML: ')
Exemplo n.º 2
0
    def test_variable(self):
        # Tests parsing variables

        # Valid has already been tested

        # Must have a name
        x = '<component name="a"><variable units="volt"/></component>'
        self.assertBad(x, 'must have a name attribute')

        # Must have units
        x = '<component name="a"><variable name="a" /></component>'
        self.assertBad(x, 'must have a units attribute')

        # CellML errors are converted to parsing errors
        x = '<component name="a"><variable name="1" units="volt"/></component>'
        self.assertBad(x, 'valid CellML identifier')

        # Unsupported units are ignored
        x = '<variable name="x" units="celsius" initial_value="3" />'
        x = '<component name="a">' + x + '</component>'
        with WarningCollector() as w:
            x = self.parse(x)['a']['x']
        self.assertIn('celsius', w.text())

        self.assertEqual(x.units().myokit_unit(), myokit.units.dimensionless)
Exemplo n.º 3
0
    def test_variable(self):
        # Tests writing of variables

        m1 = cellml.Model('m')
        c = m1.add_component('c')
        p = c.add_variable('p', 'mole')
        q = c.add_variable('q', 'kelvin', public_interface='in')
        r = c.add_variable('r', 'ampere', private_interface='out')
        p.set_initial_value(1)

        with WarningCollector():
            xml = cellml.write_string(m1)
            m2 = cellml.parse_string(xml)

        p, q, r = m2['c']['p'], m2['c']['q'], m2['c']['r']
        self.assertEqual(p.units().name(), 'mole')
        self.assertEqual(q.units().name(), 'kelvin')
        self.assertEqual(r.units().name(), 'ampere')
        self.assertEqual(p.public_interface(), 'none')
        self.assertEqual(q.public_interface(), 'in')
        self.assertEqual(r.public_interface(), 'none')
        self.assertEqual(p.private_interface(), 'none')
        self.assertEqual(q.private_interface(), 'none')
        self.assertEqual(r.private_interface(), 'out')
        self.assertEqual(p.initial_value(), 1)
        self.assertEqual(q.initial_value(), None)
        self.assertEqual(r.initial_value(), None)
Exemplo n.º 4
0
    def test_log_for_times(self):
        # Test the method Protocol.log_for_times()
        # Relies on PacingSystem

        p = myokit.Protocol()
        p.schedule(2, 10, 100, 1000, 2)

        t = [
            0, 9.999, 10, 10.001, 109.999, 110, 110.001, 1000, 1009.99, 1010,
            1110, 2000, 2020
        ]
        v = [0, 0, 2, 2, 2, 0, 0, 0, 0, 2, 0, 0, 0]
        d = p.log_for_times(t)
        self.assertEqual(len(d), 2)
        self.assertIn('time', d)
        self.assertIn('pace', d)
        self.assertEqual(d.time(), t)
        self.assertEqual(d['pace'], v)

        # Empty times
        d = p.log_for_times([])
        self.assertEqual(len(d.time()), 0)
        self.assertEqual(len(d['pace']), 0)

        # Deprecated alias
        with WarningCollector() as w:
            p.create_log_for_times([])
        self.assertIn('deprecated', w.text())
Exemplo n.º 5
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())
Exemplo n.º 6
0
    def test_guess_duration(self):
        # Deprecated method Protocol.guess_duration()

        p = myokit.Protocol()
        with WarningCollector() as w:
            self.assertEqual(p.characteristic_time(), p.guess_duration())
        self.assertIn('deprecated', w.text())
Exemplo n.º 7
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)
Exemplo n.º 8
0
    def test_parse_events(self):
        # Test parsing events (these are ignored)

        xml = (
            '<model>'
            ' <listOfEvents>'
            '  <event useValuesFromTriggerTime="true">'
            '   <trigger initialValue="false" persistent="true">'
            '    <math xmlns="http://www.w3.org/1998/Math/MathML">'
            '     <apply> <leq/> <ci> P_1 </ci> <ci> P_2 </ci> </apply>'
            '    </math>'
            '   </trigger>'
            '   <listOfEventAssignments>'
            '    <eventAssignment variable="k2">'
            '     <math xmlns="http://www.w3.org/1998/Math/MathML">'
            '      <ci> k2reset </ci>'
            '     </math>'
            '    </eventAssignment>'
            '   </listOfEventAssignments>'
            '  </event>'
            ' </listOfEvents>'
            '</model>')

        with WarningCollector() as w:
            self.p.parse_string(self.wrap(xml))
        self.assertIn('Ignoring SBML events', w.text())
Exemplo n.º 9
0
    def test_activation(self):
        # Test the activation experiment class.
        with WarningCollector():
            import myokit.lib.common as common

        # Load model
        m = os.path.join(DIR_DATA, 'lr-1991.mmt')
        m = myokit.load_model(m)
        # Create experiment
        c = m.get('ina')
        g = c.add_variable('g')
        g.set_rhs('m^3 * h * j')
        m.validate()
        a = common.Activation(m, 'ina.g')
        # Test
        a.times()
        a.traces()
        a.peaks(normalize=True)
        a.peaks(normalize=False)
        a.fit_boltzmann()
        a.convert_g2i()
        a.times()
        a.traces()
        a.peaks(normalize=True)
        a.peaks(normalize=False)
        a.fit_boltzmann()
Exemplo n.º 10
0
    def test_recovery(self):
        # Test the recovery experiment class.
        with WarningCollector():
            import myokit.lib.common as common

        # Load model
        m = os.path.join(DIR_DATA, 'lr-1991.mmt')
        m = myokit.load_model(m)
        # Create experiment
        c = m.get('ina')
        g = c.add_variable('g')
        g.set_rhs('m^3 * h * j')
        m.validate()
        r = common.Recovery(m, 'ina.g')
        # Test
        n = 20
        r.set_pause_duration(0.1, 10, n)
        d = r.ratio()
        self.assertEqual(len(d), 2)
        self.assertIn('engine.time', d)
        self.assertIn('ina.g', d)
        self.assertEqual(n, len(d['engine.time']))
        self.assertEqual(n, len(d['ina.g']))
        x = d['engine.time']
        self.assertTrue(np.all(x[1:] > x[:-1]))
        x = d['ina.g']  # This is a monotonically increasing function
        self.assertTrue(np.all(x[1:] > x[:-1]))
Exemplo n.º 11
0
    def test_from_data_log(self):
        # Test some edge cases of `DataBlock2d.from_log`.

        # Test valid construction
        d = myokit.DataLog()
        d.set_time_key('time')
        d['time'] = [1, 2, 3]
        d['x', 0, 0] = [0, 0, 0]
        d['x', 1, 0] = [1, 1, 2]
        d['x', 0, 1] = [1, 2, 2]
        d['x', 1, 1] = [3, 4, 5]
        d['x', 0, 2] = [6, 6, 6]
        d['x', 1, 2] = [7, 7, 2]
        myokit.DataBlock2d.from_log(d)

        # Deprecated alias
        with WarningCollector() as wc:
            myokit.DataBlock2d.from_DataLog(d)
        self.assertIn('deprecated', wc.text())

        # No time key
        d.set_time_key(None)
        self.assertRaises(ValueError, myokit.DataBlock2d.from_log, d)

        # Bad time key
        d.set_time_key('z')

        # Multi-dimensional time key
        d.set_time_key('0.0.x')
        self.assertRaises(ValueError, myokit.DataBlock2d.from_log, d)

        # 1-dimensional stuff
        d.set_time_key('time')
        myokit.DataBlock2d.from_log(d)
        d['y', 0] = [10, 10, 10]
        d['y', 1] = [20, 20, 20]
        self.assertRaises(ValueError, myokit.DataBlock2d.from_log, d)

        # Mismatched dimensions
        d = myokit.DataLog()
        d.set_time_key('time')
        d['time'] = [1, 2, 3]
        d['x', 0, 0] = [0, 0, 0]
        d['x', 1, 0] = [1, 1, 2]
        d['x', 0, 1] = [1, 2, 2]
        d['x', 1, 1] = [3, 4, 5]
        d['x', 0, 2] = [6, 6, 6]
        d['x', 1, 2] = [7, 7, 2]
        d['y', 0, 0] = [0, 0, 0]
        d['y', 1, 0] = [1, 1, 2]
        d['y', 0, 1] = [1, 2, 2]
        d['y', 1, 1] = [3, 4, 5]
        d['y', 0, 2] = [6, 6, 6]
        d['y', 1, 2] = [7, 7, 2]
        myokit.DataBlock2d.from_log(d)
        del (d['0.2.y'])
        del (d['1.2.y'])
        self.assertRaises(ValueError, myokit.DataBlock2d.from_log, d)
Exemplo n.º 12
0
    def test_worker(self):
        # Manual test of worker, since cover doesn't pick up on its run method.

        with WarningCollector():
            from myokit.lib.fit import _Worker as Worker

        # Create queues for worker
        import multiprocessing
        tasks = multiprocessing.Queue()
        results = multiprocessing.Queue()
        errors = multiprocessing.Queue()
        error = multiprocessing.Event()
        tasks.put((0, 1))
        tasks.put((1, 2))
        tasks.put((2, 3))
        max_tasks = 3

        w = Worker(h, (), tasks, results, max_tasks, errors, error)
        w.run()

        self.assertEqual(results.get(timeout=0.01), (0, 2))
        self.assertEqual(results.get(timeout=0.01), (1, 4))
        self.assertEqual(results.get(timeout=0.01), (2, 6))
        self.assertTrue(results.empty())

        # Test worker stops if error flag is set
        tasks = multiprocessing.Queue()
        results = multiprocessing.Queue()
        errors = multiprocessing.Queue()
        error = multiprocessing.Event()
        tasks.put((0, 1))
        tasks.put((1, 2))
        tasks.put((2, 3))
        error.set()

        w = Worker(h, (), tasks, results, max_tasks, errors, error)
        w.run()

        self.assertEqual(results.get(timeout=0.01), (0, 2))
        self.assertTrue(results.empty())

        # Tests worker catches, stores and halts on exception
        tasks = multiprocessing.Queue()
        results = multiprocessing.Queue()
        errors = multiprocessing.Queue()
        error = multiprocessing.Event()
        tasks.put((0, 1))
        tasks.put((1, 30))
        tasks.put((2, 3))

        w = Worker(h, (), tasks, results, max_tasks, errors, error)
        w.run()

        self.assertEqual(results.get(timeout=0.01), (0, 2))
        self.assertTrue(results.empty())
        self.assertTrue(error.is_set())
        #self.assertFalse(errors.empty())
        self.assertIsNotNone(errors.get(timeout=0.01))
Exemplo n.º 13
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())
Exemplo n.º 14
0
    def test_xnes(self):
        # Test if a xNES routine runs without errors.
        with WarningCollector():
            import myokit.lib.fit as fit

        np.random.seed(1)
        with np.errstate(all='ignore'):  # Tell numpy not to issue warnings
            x, f = fit.xnes(FittingTest._score,
                            self._boundaries,
                            hint=self._hint,
                            parallel=False,
                            max_iter=50)
Exemplo n.º 15
0
    def test_show_line_of(self):
        # Test :meth:`Model.show_line_of(variable)`.

        m = myokit.load_model('example')
        e = m.show_line_of(m.get('ina.INa'))
        self.assertIn('Defined on line 91', e)
        self.assertIn('Intermediary variable', e)
        self.assertEqual(len(e.splitlines()), 4)

        # Test deprecated alias
        with WarningCollector() as wc:
            m.show_line(m.get('ina.INa'))
        self.assertIn('deprecated', wc.text())
Exemplo n.º 16
0
    def test_time(self):
        # Test the time() method that returns the time variable.

        m = myokit.Model()
        c = m.add_component('c')
        x = c.add_variable('x')
        x.set_rhs(0)

        with WarningCollector() as w:
            self.assertRaises(myokit.IncompatibleModelError, multi.time, m)
            x.set_binding('time')
            self.assertEqual(x, multi.time(m))
        self.assertIn('deprecated', w.text())
Exemplo n.º 17
0
    def test_restitution(self):
        # Test the restitution experiment class.
        with WarningCollector():
            import myokit.lib.common as common

        # Load model
        m = os.path.join(DIR_DATA, 'lr-1991.mmt')
        m = myokit.load_model(m)
        # Create experiment
        r = common.Restitution(m)
        # Test
        r.set_times(300, 800, 200)
        r.run()
Exemplo n.º 18
0
    def test_strength_duration(self):
        # Test the strength-duration experiment class.
        with WarningCollector():
            import myokit.lib.common as common

        # Load model
        m = os.path.join(DIR_DATA, 'lr-1991.mmt')
        m = myokit.load_model(m)
        # Create experiment
        s = common.StrengthDuration(m, 'membrane.i_stim')
        # Test
        s.set_currents(-200, -10)
        s.set_times(0.5, 1.0, 0.2)
        s.run()
Exemplo n.º 19
0
    def test_label(self):
        # Test the label() method that returns a labelled variable.

        m = myokit.Model()
        c = m.add_component('c')
        x = c.add_variable('x')
        x.set_rhs(0)

        with WarningCollector() as w:
            self.assertRaises(
                myokit.IncompatibleModelError, multi.label, m, 'x')
            x.set_label('x')
            self.assertEqual(x, multi.label(m, 'x'))
        self.assertIn('deprecated', w.text())
Exemplo n.º 20
0
    def test_parallel_simulations(self):
        # Test running simulations in parallel

        with WarningCollector():
            import myokit.lib.fit as fit

        # Test running simulation defined in object
        s = Sim()
        e = fit.ParallelEvaluator(s.run, nworkers=4)
        e.evaluate([1, 2, 3, 4])

        # Test running simulation created inside of score function
        e = fit.ParallelEvaluator(run_sim, nworkers=4)
        e.evaluate([1, 2, 3, 4])
Exemplo n.º 21
0
    def test_units_predefined(self):
        # Tests parsing all the predefined units

        def u(units):
            m = self.parse('<component name="c">'
                           '  <variable name="x" units="' + units + '"'
                           '   initial_value="1" />'
                           '</component>')
            return m['c']['x'].units().myokit_unit()

        self.assertEqual(u('ampere'), myokit.units.ampere)
        self.assertEqual(u('becquerel'), myokit.units.becquerel)
        self.assertEqual(u('candela'), myokit.units.candela)
        self.assertEqual(u('coulomb'), myokit.units.coulomb)
        self.assertEqual(u('dimensionless'), myokit.units.dimensionless)
        self.assertEqual(u('farad'), myokit.units.farad)
        self.assertEqual(u('gram'), myokit.units.g)
        self.assertEqual(u('gray'), myokit.units.gray)
        self.assertEqual(u('henry'), myokit.units.henry)
        self.assertEqual(u('hertz'), myokit.units.hertz)
        self.assertEqual(u('joule'), myokit.units.joule)
        self.assertEqual(u('katal'), myokit.units.katal)
        self.assertEqual(u('kelvin'), myokit.units.kelvin)
        self.assertEqual(u('kilogram'), myokit.units.kg)
        self.assertEqual(u('liter'), myokit.units.liter)
        self.assertEqual(u('litre'), myokit.units.liter)
        self.assertEqual(u('lumen'), myokit.units.lumen)
        self.assertEqual(u('lux'), myokit.units.lux)
        self.assertEqual(u('meter'), myokit.units.meter)
        self.assertEqual(u('metre'), myokit.units.meter)
        self.assertEqual(u('mole'), myokit.units.mole)
        self.assertEqual(u('newton'), myokit.units.newton)
        self.assertEqual(u('ohm'), myokit.units.ohm)
        self.assertEqual(u('pascal'), myokit.units.pascal)
        self.assertEqual(u('radian'), myokit.units.radian)
        self.assertEqual(u('second'), myokit.units.second)
        self.assertEqual(u('siemens'), myokit.units.siemens)
        self.assertEqual(u('sievert'), myokit.units.sievert)
        self.assertEqual(u('steradian'), myokit.units.steradian)
        self.assertEqual(u('tesla'), myokit.units.tesla)
        self.assertEqual(u('volt'), myokit.units.volt)
        self.assertEqual(u('watt'), myokit.units.watt)
        self.assertEqual(u('weber'), myokit.units.weber)

        # Celsius is not supported
        with WarningCollector() as w:
            self.assertEqual(u('celsius'), myokit.units.dimensionless)
        self.assertIn('celsius', w.text())
Exemplo n.º 22
0
    def test_parallel_evaluator(self):

        with WarningCollector():
            import myokit.lib.fit as fit

        # Test parallel execution
        e = fit.ParallelEvaluator(f, max_tasks_per_worker=9)

        # Test 1
        x = 1 + np.random.random(30)
        e.evaluate(x)

        # Test 2
        x = 2 + np.random.random(15)
        e.evaluate(x)

        # Test 3 (with exception)
        x[13] = 0
        self.assertRaises(Exception, e.evaluate, x)

        # Repeat run with exception
        x[11] = 0
        self.assertRaises(Exception, e.evaluate, x)

        # Repeat run
        x = 1 + np.random.random(16)
        e.evaluate(x)

        e = fit.ParallelEvaluator(f_args, args=[10, 20])
        self.assertEqual(e.evaluate([1])[0], 1)

        # Argument must be callable
        self.assertRaises(ValueError, fit.ParallelEvaluator, 1)

        # Args must be a sequence
        self.assertRaises(ValueError, fit.ParallelEvaluator, f_args, args=1)

        # n-workers must be >0
        self.assertRaises(ValueError, fit.ParallelEvaluator, f, 0)

        # max tasks must be >0
        self.assertRaises(ValueError, fit.ParallelEvaluator, f, 1, 0)

        e = fit.ParallelEvaluator(ioerror_on_five)

        self.assertRaisesRegex(Exception, 'in subprocess', e.evaluate,
                               range(10))
Exemplo n.º 23
0
    def test_from_log(self):
        # Test some edge cases of `DataBlock1d.from_log`.

        # Test valid construction
        d = myokit.DataLog()
        d.set_time_key('time')
        d['time'] = [1, 2, 3]
        d['x', 0] = [0, 0, 0]
        d['x', 1] = [1, 1, 2]
        myokit.DataBlock1d.from_log(d)

        # Deprecated alias
        with WarningCollector() as wc:
            myokit.DataBlock1d.from_DataLog(d)
        self.assertIn('deprecated', wc.text())

        # No time key
        d = myokit.DataLog()
        d['time'] = [1, 2, 3]
        d['x', 0] = [0, 0, 0]
        d['x', 1] = [1, 1, 2]
        self.assertRaises(ValueError, myokit.DataBlock1d.from_log, d)

        # Multi-dimensional time key
        d.set_time_key('0.x')
        self.assertRaises(ValueError, myokit.DataBlock1d.from_log, d)

        # 2-dimensional stuff
        d.set_time_key('time')
        myokit.DataBlock1d.from_log(d)
        d['y', 0, 0] = [10, 10, 10]
        self.assertRaises(ValueError, myokit.DataBlock1d.from_log, d)

        # Mismatched dimensions
        d = myokit.DataLog()
        d.set_time_key('time')
        d['time'] = [1, 2, 3]
        d['x', 0] = [0, 0, 0]
        d['x', 1] = [1, 1, 2]
        d['y', 0] = [2, 0, 0]
        d['y', 1] = [3, 1, 2]
        d['y', 2] = [0, 4, 5]
        self.assertRaises(ValueError, myokit.DataBlock1d.from_log, d)
Exemplo n.º 24
0
    def test_sim_1d(self):
        # Test running a short 1d simulation (doesn't inspect output)

        m, p, _ = myokit.load('example')
        s = myokit.SimulationOpenCL(m, p, 20)

        # Run, log state and intermediary variable (separate logging code!)
        d = s.run(1, log=['engine.time', 'membrane.V', 'ina.INa'])
        self.assertIn('engine.time', d)
        self.assertIn('0.membrane.V', d)
        self.assertIn('19.membrane.V', d)
        self.assertIn('0.ina.INa', d)
        self.assertIn('19.ina.INa', d)
        self.assertEqual(len(d), 41)

        # Test is_2d()
        self.assertFalse(s.is_2d())
        with WarningCollector() as wc:
            self.assertFalse(s.is2d())
        self.assertIn('deprecated', wc.text())
Exemplo n.º 25
0
    def test_parse_constraint(self):
        # Test parsing constraints (these are ignored)

        xml = (
            '<model>'
            ' <listOfConstraints>'
            '  <constraint>'
            '   <math xmlns="http://www.w3.org/1998/Math/MathML">'
            '    <apply> <lt/> <cn> 1 </cn> <ci> S1 </ci> </apply>'
            '   </math>'
            '   <message>'
            '     <p xmlns="http://www.w3.org/1999/xhtml">Out of range.</p>'
            '   </message>'
            '  </constraint>'
            ' </listOfConstraints>'
            '</model>')

        with WarningCollector() as w:
            self.p.parse_string(self.wrap(xml))
        self.assertIn('Ignoring SBML constraints', w.text())
Exemplo n.º 26
0
    def test_log_for_interval(self):
        # Tests the method Protocol.log_for_interval()
        # Relies on PacingSystem

        debug = False

        # Test basic use + log creation methods
        p = myokit.Protocol()
        p.schedule(1, 10, 1, 1000, 0)
        d = p.log_for_interval(0, 3000)
        self.assertEqual(d.time(), [0, 10, 11, 1010, 1011, 2010, 2011, 3000])
        d = p.log_for_interval(0, 2000, for_drawing=True)
        if debug:
            import matplotlib.pyplot as plt
            plt.figure()
            plt.plot(d.time(), d['pace'])
            plt.show()
        self.assertEqual(d.time(),
                         [0, 10, 10, 11, 11, 1010, 1010, 1011, 1011, 2000])
        p = myokit.Protocol()
        p.schedule(1, 0, 1, 1000, 0)
        d = p.log_for_interval(0, 3000)
        self.assertEqual(d.time(), [0, 1, 1000, 1001, 2000, 2001, 3000])
        d = p.log_for_interval(0, 2000, for_drawing=True)
        if debug:
            import matplotlib.pyplot as plt
            plt.figure()
            plt.plot(d.time(), d['pace'])
            plt.show()
        self.assertEqual(d.time(),
                         [0, 1, 1, 1000, 1000, 1001, 1001, 2000, 2000])

        # Test bad interval call
        self.assertRaises(ValueError, p.log_for_interval, 100, 0)

        # Test deprecated alias
        with WarningCollector() as w:
            p.create_log_for_interval(0, 2000, for_drawing=True)
        self.assertIn('deprecated', w.text())
Exemplo n.º 27
0
    def test_evaluators(self):

        with WarningCollector():
            import myokit.lib.fit as fit

        # Test basic sequential/parallel evaluation
        x = 1 + np.random.random(100)

        # Simple run: sequential and parallel
        fit.evaluate(f, x, parallel=False)

        # Note: the overhead is almost 100% of the run-time of this test
        fit.evaluate(f, x, parallel=True)

        e = fit.SequentialEvaluator(f_args, [10, 20])
        self.assertEqual(e.evaluate([1])[0], 1)

        # Argument must be callable
        self.assertRaises(ValueError, fit.SequentialEvaluator, 1)

        # Args must be a sequence
        self.assertRaises(ValueError, fit.SequentialEvaluator, f_args, 1)
Exemplo n.º 28
0
    def test_sim_2d(self):
        # Test running a short 2d simulation (doesn't inspect output)

        m, p, _ = myokit.load('example')
        n = (8, 8)
        s = myokit.SimulationOpenCL(m, p, n)
        s.set_paced_cells(4, 4)

        # Run, log state and intermediary variable (separate logging code!)
        d = s.run(1, log=['engine.time', 'membrane.V', 'ina.INa'])
        self.assertEqual(len(d), 129)
        self.assertIn('engine.time', d)
        self.assertIn('0.0.membrane.V', d)
        self.assertIn('7.7.membrane.V', d)
        self.assertIn('0.0.ina.INa', d)
        self.assertIn('7.7.ina.INa', d)

        # Test is_2d()
        self.assertTrue(s.is_2d())
        with WarningCollector() as wc:
            self.assertTrue(s.is2d())
        self.assertIn('deprecated', wc.text())
Exemplo n.º 29
0
    def test_units(self):
        # Test parsing a units definition

        # Valid has already been testsed

        # New base units are not supported
        x = '<units name="base" />'
        with WarningCollector() as w:
            m = self.parse(x)
        self.assertIn('new base units', w.text())
        self.assertEqual(
            m.find_units('base').myokit_unit(), myokit.units.dimensionless)

        # CellML errors are converted to parse errors
        x = '<units name="123"><unit units="volt" /></units>'
        self.assertBad(x, 'valid CellML identifier')

        # Missing name
        x = '<units><unit units="volt" /></units>'
        self.assertBad(x, 'must have a name')

        # Name overlaps with predefined
        x = '<units name="metre"><unit units="volt" /></units>'
        self.assertBad(x, 'overlaps with a predefined name')

        # Duplicate name (handled in sorting)
        x = '<units name="wooster"><unit units="volt" /></units>'
        self.assertBad(x + x, 'Duplicate units definition')

        # Missing units definitions
        x = ('<units name="wooster"><unit units="fluther" /></units>')
        self.assertBad(x, 'Unable to resolve network of units')

        # Circular units definitions
        x = ('<units name="wooster"><unit units="fluther" /></units>'
             '<units name="fluther"><unit units="wooster" /></units>')
        self.assertBad(x, 'Unable to resolve network of units')
Exemplo n.º 30
0
    def test_cmaes(self):
        # Test if a CMA-ES routine runs without errors.

        with WarningCollector():
            import myokit.lib.fit as fit

        # Some CMAES versions import matplotlib...
        import matplotlib
        matplotlib.use('template')

        try:
            import cma
            del (cma)
        except ImportError:
            print('CMA module not found, skipping test.')
            return

        np.random.seed(1)
        with np.errstate(all='ignore'):  # Tell numpy not to issue warnings
            x, f = fit.cmaes(FittingTest._score,
                             self._boundaries,
                             hint=self._hint,
                             parallel=False,
                             target=1)