def trapped_inactivated_state_blocker(output_dir, save_model=False):

    mc = example_models.construct_four_state_chain()
    mc.mirror_model(prefix='d_')
    drug_rates = [('I', 'd_I', 'drug_on', 'drug_off')]

    for r in drug_rates:
        mc.add_both_transitions(*r)

    positive_rate_expr = ('a*exp(b*V)', ('a', 'b'))
    negative_rate_expr = ('a*exp(-b*V)', ('a', 'b'))
    kon_rate_expr = ('k*D', ('k'))
    koff_rate_expr = ('l', ('l'))

    rate_dictionary = dict(zip(['k_1', 'k_3', 'k_2', 'k_4', 'drug_on', 'drug_off'],
                               [positive_rate_expr] * 2 + [negative_rate_expr]
                               * 2 + [kon_rate_expr] + [koff_rate_expr]))

    mc.parameterise_rates(rate_dictionary, ['V', 'D'])
    mc.draw_graph(os.path.join(output_dir, "%s_trapped_inactivated_state_blocker.html" % mc.name), show_parameters=True)

    myokitmodel = mc.generate_myokit_model(drug_binding=True)
    print(myokitmodel.code())

    if save_model:
        myokit.save(filename=os.path.join("%s_trapped_inactivated_state_blocker.mmt") % mc.name, model=myokitmodel)
def mmt_import(importer, source, target=None):
    """
    Imports a model and saves it in mmt format.
    """
    import myokit

    # Get importer
    importer = myokit.formats.importer(importer)

    # Get logger
    logger = importer.logger()

    # If a target is specified, set the importer to live logging mode
    if target:
        logger.set_live(True)
    logger.log_flair(str(importer.__class__.__name__))

    # Import
    m = importer.model(source)

    # If a target is specified, save the output
    if target:
        # Save or output model to new location
        logger.log('Saving output to ' + str(target))
        myokit.save(target, m)
        logger.log('Done.')
    else:
        # Write it to screen
        print(myokit.save(None, m))
    def test_parameterise_rates(self):
        """
        Test the MarkovChain.parameterise_rates function.
        """

        mc = example_models.construct_four_state_chain()

        # Expressions to be used for the rates. The variable V (membrane
        # voltage) is shared across expressions and so it should only appear
        # once in the parameter list.

        # Output system of equations
        logging.debug("ODE system is %s",
                      str(mc.get_transition_matrix(use_parameters=True)))

        # Output reduced system of equations
        logging.debug(
            "Reduced ODE system is :%s",
            str(
                mc.eliminate_state_from_transition_matrix(
                    list(mc.graph.nodes)[:-1], use_parameters=True)))

        # Output list of parameters
        param_list = mc.get_parameter_list()
        logging.debug("parameters are %s", mc.get_parameter_list())

        self.assertEqual(param_list.count('V'), 1)

        # Generate myokit code
        myokit_model = mc.generate_myokit_model()
        myokit.save(os.path.join(self.output_dir, 'beattie_model.mmt'),
                    myokit_model)

        myokit_model = mc.generate_myokit_model(eliminate_state='IC')
        myokit.save(os.path.join(self.output_dir, 'beattie_model_reduced.mmt'),
                    myokit_model)
