Ejemplo n.º 1
0
    def __init__(self, model, variables=None, exclude_selected=False):
        super(RhsBenchmarker, self).__init__()

        # Require a valid model
        model.validate()

        # Clone model
        self._model = model.clone()

        # Check given variables
        self._check_variables(variables)

        # Extension module id
        RhsBenchmarker._index += 1
        module_name = 'myokit_RhsBenchmarker_' + str(RhsBenchmarker._index)
        module_name += '_' + str(myokit.pid_hash())

        # Distutils arguments
        args = {
            'module_name': module_name,
            'model': self._model,
            'variables': self._variables,
            'exclude_selected': exclude_selected,
        }
        fname = os.path.join(myokit.DIR_CFUNC, SOURCE_FILE)

        # Define libraries
        libs = []
        if platform.system() != 'Windows':  # pragma: no windows cover
            libs.append('m')

        # Create extension
        self._ext = self._compile(module_name, fname, args, libs)
Ejemplo n.º 2
0
    def __init__(self, model):
        super(JacobianTracer, self).__init__()

        # Require a valid model
        model.validate()

        # Clone model
        self._model = model.clone()

        # Create ordered list of input labels used in the model
        self._inputs = [label for label, var in self._model.bindings()]

        # Extension module id
        JacobianTracer._index += 1
        module_name = 'myokit_JacobianTracer_' + str(JacobianTracer._index)
        module_name += '_' + str(myokit.pid_hash())

        # Template arguments
        args = {
            'module_name': module_name,
            'model': self._model,
            'inputs': self._inputs,
        }
        fname = os.path.join(myokit.DIR_CFUNC, SOURCE_FILE)

        # Define libraries
        libs = []
        if platform.system() != 'Windows':  # pragma: no windows cover
            libs.append('m')

        # Compile extension
        libd = []
        incd = [myokit.DIR_CFUNC]
        self._ext = self._compile(module_name, fname, args, libs, libd, incd)
Ejemplo n.º 3
0
    def _create_simulation(self, cmodel_code):
        """ Creates and compiles the C simulation module. """
        # Unique simulation id
        Simulation._index += 1
        module_name = 'myokit_sim_' + str(Simulation._index)
        module_name += '_' + str(myokit.pid_hash())

        # Arguments
        args = {
            'module_name': module_name,
            'model_code': cmodel_code,
        }
        fname = os.path.join(myokit.DIR_CFUNC, SOURCE_FILE)

        # Define libraries
        libs = [
            'sundials_cvodes',
            'sundials_nvecserial',
        ]
        if platform.system() != 'Windows':  # pragma: no windows cover
            libs.append('m')

        # Define library paths
        # Note: Sundials path on windows already includes local binaries
        libd = list(myokit.SUNDIALS_LIB)
        incd = list(myokit.SUNDIALS_INC)
        incd.append(myokit.DIR_CFUNC)

        # Create extension
        self._sim = self._compile(module_name, fname, args, libs, libd, incd)
Ejemplo n.º 4
0
    def __init__(self, model, protocol=None):
        super(ICSimulation, self).__init__()

        # Deprecated on 2021-02-25
        warnings.warn(
            'The class `ICSimulation` is deprecated. Sensitivities with'
            ' respect to initial conditions can now be calculated with the'
            ' single cell myokit.Simulation class.')

        # Require a valid model
        if not model.is_valid():
            model.validate()
        model = model.clone()
        self._model = model

        # Set protocol
        self.set_protocol(protocol)

        # Get state and default state from model
        self._state = self._model.state()
        self._default_state = list(self._state)

        # Create initial list of derivatives
        n = len(self._state)
        self._deriv = [0.0] * n**2
        for i in range(n):
            self._deriv[i * (n + 1)] = 1.0

        # Starting time
        self._time = 0

        # Default time step
        self._dt = 0
        self.set_step_size()

        # Unique simulation id
        ICSimulation._index += 1
        module_name = 'myokit_ICSimulation_' + str(ICSimulation._index)
        module_name += '_' + str(myokit.pid_hash())

        # Arguments
        args = {
            'module_name': module_name,
            'model': self._model,
        }
        fname = os.path.join(myokit.DIR_CFUNC, SOURCE_FILE)

        # Define libraries
        libs = []
        if platform.system() != 'Windows':  # pragma: no windows cover
            libs.append('m')

        # Create simulation
        libd = []
        incd = [myokit.DIR_CFUNC]
        self._sim = self._compile(module_name, fname, args, libs, libd, incd)
