Пример #1
0
 def save_model(self):
     """
     Tests if the correct parts are saved/loaded from disk using the
     ``save_model()`` method.
     """
     ipath = os.path.join(myotest.DIR_DATA, 'lr-1991.mmt')
     opath = os.path.join(myotest.DIR_OUT, 'loadsavetest.mmt')
     if os.path.exists(opath):
         os.remove(opath)
     # 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)
     if os.path.exists(opath):
         os.remove(opath)
     try:
         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())
     finally:
         os.remove(opath)
Пример #2
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)
Пример #3
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())
    def setUpClass(cls):
        # Load models and protocols for use in testing

        # Fiber model, tissue model, protocol
        cls.mf = myokit.load_model(
            os.path.join(DIR_DATA, 'dn-1985-normalised.mmt'))
        cls.mt = myokit.load_model(os.path.join(DIR_DATA, 'lr-1991.mmt'))

        # Fiber/Tissue sizes (small sim)
        cls.nfx = 8
        cls.nfy = 4
        cls.ntx = 8
        cls.nty = 6

        # Standard protocols
        cls.p1 = myokit.pacing.blocktrain(1000, 2, offset=.01)

        # Protocol with error at t = 2
        cls.p2 = myokit.Protocol()
        cls.p2.schedule(period=0, duration=5, level=5e3, start=2)

        # Protocol with error at t = 1.234 (in tissue?)
        cls.p3 = myokit.Protocol()
        cls.p3.schedule(period=0, duration=5, level=-1, start=1.234)
        v = cls.mt.get('ina.m')
        v.set_rhs('if(membrane.V < -100, 1e4, ' + v.rhs().code() + ')')

        # Shared simulations
        cls._s1 = None
Пример #5
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)
def step(source, ref, ini, raw):
    """
    Loads a model and evaluates the state vector derivatives.
    """
    import sys
    import myokit

    # Parse reference file, if given
    if ref and not raw:
        print('Reading reference file...')
        try:
            ref = myokit.load_model(ref[0])
            print('Reference model loaded successfully.')
        except Exception:
            ref = myokit.load_state(ref[0])
            print('Reference file read successfully.')

    # Parse initial value file, if given
    if ini:
        if not raw:
            print('Reading initial value file...')
        ini = myokit.load_state(ini[0])
        if not raw:
            print('Initial value file read successfully.')

    # Load myokit model
    try:
        if not raw:
            print('Reading model from ' + source + '...')
        model = myokit.load_model(source)
        if not raw:
            print('Model ' + model.name() + ' read successfully.')
    except myokit.ParseError as ex:
        print(myokit.format_parse_error(ex, source))
        sys.exit(1)

    # Ensure proper ordering of reference and initial value files
    if ref and not isinstance(ref, myokit.Model):
        ref = model.map_to_state(ref)

    # Evaluate all derivatives, show the results
    try:
        if raw:
            derivs = model.eval_state_derivatives(state=ini)
            print('\n'.join([myokit.strfloat(x) for x in derivs]))
        else:
            print(myokit.step(model, initial=ini, reference=ref))
    except myokit.NumericalError as ee:
        e = 'Numerical error'
        n = line_width - len(e) - 2
        print('-' * int(n / 2) + ' ' + e + ' ' + '-' * (n - int(n / 2)))
        print('A numerical error occurred:')
        print(str(ee))
def compare(model1, model2):
    """
    Compares two models.
    """
    import myokit

    # Load models
    m1 = myokit.load_model(model1)
    m2 = myokit.load_model(model2)

    # Compare
    myokit.ModelComparison(m1, m2, live=True)
Пример #8
0
    def test_opencl_exporter_errors(self):
        # Checks the errors raised by the OpenCL exporter.
        e = myokit.formats.exporter('opencl')

        # Label membrane_potential must be set
        m = myokit.load_model('example')
        m.label('membrane_potential').set_label(None)
        self.assertRaisesRegex(ValueError, 'membrane_potential', self._test, e,
                               m)

        # Binding diffusion_current must be set
        m = myokit.load_model('example')
        m.binding('diffusion_current').set_binding(None)
        self.assertRaisesRegex(ValueError, 'diffusion_current', self._test, e,
                               m)
