Esempio n. 1
0
    def setUpClass(cls):
        # Load model, simulation etc. only once
        fname = os.path.join(DIR_DATA, 'clancy-1999-fitting.mmt')
        model = myokit.load_model(fname)

        # Extract the Markov model of INa
        parameters = ['ina.p1', 'ina.p2']
        cls._boundaries = [[1e-3, 10], [1e-3, 10]]
        markov_model = markov.LinearModel.from_component(
            model.get('ina'),
            parameters=parameters,
            current='ina.i',
        )

        # Create an analytical markov model simulation
        cls._sim = markov.AnalyticalSimulation(markov_model)

        # Voltages to test at
        r = 10
        cls._voltages = np.arange(-70, -10 + r, r)

        # Times to evaluate at
        times = np.concatenate((np.linspace(0, 4, 100), np.linspace(4, 8, 20)))

        # Generate reference traces
        cls._references = []
        for v in cls._voltages:
            cls._sim.set_membrane_potential(v)
            x, i = cls._sim.solve(times)
            cls._references.append(i)

        # Give a hint
        # p1 = 0.1027 / 3.802 ~ 0.0270
        # p2 = 0.20 / 3.802 ~ 0.0526
        cls._hint = [0.0269, 0.052]
Esempio n. 2
0
 def create_manual(self):
     """
     Tests manual creation of a Markov model
     """
     # Load model
     fname = os.path.join(myotest.DIR_DATA, 'clancy-1999-fitting.mmt')
     model = myokit.load_model(fname)
     # Select a number of states and parameters
     states = [
         'ina.C3',
         'ina.C2',
         'ina.C1',
         'ina.IF',
         'ina.IS',
         'ina.O',
     ]
     parameters = [
         'ina.p1',
         'ina.p2',
         'ina.p3',
         'ina.p4',
     ]
     current = 'ina.i'
     # Create a markov model
     m = markov.LinearModel(model, states, parameters, current)
     # Create a simulation
     s = markov.AnalyticalSimulation(m)
     # Times to evaluate at
     times = np.linspace(0, 100, 5)
     # Voltages to test at
     voltages = np.arange(-70, 0, 30)
     # Generate traces
     for v in voltages:
         s.set_membrane_potential(v)
         x, i = s.solve(times)
Esempio n. 3
0
    def test_analytical_simulation_properties(self):
        # Test basic get/set methods of analytical simulation.

        # Create a simulation
        fname = os.path.join(DIR_DATA, 'clancy-1999-fitting.mmt')
        model = myokit.load_model(fname)
        m = markov.LinearModel.from_component(model.get('ina'))
        s = markov.AnalyticalSimulation(m)

        # membrane potential
        self.assertEqual(s.membrane_potential(),
                         model.get('membrane.V').eval())
        s.set_membrane_potential(10)
        self.assertEqual(s.membrane_potential(), 10)

        # Parameter values
        p = list(range(len(s.parameters())))
        self.assertNotEqual(p, s.parameters())
        s.set_parameters(p)
        self.assertEqual(p, s.parameters())
        self.assertRaises(ValueError, s.set_parameters, p[:-1])

        # Change parameter with set_constant
        p[3] += 1
        self.assertNotEqual(p, s.parameters())
        s.set_constant(m.parameters()[3], p[3])
        self.assertEqual(p, s.parameters())

        # State
        state = np.zeros(len(s.state()))
        state[0] = 0.5
        state[1] = 0.5
        self.assertNotEqual(list(state), list(s.state()))
        s.set_state(state)
        self.assertEqual(list(state), list(s.state()))
        self.assertRaisesRegex(ValueError, 'Wrong size', s.set_state,
                               state[:-1])
        state[0] += 0.1
        self.assertRaisesRegex(ValueError, 'sum to 1', s.set_state, state)
        state[0] = -.1
        state[1] = 1.1
        self.assertRaisesRegex(ValueError, 'negative', s.set_state, state)

        # Default state
        dstate = np.zeros(len(s.default_state()))
        dstate[0] = 0.5
        dstate[1] = 0.5
        self.assertNotEqual(list(dstate), list(s.default_state()))
        s.set_default_state(dstate)
        self.assertEqual(list(dstate), list(s.default_state()))
        self.assertRaisesRegex(ValueError, 'Wrong size', s.set_default_state,
                               dstate[:-1])
        dstate[0] += 0.1
        self.assertRaisesRegex(ValueError, 'sum to 1', s.set_default_state,
                               dstate)
        dstate[0] = -.1
        dstate[1] = 1.1
        self.assertRaisesRegex(ValueError, 'negative', s.set_default_state,
                               dstate)