Esempio n. 4
0
 def save(self):
     """
     Tests if the correct parts are saved/loaded from disk using the
     ``save()`` method.
     """
     opath = os.path.join(myotest.DIR_OUT, 'loadsavetest.mmt')
     if os.path.exists(opath):
         os.remove(opath)
     # Test example loading
     m, p, x = myokit.load('example')
     self.assertIsInstance(m, myokit.Model)
     self.assertIsInstance(p, myokit.Protocol)
     self.assertIsInstance(x, str)
     # Save all three and reload
     try:
         myokit.save(opath, m, p, x)
         mm, pp, xx = myokit.load(opath)
         self.assertEqual(m.code(), mm.code())
         self.assertEqual(p.code(), pp.code())
         self.assertEqual(x, xx)
     finally:
         if os.path.exists(opath):
             os.remove(opath)
     # Save only model
     try:
         myokit.save(opath, model=m)
         with open(opath, 'r') as f:
             text = f.read()
         self.assertTrue('[[model]]' in text)
         self.assertFalse('[[protocol]]' in text)
         self.assertFalse('[[script]]' in text)
         mm, pp, xx = myokit.load(opath)
         self.assertEqual(mm.code(), m.code())
         self.assertEqual(pp, None)
         self.assertEqual(xx, None)
     finally:
         if os.path.exists(opath):
             os.remove(opath)
     # Save only protocol
     try:
         myokit.save(opath, protocol=p)
         with open(opath, 'r') as f:
             text = f.read()
         self.assertFalse('[[model]]' in text)
         self.assertTrue('[[protocol]]' in text)
         self.assertFalse('[[script]]' in text)
         mm, pp, xx = myokit.load(opath)
         self.assertEqual(mm, None)
         self.assertEqual(pp.code(), p.code())
         self.assertEqual(xx, None)
     finally:
         if os.path.exists(opath):
             os.remove(opath)
     # Save only script
     try:
         myokit.save(opath, script=x)
         with open(opath, 'r') as f:
             text = f.read()
         self.assertFalse('[[model]]' in text)
         self.assertFalse('[[protocol]]' in text)
         self.assertTrue('[[script]]' in text)
         mm, pp, xx = myokit.load(opath)
         self.assertEqual(mm, None)
         self.assertEqual(pp, None)
         self.assertEqual(xx, x)
     finally:
         if os.path.exists(opath):
             os.remove(opath)
     # Save all but model
     try:
         myokit.save(opath, protocol=p, script=x)
         with open(opath, 'r') as f:
             text = f.read()
         self.assertFalse('[[model]]' in text)
         self.assertTrue('[[protocol]]' in text)
         self.assertTrue('[[script]]' in text)
         mm, pp, xx = myokit.load(opath)
         self.assertEqual(mm, None)
         self.assertEqual(pp.code(), p.code())
         self.assertEqual(xx, x)
     finally:
         if os.path.exists(opath):
             os.remove(opath)
     # Save all but protocol
     try:
         myokit.save(opath, model=m, script=x)
         with open(opath, 'r') as f:
             text = f.read()
         self.assertTrue('[[model]]' in text)
         self.assertFalse('[[protocol]]' in text)
         self.assertTrue('[[script]]' in text)
         mm, pp, xx = myokit.load(opath)
         self.assertEqual(mm.code(), m.code())
         self.assertEqual(pp, None)
         self.assertEqual(xx, x)
     finally:
         if os.path.exists(opath):
             os.remove(opath)
     # Save all but script
     try:
         myokit.save(opath, model=m, protocol=p)
         with open(opath, 'r') as f:
             text = f.read()
         self.assertTrue('[[model]]' in text)
         self.assertTrue('[[protocol]]' in text)
         self.assertFalse('[[script]]' in text)
         mm, pp, xx = myokit.load(opath)
         self.assertEqual(mm.code(), m.code())
         self.assertEqual(pp.code(), p.code())
         self.assertEqual(xx, None)
     finally:
         if os.path.exists(opath):
             os.remove(opath)
Esempio n. 5
0
    def test_save(self):
        # Test if the correct parts are saved/loaded from disk using the
        # ``save()`` method.

        # Test example loading
        m, p, x = myokit.load('example')
        self.assertIsInstance(m, myokit.Model)
        self.assertIsInstance(p, myokit.Protocol)
        self.assertTrue(isinstance(x, basestring))

        # Save all three and reload
        with TemporaryDirectory() as d:
            opath = d.path('test.mmt')
            myokit.save(opath, m, p, x)
            mm, pp, xx = myokit.load(opath)
            self.assertEqual(m.code(), mm.code())
            self.assertEqual(p.code(), pp.code())
            self.assertEqual(x, xx)

        # Save only model
        with TemporaryDirectory() as d:
            opath = d.path('test.mmt')
            myokit.save(opath, model=m)
            with open(opath, 'r') as f:
                text = f.read()
            self.assertTrue('[[model]]' in text)
            self.assertFalse('[[protocol]]' in text)
            self.assertFalse('[[script]]' in text)
            mm, pp, xx = myokit.load(opath)
            self.assertEqual(mm.code(), m.code())
            self.assertEqual(pp, None)
            self.assertEqual(xx, None)

        # Save only protocol
        with TemporaryDirectory() as d:
            opath = d.path('test.mmt')
            myokit.save(opath, protocol=p)
            with open(opath, 'r') as f:
                text = f.read()
            self.assertFalse('[[model]]' in text)
            self.assertTrue('[[protocol]]' in text)
            self.assertFalse('[[script]]' in text)
            mm, pp, xx = myokit.load(opath)
            self.assertEqual(mm, None)
            self.assertEqual(pp.code(), p.code())
            self.assertEqual(xx, None)

        # Save only script
        with TemporaryDirectory() as d:
            opath = d.path('test.mmt')
            myokit.save(opath, script=x)
            with open(opath, 'r') as f:
                text = f.read()
            self.assertFalse('[[model]]' in text)
            self.assertFalse('[[protocol]]' in text)
            self.assertTrue('[[script]]' in text)
            mm, pp, xx = myokit.load(opath)
            self.assertEqual(mm, None)
            self.assertEqual(pp, None)
            self.assertEqual(xx, x)

        # Save all but model
        with TemporaryDirectory() as d:
            opath = d.path('test.mmt')
            myokit.save(opath, protocol=p, script=x)
            with open(opath, 'r') as f:
                text = f.read()
            self.assertFalse('[[model]]' in text)
            self.assertTrue('[[protocol]]' in text)
            self.assertTrue('[[script]]' in text)
            mm, pp, xx = myokit.load(opath)
            self.assertEqual(mm, None)
            self.assertEqual(pp.code(), p.code())
            self.assertEqual(xx, x)

        # Save all but protocol
        with TemporaryDirectory() as d:
            opath = d.path('test.mmt')
            myokit.save(opath, model=m, script=x)
            with open(opath, 'r') as f:
                text = f.read()
            self.assertTrue('[[model]]' in text)
            self.assertFalse('[[protocol]]' in text)
            self.assertTrue('[[script]]' in text)
            mm, pp, xx = myokit.load(opath)
            self.assertEqual(mm.code(), m.code())
            self.assertEqual(pp, None)
            self.assertEqual(xx, x)

        # Save all but script
        with TemporaryDirectory() as d:
            opath = d.path('test.mmt')
            myokit.save(opath, model=m, protocol=p)
            with open(opath, 'r') as f:
                text = f.read()
            self.assertTrue('[[model]]' in text)
            self.assertTrue('[[protocol]]' in text)
            self.assertFalse('[[script]]' in text)
            mm, pp, xx = myokit.load(opath)
            self.assertEqual(mm.code(), m.code())
            self.assertEqual(pp.code(), p.code())
            self.assertEqual(xx, None)

        # Save all as strings
        with TemporaryDirectory() as d:
            opath = d.path('test.mmt')
            myokit.save(opath, m, p, x)
            with open(opath, 'r') as f:
                text1 = f.read()
            myokit.save(opath, m.code(), p.code(), x)
            with open(opath, 'r') as f:
                text2 = f.read()
            self.assertEqual(text1, text2)

        # Save all as strings without [[model]] or [[protocol]] tage
        with TemporaryDirectory() as d:
            opath = d.path('test.mmt')
            myokit.save(opath, m, p, x)
            with open(opath, 'r') as f:
                text1 = f.read()
            mcode = '\n'.join(m.code().splitlines()[1:])
            pcode = '\n'.join(p.code().splitlines()[1:])
            myokit.save(opath, mcode, pcode, x)
            with open(opath, 'r') as f:
                text2 = f.read()
            self.assertEqual(text1, text2)

        # Save all, compare with string generated version
        with TemporaryDirectory() as d:
            opath = d.path('test.mmt')
            myokit.save(opath, model=m, protocol=p, script=x)
            with open(opath, 'r') as f:
                text = f.read()
            self.assertEqual(text, myokit.save(model=m, protocol=p, script=x))