Пример #9
0
 def test_advanced_units(self):
     """
     Tests the new unit syntax where literals have units.
     """
     model = 'br-1977-units.mmt'
     m = myokit.load_model(os.path.join(myotest.DIR_DATA, model))
     m.validate()
Пример #10
0
 def test_piecewise(self):
     """
     Tests a model with a piecewise statement
     """
     m = myokit.load_model(os.path.join(myotest.DIR_DATA,
                                        'conditional.mmt'))
     # Test evaluation
     x = m.get('test.x')
     y = m.get('test.y')
     xo = m.get('test.xo')
     yo = m.get('test.yo')
     s = m.state()
     i = m.get('membrane.V').indice()
     # Test x, xo, y, yo
     s[i] = -80
     m.set_state(s)
     self.assertEqual(x.rhs().eval(), 3)
     self.assertEqual(xo.rhs().eval(), 3)
     self.assertEqual(y.rhs().eval(), 2)
     self.assertEqual(yo.rhs().eval(), 2)
     s[i] = -10
     m.set_state(s)
     self.assertEqual(x.rhs().eval(), 2)
     self.assertEqual(xo.rhs().eval(), 2)
     self.assertEqual(y.rhs().eval(), 2)
     self.assertEqual(yo.rhs().eval(), 2)
     s[i] = 30
     m.set_state(s)
     self.assertEqual(x.rhs().eval(), 1)
     self.assertEqual(xo.rhs().eval(), 1)
     self.assertEqual(y.rhs().eval(), 1)
     self.assertEqual(yo.rhs().eval(), 1)
     # Test code() output by cloning
     m.clone()
Пример #11
0
    def test_strip_expression_units(self):
        """
        Test :meth:`strip_expression_units`.
        """
        from myokit._parsing import parse_model, strip_expression_units

        m1 = myokit.load_model('example')
        m2 = parse_model(m1.code())
        self.assertEqual(m1.code(), m2.code())

        m2 = parse_model(strip_expression_units(m1.code()))
        c1 = m1.code()
        c2 = m2.code()
        self.assertNotEqual(c1, c2)
        self.assertTrue(len(c2) < len(c1))
        self.assertEqual(m1.eval_state_derivatives(),
                         m2.eval_state_derivatives())

        m2 = parse_model(strip_expression_units(m1.code().splitlines()))
        c1 = m1.code()
        c2 = m2.code()
        self.assertNotEqual(c1, c2)
        self.assertTrue(len(c2) < len(c1))
        self.assertEqual(m1.eval_state_derivatives(),
                         m2.eval_state_derivatives())
Пример #12
0
 def activation(self):
     """
     Tests the activation experiment class.
     """
     # Load model
     m = os.path.join(myotest.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()
Пример #13
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]
Пример #14
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)
Пример #15
0
def GPB_HF_Moreno(cell_type = None):
    m = myokit.load_model('grandi-2010_modified.mmt')

    # Original grandi model does not contain late channel. Changes from Tenor et al.
    # Late Na+ current. +900%
    inal = m.get('inal.GNal') # GNal multiplied by both junc and sl
    inal.set_rhs(myokit.Multiply(myokit.Number(10.0), inal.rhs()))

    # Transient outward K+ current -36%
    ito = m.get('ito.ito')
    ito.set_rhs(myokit.Multiply(myokit.Number(0.64), ito.rhs()))

    # Inward rectifier K+ current. -25% in HF
    ik1 = m.get('ik1.I_k1')
    ik1.set_rhs(myokit.Multiply(myokit.Number(0.75), ik1.rhs()))

    # Na+/ K+ pump current- Between -42% and -10% in literature. Taken mean:-26%
    inak = m.get('inak.I_nak')
    inak.set_rhs(myokit.Multiply(myokit.Number(0.9), inak.rhs()))

    # Background Na+ current +1600% in moreno (2013) from rabbit HF data
    inab = m.get('inab.GNaB') # Then slow and junc = 0, as both multiplied by GNaB
    inab.set_rhs(myokit.Multiply(myokit.Number(1.0), inab.rhs()))

    # Sarco/ endoplasmic reticulum Ca2+ pump current: -36% in HF human patients
    serca = m.get('caflux.J_serca')
    serca.set_rhs(myokit.Multiply(myokit.Number(0.64), serca.rhs()))

    # SR Ca2+ leak. +350% from rabbit HF data
    leak = m.get('caflux.J_SRleak')
    leak.set_rhs(myokit.Multiply(myokit.Number(4.5), leak.rhs()))

    return(m)