Esempio n. 4
0
    def __init__(self, name):
        super(FittingTest, self).__init__(name)
        # Load model, simulation etc. only once
        fname = os.path.join(myotest.DIR_DATA, 'clancy-1999-fitting.mmt')
        model = myokit.load_model(fname)

        # Extract the Markov model of INa
        parameters = ['ina.p1', 'ina.p2']
        self._boundaries = [[1e-3, 10], [1e-3, 10]]
        markov_model = markov.LinearModel.from_component(
            model.get('ina'),
            parameters=parameters,
            current='ina.i',
        )

        # Create an analytical markov model simulation
        self._sim = markov.AnalyticalSimulation(markov_model)

        # Voltages to test at
        r = 10
        self._voltages = np.arange(-70, -10 + r, r)

        # Times to evaluate at
        times = np.concatenate((np.linspace(0, 4, 100), np.linspace(4, 8, 20)))

        # Generate reference traces
        self._references = []
        for v in self._voltages:
            self._sim.set_membrane_potential(v)
            x, i = self._sim.solve(times)
            self._references.append(i)

        # Define function to optimize
        def score(guess):
            try:
                error = 0
                self._sim.set_parameters(guess)
                for k, v in enumerate(self._voltages):
                    self._sim.set_membrane_potential(v)
                    x, i = self._sim.solve(times)
                    r = self._references[k]
                    rmax = np.max(np.abs(r))
                    error += np.sqrt(np.sum(((i - r) / rmax) ** 2))
                return error / len(self._voltages)
            except Exception:
                return float('inf')
        self._score = score

        # Give a hint
        self._hint = [0.03, 0.05]
Esempio n. 5
0
    def test_against_cvode(self):
        # Validate against a cvode sim.

        # Get a model
        fname = os.path.join(DIR_DATA, 'clancy-1999-fitting.mmt')
        model = myokit.load_model(fname)

        # Create a protocol
        vs = [-30, -20, -10]
        p = myokit.pacing.steptrain(
            vsteps=vs,
            vhold=-120,
            tpre=8,
            tstep=2,
            tpost=0)
        t = p.characteristic_time()

        # Run an analytical simulation
        dt = 0.01
        m = markov.LinearModel.from_component(model.get('ina'))
        s1 = markov.AnalyticalSimulation(m, p)
        d1 = s1.run(t, log_interval=dt).npview()

        s2 = myokit.Simulation(model, p)
        s2.set_tolerance(1e-8, 1e-8)
        d2 = s2.run(t, log_interval=dt).npview()

        # Test protocol output is the same
        e = np.abs(d1['membrane.V'] - d2['membrane.V'])
        if False:
            import matplotlib.pyplot as plt
            plt.figure()
            plt.plot(d1['membrane.V'])
            plt.plot(d2['membrane.V'])
            plt.show()
        self.assertEqual(np.max(e), 0)

        # Test current output is very similar
        e = np.abs(d1['ina.i'] - d2['ina.i'])
        if False:
            import matplotlib.pyplot as plt
            plt.figure()
            plt.plot(d1['ina.i'])
            plt.plot(d2['ina.i'])
            plt.figure()
            plt.plot(d1['ina.i'] - d2['ina.i'])
            plt.show()
        self.assertLess(np.max(e), 2e-4)