Ejemplo n.º 5
0
    def _create_backend(self):
        """
        Creates this simulation's backend.
        """
        # Unique simulation id
        FiberTissueSimulation._index += 1
        mname = 'myokit_sim_fiber_tissue_' + str(FiberTissueSimulation._index)
        mname += '_' + str(myokit.pid_hash())

        # Arguments
        args = {
            'module_name': mname,
            'modelf': self._modelf,
            'modelt': self._modelt,
            'vmf': self._vmf,
            'vmt': self._vmt,
            'boundf': self._bound_variablesf,
            'boundt': self._bound_variablest,
            'precision': self._precision,
            'native_math': self._native_math,
        }
        fname = os.path.join(myokit.DIR_CFUNC, SOURCE_FILE)

        # Define libraries
        libs = []
        flags = []
        plat = platform.system()
        if plat != 'Darwin':    # pragma: no macos cover
            libs.append('OpenCL')
        else:                   # pragma: no cover
            flags.append('-framework')
            flags.append('OpenCL')
        if plat != 'Windows':   # pragma: no windows cover
            libs.append('m')

        # Create extension
        libd = list(myokit.OPENCL_LIB)
        incd = list(myokit.OPENCL_INC)
        incd.append(myokit.DIR_CFUNC)
        self._sim = self._compile(
            mname, fname, args, libs, libd, incd, larg=flags,
            continue_in_debug_mode=True)
Ejemplo n.º 6
0
    def __init__(self):
        super(Compiler, self).__init__()
        # Create and cache back-end
        Compiler._index += 1

        # Define libraries
        libd = list()
        incd = list()
        incd.append(myokit.DIR_CFUNC)
        libs = []

        # Create back-end
        mname = 'myokit_compiler_info_' + str(Compiler._index)
        mname += '_' + str(myokit.pid_hash())
        fname = os.path.join(myokit.DIR_CFUNC, SOURCE_FILE)
        args = {'module_name': mname}
        try:
            Compiler._instance = self._compile(mname, fname, args, libs, libd,
                                               incd)
        except myokit.CompilationError as e:  # pragma: no cover
            Compiler._instance = False
            Compiler._message = str(e)
Ejemplo n.º 7
0
    def __init__(self):
        super(OpenCL, self).__init__()
        # Create back-end and cache it
        OpenCL._index += 1
        mname = 'myokit_opencl_info_' + str(OpenCL._index)
        mname += '_' + str(myokit.pid_hash())
        fname = os.path.join(myokit.DIR_CFUNC, SOURCE_FILE)
        args = {'module_name': mname}

        # Define libraries
        libs = []
        flags = []
        import platform
        if platform.system() != 'Darwin':  # pragma: no macos cover
            libs.append('OpenCL')
        else:  # pragma: no cover
            flags.append('-framework')
            flags.append('OpenCL')

        # Add include / linker paths
        libd = list(myokit.OPENCL_LIB)
        incd = list(myokit.OPENCL_INC)
        incd.append(myokit.DIR_CFUNC)

        try:
            OpenCL._message = None
            OpenCL._instance = self._compile(mname,
                                             fname,
                                             args,
                                             libs,
                                             libd,
                                             incd,
                                             larg=flags)
        except myokit.CompilationError as e:  # pragma: no cover
            OpenCL._instance = False
            OpenCL._message = str(e)