Пример #16
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()
Пример #17
0
    def test_equals(self):
        # Check that equality takes both code() and unames into account

        # Test without custom reserved names
        m1 = myokit.load_model('example')
        m2 = m1.clone()
        self.assertIsInstance(m2, myokit.Model)
        self.assertFalse(m1 is m2)
        self.assertEqual(m1, m2)
        self.assertEqual(m1, m1)

        # Test with none-model
        self.assertNotEqual(m1, None)
        self.assertNotEqual(m1, m1.code())

        # Add reserved names
        m1.reserve_unique_names('bertie')
        self.assertNotEqual(m1, m2)
        m1.reserve_unique_names('clair')
        self.assertNotEqual(m1, m2)
        m2.reserve_unique_names('clair', 'bertie')
        self.assertEqual(m1, m2)

        # Add reserved name prefixes
        m1.reserve_unique_name_prefix('aa', 'bb')
        m1.reserve_unique_name_prefix('cc', 'dd')
        self.assertNotEqual(m1, m2)
        m2.reserve_unique_name_prefix('aa', 'bb')
        m2.reserve_unique_name_prefix('cc', 'ee')
        self.assertNotEqual(m1, m2)
        m2.reserve_unique_name_prefix('cc', 'dd')
        self.assertEqual(m1, m2)
Пример #18
0
def simulate_aps(scales, model_file, beats=2, cl=1000, prepace=100,
        stimulate=True):
    """
        Generate APs using the given scalings.
    """
    # Load model
    model = myokit.load_model(model_file)

    # Apply scalings
    for var in scales:
        scale = scales[var]
        v = model.get(var)
        v.set_rhs(myokit.Multiply(myokit.Number(scale), v.rhs()))

    # Simulate with modified model
    sim = myokit.Simulation(model)

    # Add stimulus
    if stimulate:
        protocol = myokit.pacing.blocktrain(period=cl, duration=1,
                offset=50)
        sim.set_protocol(protocol)
    
    # Pre-pace for some beats
    sim.pre(prepace * cl)

    # Log some beats and return
    log = ['engine.time', 'membrane.V']
    log = ['environment.time', 'membrane.V']
    log = ['membrane.V']
    return sim.run(beats * cl, log=log, log_interval=DT).npview()
Пример #19
0
    def test_component_dependency_graph(self):
        # Test create_ and plot_ component dependency graph method, to show
        # digraph plot of variable dependencies.

        # Nodes are placed at random, so seed the generator for consistent
        # output (otherwise we risk missing full cover on some runs).
        random.seed(1)

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

        # Select matplotlib backend that doesn't require a screen
        import matplotlib
        matplotlib.use('template')

        # Create plot
        self.assertFalse(model.has_interdependent_components())
        deps.plot_component_dependency_graph(model)

        # Add cyclical component dependencies, plot again
        # This time, the acylical plotting code can't be used.
        v = model.get('ina').add_variable('ion')
        v.set_rhs('membrane.i_ion')
        self.assertTrue(model.has_interdependent_components())
        deps.plot_component_dependency_graph(model)