Esempio n. 6
0
 def create_automatic(self):
     # Load model
     fname = os.path.join(myotest.DIR_DATA, 'clancy-1999-fitting.mmt')
     model = myokit.load_model(fname)
     # Create a markov model
     m = markov.LinearModel.from_component(model.get('ina'))
     # Create a simulation
     s = markov.AnalyticalSimulation(m)
     # Times to evaluate at
     times = np.linspace(0, 100, 5)
     # Voltages to test at
     voltages = np.arange(-70, 0, 30)
     # Generate traces
     for v in voltages:
         s.set_membrane_potential(v)
         x, i = s.solve(times)
Esempio n. 7
0
    def test_create_and_run(self):
        # Test basics of analytical simulation

        # Create a simulation
        fname = os.path.join(DIR_DATA, 'clancy-1999-fitting.mmt')
        model = myokit.load_model(fname)
        m = markov.LinearModel.from_component(model.get('ina'))

        # Bad constructors
        self.assertRaisesRegex(ValueError, 'LinearModel',
                               markov.AnalyticalSimulation, 1)
        self.assertRaisesRegex(ValueError, 'Protocol',
                               markov.AnalyticalSimulation, m, 1)

        # Create properly
        s = markov.AnalyticalSimulation(m)

        # Times to evaluate at
        times = np.linspace(0, 100, 5)

        # Voltages to test at
        voltages = np.arange(-70, 0, 30)

        # Generate traces with "solve" method
        state = s.state()
        dstate = s.default_state()
        for v in voltages:
            s.set_membrane_potential(v)
            x, i = s.solve(times)

        # Solve shouldn't change the state
        self.assertEqual(state, s.state())
        self.assertEqual(dstate, s.default_state())

        # Run for a bit
        self.assertIsInstance(s.run(10), myokit.DataLog)

        # Calculate current for a particular state
        self.assertIsInstance(s.current(s.state()), float)

        # No current variable? Then current can't be calculated
        model2 = model.clone()
        model2.get('ina').remove_variable(model2.get('ina.i'))
        m2 = markov.LinearModel.from_component(model2.get('ina'))
        s2 = markov.AnalyticalSimulation(m2)
        self.assertRaisesRegex(Exception, 'did not specify a current',
                               s2.current, s2.state())
        # But simulation still works
        self.assertIsInstance(s2.run(10), myokit.DataLog)
        del (model2, m2, s2)

        # Create protocol

        # Protocol times: prep, step, post, full
        tprep = 2800
        tstep = 15
        tpost = 0

        # Step voltages
        vhold = -80
        vlo = -140
        vhi = 100
        res = 50
        v = np.arange(vlo, vhi + res, res)
        p = myokit.pacing.steptrain(v, vhold, tprep, tstep, tpost)
        t = p.characteristic_time()

        # Create simulation with protocol (set_protocol is not supported)
        s = markov.AnalyticalSimulation(m, p)

        # Membrane potential and protocol can't be used simultaneously
        self.assertRaisesRegex(Exception, 'cannot be set if',
                               s.set_membrane_potential, -80)

        # Pre should change the state and default state
        state = s.state()
        dstate = s.default_state()
        s.pre(tprep + tstep)
        self.assertNotEqual(state, s.state())
        self.assertNotEqual(dstate, s.default_state())
        self.assertRaises(ValueError, s.pre, -1)

        # Run should change the state, not the default state
        state = s.state()
        dstate = s.default_state()
        d = s.run(t)
        self.assertNotEqual(state, s.state())
        self.assertEqual(dstate, s.default_state())
        self.assertRaisesRegex(ValueError, 'Duration', s.run, -1)
        self.assertRaisesRegex(ValueError,
                               'Log interval',
                               s.run,
                               1,
                               log_interval=-1)
        d['hello'] = [1, 2, 3]
        self.assertRaisesRegex(ValueError, 'extra keys', s.run, 1, log=d)
        del (d['hello'])
        del (d[next(iter(d.keys()))])
        self.assertRaisesRegex(ValueError, 'missing', s.run, 1, log=d)

        # Reset should reset the state
        s.reset()
        self.assertEqual(state, s.state())

        # Run can append to log
        d = s.run(10)
        n = len(d['engine.time'])
        e = s.run(1, log=d)
        self.assertIs(d, e)
        self.assertTrue(len(d['engine.time']) > n)