Ejemplo n.º 8
0
    def __init__(self, model, protocol=None, apd_var=None):
        super(Simulation, self).__init__()

        # Require a valid model
        if not model.is_valid():
            model.validate()
        model = model.clone()
        self._model = model

        # Set protocol
        self._protocol = None
        self._fixed_form_protocol = None
        self.set_protocol(protocol)

        # Check potential and threshold values
        if apd_var is None:
            self._apd_var = None
        else:
            if isinstance(apd_var, myokit.Variable):
                apd_var = apd_var.qname()
            self._apd_var = self._model.get(apd_var)
            if not self._apd_var.is_state():
                raise ValueError('The `apd_var` must be a state variable.')

        # Get state and default state from model
        self._state = self._model.state()
        self._default_state = list(self._state)

        # Last state reached before error
        self._error_state = None

        # Starting time
        self._time = 0

        # Unique simulation id
        Simulation._index += 1
        module_name = 'myokit_leg_sim_' + str(Simulation._index)
        module_name += '_' + str(myokit.pid_hash())

        # Arguments
        args = {
            'module_name': module_name,
            'model': self._model,
            'potential': self._apd_var,
        }
        fname = os.path.join(myokit.DIR_CFUNC, SOURCE_FILE)

        # Define libraries
        libs = [
            'sundials_cvode',
            'sundials_nvecserial',
        ]
        if platform.system() != 'Windows':  # pragma: no windows cover
            libs.append('m')

        # Define library paths
        # Note: Sundials path on windows already includes local binaries
        libd = list(myokit.SUNDIALS_LIB)
        incd = list(myokit.SUNDIALS_INC)
        incd.append(myokit.DIR_CFUNC)

        # Create extension
        self._sim = self._compile(module_name, fname, args, libs, libd, incd)

        # Set default tolerance values
        self._tolerance = None
        self.set_tolerance()

        # Set default min and max step size
        self._dtmax = self._dtmin = None
Ejemplo n.º 9
0
    def __init__(self, model, protocol=None, ncells=50, rl=False):
        super(Simulation1d, self).__init__()

        # Require a valid model
        model.validate()

        # Set protocol
        self.set_protocol(protocol)

        # Set number of cells
        ncells = int(ncells)
        if ncells < 1:
            raise ValueError('The number of cells must be at least 1.')
        self._ncells = ncells

        # Set rush-larsen mode
        self._rl = bool(rl)

        # Get membrane potential variable
        vm = model.label('membrane_potential')
        if vm is None:
            raise ValueError(
                'This simulation requires the membrane potential'
                ' variable to be labelled as "membrane_potential".')

        # Prepare for Rush-Larsen updates, and/or clone model
        rl_states = {}
        if self._rl:
            import myokit.lib.hh as hh

            # Convert alpha-beta formulations to inf-tau forms, cloning model
            self._model = hh.convert_hh_states_to_inf_tau_form(model, vm)
            self._vm = self._model.get(vm.qname())
            del (model, vm)

            # Get (inf, tau) tuple for every Rush-Larsen state
            for state in self._model.states():
                res = hh.get_inf_and_tau(state, self._vm)
                if res is not None:
                    rl_states[state] = res

        else:
            # Clone model, store
            self._model = model.clone()
            self._vm = self._model.get(vm.qname())
            del (model, vm)

        # Set number of cells paced
        self.set_paced_cells()

        # Set conductance
        self.set_conductance()

        # Set step size
        self.set_step_size()

        # Set remaining properties
        self._time = 0
        self._nstate = self._model.count_states()

        # Get membrane potential variable
        self._vm = self._model.label('membrane_potential')
        # Already checked this above
        # if self._vm is None:
        #    raise ValueError(
        #        'This simulation requires the membrane potential'
        #        ' variable to be labelled as "membrane_potential".')

        # Check for binding to diffusion_current
        if self._model.binding('diffusion_current') is None:
            raise ValueError(
                'This simulation requires a variable to be bound to'
                ' "diffusion_current" to pass current from one cell to the'
                ' next')

        # Set state and default state
        self._state = self._model.state() * ncells
        self._default_state = list(self._state)

        # Unique simulation id
        Simulation1d._index += 1
        module_name = 'myokit_sim1d_' + str(Simulation1d._index)
        module_name += '_' + str(myokit.pid_hash())

        # Arguments
        args = {
            'module_name': module_name,
            'model': self._model,
            'vmvar': self._vm,
            'ncells': self._ncells,
            'rl_states': rl_states,
        }
        fname = os.path.join(myokit.DIR_CFUNC, SOURCE_FILE)

        # Define libraries
        libs = []
        if platform.system() != 'Windows':  # pragma: no windows cover
            libs.append('m')

        # Create simulation
        libd = None
        incd = [myokit.DIR_CFUNC]
        self._sim = self._compile(module_name, fname, args, libs, libd, incd)