Esempio n. 6
0
def clamp_experiment_model(model_filename,
                           clamped_variable_annot: str,
                           pace_variable_annotation: str,
                           protocol=None,
                           save_new_mmt_filename=None):
    """
    This function loads a mmt model, sets the equation for the desired variable
    to engine.pace (bound with the protocol), and returns the Myokit.model
    generated this way. If the user provides the argument for
    save_new_mmt_filename, the new model is also saved in the hard drive.

    :param model_filename: str
        Path and filename to the MMT model loaded.
    :param clamped_variable_annot: str
        MMT model annotation for the model variable clamped. This variable's
        values will be set by the protocol.
    :param pace_variable_annotation: str
        Model annotation for the variable bound to pace, used to read out
        information from the Myokit protocol. Usually, the annotation is either
        engine.pace or environment.pace
    :param protocol: Myokit.Protocol()
        If specified by the user, the protocol will be added to the MMT file
        saved.
    :param save_new_mmt_filename: str
        Path and filename to the location where the user wants to save the
        model ready for clamping simulations.
    :return: m: Myokit.Model()
        Returns a Myokit.Model() ready to be used with a clamping protocol to
        generate a Myokit.Simulation().
    """
    # Check that model_filename is provided as a mmt file
    if model_filename[-4:] != '.mmt':
        raise ValueError('The model_filename should lead to a MMT model.')

    # Load the MMT file depending on whether a protocol is entered as function
    # input
    if protocol is not None:
        m = myokit.load_model(model_filename)
    else:
        m, protocol, script = myokit.load(model_filename)

    # Analyse the clamped_variable_annot to find component name and variable
    # name
    i = clamped_variable_annot.index('.')
    component_name = clamped_variable_annot[0:i]
    variable_name = clamped_variable_annot[i + 1:]

    # Change the model to clamp the selected value
    original_protocol_component = m.get(component_name,
                                        class_filter=myokit.Component)

    variable_found = False

    for variable in original_protocol_component.variables():
        if variable.name() == variable_name:
            if variable.is_state():
                # Set the variable type to constant if needed
                variable.demote()
            # Bind the variable to the pace (= read from protocol)
            variable.set_rhs(pace_variable_annotation)
            variable_found = True

    if not variable_found:
        raise ValueError('The variable ' + clamped_variable_annot +
                         ' could not be found.')

    # Save the new model and protocol if the user provided the argument
    # save_new_mmt_filename
    if save_new_mmt_filename is not None:
        if protocol is not None:
            myokit.save(save_new_mmt_filename, model=m, protocol=protocol)
        else:
            myokit.save(save_new_mmt_filename, model=m)

    return m