Пример #20
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)
Пример #21
0
    def test_linear_model_steady_state_1(self):
        # Test finding the steady-state of the Clancy model

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

        # Get steady state
        ss = np.array(m.steady_state())

        # Check that this is a valid steady state
        self.assertTrue(np.all(ss >= 0))
        self.assertTrue(np.all(ss <= 1))

        # Check that derivatives with ss are close to zero
        ss = list(ss)
        model.set_state(ss + ss)  # Model has 2 ina's
        derivs = model.evaluate_derivatives()
        for i in range(len(ss)):
            self.assertAlmostEqual(0, derivs[i])

        # Try with awful parameters
        self.assertRaisesRegex(markov.LinearModelError,
                               'positive eigenvalues',
                               m.steady_state,
                               parameters=[-1] * 21)
Пример #22
0
    def test_easyml_exporter(self):
        # Tests exporting a model

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

            # Test with simple model
            e = myokit.formats.easyml.EasyMLExporter()
            e.model(path, model)

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

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

            # Test with invalid model
            v.set_rhs('2 * V')
            self.assertRaisesRegex(myokit.ExportError, 'valid model', e.model,
                                   path, model)
Пример #23
0
    def test_linear_combination(self):
        # Tests _linear_combination()

        # Load model, to create interesting RHS
        fname = os.path.join(DIR_DATA, 'clancy-1999-fitting.mmt')
        model = myokit.load_model(fname)
        v1 = model.get('ina.C1')
        v2 = model.get('ina.C2')
        v3 = model.get('ina.C3')
        v4 = model.get('ina.IF')
        v5 = model.get('ina.IS')
        v6 = model.get('ina.O')

        # Test C1 rhs
        f = markov._linear_combination(v1.rhs(), [v1, v2, v3, v4, v5, v6])
        self.assertEqual(f[0].code(), '-(ina.a13 + ina.b12 + ina.b3)')
        self.assertEqual(f[1].code(), 'ina.a12')
        self.assertIsNone(f[2])
        self.assertEqual(f[3].code(), 'ina.a3')
        self.assertIsNone(f[4])
        self.assertEqual(f[5].code(), 'ina.b13')

        # Test double appearances
        v1.set_rhs('2 * C1 - 3 * C1 + C1 * sqrt(O) + C2 * IF')
        f = markov._linear_combination(v1.rhs(), [v1, v2, v3])
        self.assertEqual(f[0].code(), '2 + -3 + sqrt(ina.O)')
        self.assertEqual(f[1].code(), 'ina.IF')
        self.assertIsNone(f[2])
Пример #24
0
    def __init__(self, protocol, temperature, sine_wave=False):

        # Load model
        model = myokit.load_model(model_file)

        # Set reversal potential
        model.get('nernst.EK').set_rhs(erev(temperature))

        # Add sine-wave equation to model
        if sine_wave:
            model.get('membrane.V').set_rhs(
                'if(engine.time >= 3000.1 and engine.time < 6500.1,' +
                ' - 30' + ' + 54 * sin(0.007 * (engine.time - 2500.1))' +
                ' + 26 * sin(0.037 * (engine.time - 2500.1))' +
                ' + 10 * sin(0.190 * (engine.time - 2500.1))' +
                ', engine.pace)')

        # Create simulation
        self.simulation = myokit.Simulation(model)

        # Add protocol
        if isinstance(protocol, myokit.Protocol):
            self.simulation.set_protocol(protocol)
        else:
            # Apply data-clamp
            times, voltage = protocol
            self.simulation.set_fixed_form_protocol(times, voltage)

            # Set max step size
            self.simulation.set_max_step_size(0.1)

        # Set solver tolerances to values used by Kylie
        self.simulation.set_tolerance(1e-8, 1e-8)
Пример #25
0
    def test_show_expressions_for(self):
        # Test :meth:`Model.show_expressions_for(variable)`.

        m = myokit.load_model('example')
        e = m.show_expressions_for(m.get('ina.INa'))
        self.assertIn('ina.INa is a function of', e)
        self.assertEqual(len(e.splitlines()), 22)