Ejemplo n.º 10
0
    def __init__(self, model, protocol=None, variables=None, parameters=None):
        super(PSimulation, self).__init__()

        # Deprecated on 2021-02-25
        warnings.warn(
            'The class `PSimulation` is deprecated. Sensitivities with'
            ' respect to parameters can now be calculated with the single cell'
            ' myokit.Simulation class.')

        # Check presence of variables and parameters arguments (are required
        # arguments but protocol is not...)
        if variables is None:
            raise ValueError(
                'Please specify a set of variables whose derivatives should be'
                ' tracked.')
        if parameters is None:
            raise ValueError('Please specify a set of parameters.')

        # Require a valid model
        if not model.is_valid():
            model.validate()
        model = model.clone()
        self._model = model

        # Set protocol
        self.set_protocol(protocol)

        # Check tracked variables
        if len(variables) != len(set(variables)):
            raise ValueError('Duplicate variable in `variables`.')
        self._variables = []
        for v in variables:
            if isinstance(v, myokit.Variable):
                v = v.qname()
            v = self._model.get(v, myokit.Variable)
            if not (v.is_state() or v.is_intermediary()):
                if v.is_bound():
                    raise ValueError(
                        'Variables to track cannot be bound to external'
                        ' inputs.')
                else:
                    raise ValueError('Variables to track cannot be constants.')
            self._variables.append(v)

        # Check parameters
        if len(parameters) != len(set(parameters)):
            raise ValueError('Duplicate parameter in `parameters`.')
        self._parameters = []
        for p in parameters:
            if isinstance(p, myokit.Variable):
                p = p.qname()
            p = self._model.get(p, myokit.Variable)
            if not p.is_literal():
                if p.is_bound():
                    raise ValueError(
                        'Parameters cannot be bound to external inputs.')
                else:
                    raise ValueError('Parameters must be literal constants.')
            self._parameters.append(p)
        del (parameters)

        # Create list of parameter values
        self._values = []
        for p in self._parameters:
            self._values.append(p.rhs().eval())

        # Get state and default state from model
        self._state = self._model.state()
        self._default_state = list(self._state)

        # Create list of state-parameter-derivatives
        ms = len(self._state)
        mp = len(self._parameters)
        self._state_ddp = [0.0] * (ms * mp)

        # Starting time
        self._time = 0

        # Default time step
        self._dt = 0
        self.set_step_size()

        # Unique simulation id
        PSimulation._index += 1
        module_name = 'myokit_PSimulation_' + str(PSimulation._index)
        module_name += '_' + str(myokit.pid_hash())

        # Arguments
        args = {
            'module_name': module_name,
            'model': self._model,
            'variables': self._variables,
            'parameters': self._parameters,
        }
        fname = os.path.join(myokit.DIR_CFUNC, SOURCE_FILE)

        # Define libraries
        libs = []
        if platform.system() != 'Windows':
            libs.append('m')

        # Create simulation
        libd = []
        incd = [myokit.DIR_CFUNC]
        self._sim = self._compile(module_name, fname, args, libs, libd, incd)