Пример #26
0
    def test_hh_model_steady_state(self):
        # Test the method HHModel.steady_state().

        # Create model
        fname = os.path.join(DIR_DATA, 'lr-1991-fitting.mmt')
        model = myokit.load_model(fname)
        m = hh.HHModel.from_component(model.get('ina'))

        # Get steady state
        ss = np.array(m.steady_state())

        # Check that this is a valid steady state
        self.assertTrue(np.all(ss >= 0))
        self.assertTrue(np.all(ss <= 1))

        # Test if derivatives are zero
        for k, x in enumerate(['ina.m', 'ina.h', 'ina.j']):
            x = model.get(x)
            x.set_state_value(ss[k])
            self.assertAlmostEqual(x.eval(), 0)

        # Test arguments
        m.steady_state(-20, m.default_parameters())
        self.assertRaisesRegex(ValueError, 'parameter vector size',
                               m.steady_state, -20, [1])
Пример #27
0
    def test_get(self):
        # Test Model.get().

        m = myokit.load_model('example')

        # Get by name
        v = m.get('membrane.V')
        self.assertEqual(v.qname(), 'membrane.V')
        self.assertIsInstance(v, myokit.Variable)

        # Get by variable ref (useful for handling unknown input type)
        w = m.get(v)
        self.assertIs(w, v)

        # Get nested
        a = m.get('ina.m.alpha')
        self.assertEqual(a.qname(), 'ina.m.alpha')
        self.assertIsInstance(a, myokit.Variable)

        # Get component
        c = m.get('membrane')
        self.assertEqual(c.qname(), 'membrane')
        self.assertIsInstance(c, myokit.Component)

        # Get with filter
        a = m.get('ina.m.alpha', myokit.Variable)
        self.assertEqual(a.qname(), 'ina.m.alpha')
        self.assertIsInstance(a, myokit.Variable)
        self.assertRaises(KeyError, m.get, 'ina.m.alpha', myokit.Component)
        self.assertRaises(KeyError, m.get, 'ina', myokit.Variable)
        m.get('ina', myokit.Component)

        # Get non-existent
        self.assertRaises(KeyError, m.get, 'membrane.bert')
        self.assertRaises(KeyError, m.get, 'bert.bert')
Пример #28
0
    def test_against_cvode(self):
        # Validate against a cvode sim.

        # Get a model
        fname = os.path.join(DIR_DATA, 'lr-1991-fitting.mmt')
        model = myokit.load_model(fname)
        model.get('membrane.V').set_binding('pace')

        # 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 = hh.HHModel.from_component(model.get('ina'))
        s1 = hh.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'])
        self.assertEqual(np.max(e), 0)

        # Test current output is very similar
        e = np.abs(d1['ina.INa'] - d2['ina.INa'])
        self.assertLess(np.max(e), 2e-4)
Пример #29
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]))
Пример #30
0
    def test_simultaneous_event_error(self):
        # Test raising of errors on rescheduled periodic events

        p = myokit.Protocol()
        p.schedule(1, 0, 1, 1000)
        p.schedule(1, 3000, 1)
        s = AnsicEventBasedPacing(p)
        t = s.next_time()
        self.assertEqual(t, 1)
        s.advance(t)
        t = s.next_time()
        self.assertEqual(t, 1000)
        s.advance(t)
        t = s.next_time()
        self.assertEqual(t, 1001)
        s.advance(t)
        t = s.next_time()
        self.assertEqual(t, 2000)
        self.assertRaises(myokit.SimultaneousProtocolEventError, s.advance, t)

        # Test raising of errors in simulation
        p = myokit.Protocol()
        p.schedule(1, 0, 1, 10)
        p.schedule(1, 30, 1)
        m = myokit.load_model('example')
        s = myokit.Simulation(m, p)
        self.assertRaises(myokit.SimultaneousProtocolEventError, s.run, 40)