Beispiel #1
0
    def __init__(self, group, when='resets', order=None, event='spike'):
        self.event = event
        # Since this now works for general events not only spikes, we have to
        # pass the information about which variable to use to the template,
        # it can not longer simply refer to "_spikespace"
        eventspace_name = '_{}space'.format(event)
        template_kwds = {'eventspace_variable': group.variables[eventspace_name]}
        needed_variables= [eventspace_name]
        order = order if order is not None else group.order
        CodeRunner.__init__(self, group,
                            'reset',
                            code='',  # will be set in update_abstract_code
                            clock=group.clock,
                            when=when,
                            order=order,
                            name=group.name + '_resetter*',
                            override_conditional_write=['not_refractory'],
                            needed_variables=needed_variables,
                            template_kwds=template_kwds)

        # Check the abstract code for unit mismatches (only works if the
        # namespace is already complete)
        try:
            self.update_abstract_code(level=1)
            check_code_units(self.abstract_code, self.group)
        except KeyError:
            pass
Beispiel #2
0
    def __init__(self, group, when='thresholds', event='spike'):
        self.event = event
        if group._refractory is False or event != 'spike':
            template_kwds = {'_uses_refractory': False}
            needed_variables = []
        else:
            template_kwds = {'_uses_refractory': True}
            needed_variables=['t', 'not_refractory', 'lastspike']
        # Since this now works for general events not only spikes, we have to
        # pass the information about which variable to use to the template,
        # it can not longer simply refer to "_spikespace"
        eventspace_name = '_{}space'.format(event)
        template_kwds['eventspace_variable'] = group.variables[eventspace_name]
        needed_variables.append(eventspace_name)
        CodeRunner.__init__(self, group,
                            'threshold',
                            code='',  # will be set in update_abstract_code
                            clock=group.clock,
                            when=when,
                            order=group.order,
                            name=group.name+'_thresholder*',
                            needed_variables=needed_variables,
                            template_kwds=template_kwds)

        # Check the abstract code for unit mismatches (only works if the
        # namespace is already complete)
        try:
            self.update_abstract_code(level=1)
            check_code_units(self.abstract_code, self.group)
        except KeyError:
            pass
Beispiel #3
0
    def __init__(self, group):
        GroupCodeRunner.__init__(self, group,
                                 'reset',
                                 when=(group.clock, 'resets'),
                                 name=group.name + '_resetter*')

        # Check the abstract code for unit mismatches (only works if the
        # namespace is already complete)
        self.update_abstract_code()
        check_code_units(self.abstract_code, self.group, ignore_keyerrors=True)
Beispiel #4
0
    def get_with_expression(self, variable_name, variable, code,
                            level=0, run_namespace=None):
        '''
        Gets a variable using a string expression. Is called by
        `VariableView.get_item` for statements such as
        ``print G.v['g_syn > 0']``.

        Parameters
        ----------
        variable_name : str
            The name of the variable in its context (e.g. ``'g_post'`` for a
            variable with name ``'g'``)
        variable : `ArrayVariable`
            The `ArrayVariable` object for the variable to be set
        code : str
            An expression that states a condition for elements that should be
            selected. Can contain references to indices, such as ``i`` or ``j``
            and to state variables. For example: ``'i>3 and v>0*mV'``.
        level : int, optional
            How much farther to go up in the stack to find the implicit
            namespace (if used, see `run_namespace`).
        run_namespace : dict-like, optional
            An additional namespace that is used for variable lookup (if not
            defined, the implicit namespace of local variables is used).
        '''
        if variable.scalar:
            raise IndexError(('Cannot access the variable %s with a '
                              'string expression, it is a scalar '
                              'variable.') % variable_name)
        # Add the recorded variable under a known name to the variables
        # dictionary. Important to deal correctly with
        # the type of the variable in C++
        variables = Variables(None)
        variables.add_auxiliary_variable('_variable', unit=variable.unit,
                                         dtype=variable.dtype,
                                         scalar=variable.scalar)
        variables.add_auxiliary_variable('_cond', unit=Unit(1), dtype=np.bool)

        abstract_code = '_variable = ' + variable_name + '\n'
        abstract_code += '_cond = ' + code
        check_code_units(abstract_code, self,
                         additional_variables=variables,
                         level=level+2,
                         run_namespace=run_namespace)
        codeobj = create_runner_codeobj(self,
                                        abstract_code,
                                        'group_variable_get_conditional',
                                        additional_variables=variables,
                                        level=level+2,
                                        run_namespace=run_namespace,
                                        )
        return codeobj()
Beispiel #5
0
    def __init__(self, group):
        CodeRunner.__init__(self, group,
                            'reset',
                            when=(group.clock, 'resets'),
                            name=group.name + '_resetter*',
                            override_conditional_write=['not_refractory'])

        # Check the abstract code for unit mismatches (only works if the
        # namespace is already complete)
        try:
            self.update_abstract_code(level=1)
            check_code_units(self.abstract_code, self.group)
        except KeyError:
            pass
Beispiel #6
0
    def set_with_expression_conditional(self, varname, variable, cond,
                                        code, check_units=True, level=0,
                                        run_namespace=None):
        '''
        Sets a variable using a string expression and string condition. Is
        called by `VariableView.set_item` for statements such as
        ``S.var['i!=j'] = 'exp(-abs(i-j)/space_constant)*nS'``

        Parameters
        ----------
        varname : str
            The name of the variable to be set.
        variable : `ArrayVariable`
            The `ArrayVariable` object for the variable to be set.
        cond : str
            The string condition for which the variables should be set.
        code : str
            The code that should be executed to set the variable values.
        check_units : bool, optional
            Whether to check the units of the expression.
        level : int, optional
            How much farther to go up in the stack to find the implicit
            namespace (if used, see `run_namespace`).
        run_namespace : dict-like, optional
            An additional namespace that is used for variable lookup (if not
            defined, the implicit namespace of local variables is used).
        '''
        if variable.scalar and cond != 'True':
            raise IndexError(('Cannot conditionally set the scalar variable '
                              '%s.') % varname)
        abstract_code_cond = '_cond = '+cond
        abstract_code = varname + ' = ' + code
        variables = Variables(None)
        variables.add_auxiliary_variable('_cond', unit=Unit(1), dtype=np.bool)
        check_code_units(abstract_code_cond, self,
                         additional_variables=variables,
                         level=level+2,
                         run_namespace=run_namespace)
        # TODO: Have an additional argument to avoid going through the index
        # array for situations where iterate_all could be used
        codeobj = create_runner_codeobj(self,
                                        {'condition': abstract_code_cond,
                                         'statement': abstract_code},
                                        'group_variable_set_conditional',
                                        additional_variables=variables,
                                        check_units=check_units,
                                        level=level+2,
                                        run_namespace=run_namespace)
        codeobj()
Beispiel #7
0
    def get_with_expression(self, group, variable_name, variable, code, level=0):
        '''
        Gets a variable using a string expression. Is called by
        `VariableView.get_item` for statements such as
        ``print G.v['g_syn > 0']``.

        Parameters
        ----------
        group : `Group`
            The group providing the context for the indexing.
        variable_name : str
            The name of the variable in its context (e.g. ``'g_post'`` for a
            variable with name ``'g'``)
        variable : `ArrayVariable`
            The `ArrayVariable` object for the variable to be set
        code : str
            An expression that states a condition for elements that should be
            selected. Can contain references to indices, such as ``i`` or ``j``
            and to state variables. For example: ``'i>3 and v>0*mV'``.
        level : int, optional
            How much farther to go up in the stack to find the namespace.
        '''
        # interpret the string expression
        namespace = get_local_namespace(level+1)
        additional_namespace = ('implicit-namespace', namespace)
        # Add the recorded variable under a known name to the variables
        # dictionary. Important to deal correctly with
        # the type of the variable in C++
        variables = Variables(None)
        variables.add_auxiliary_variable('_variable', unit=variable.unit,
                                         dtype=variable.dtype,
                                         scalar=variable.scalar,
                                         is_bool=variable.is_bool)
        variables.add_auxiliary_variable('_cond', unit=Unit(1), dtype=np.bool,
                                         is_bool=True)

        abstract_code = '_variable = ' + variable_name + '\n'
        abstract_code += '_cond = ' + code
        check_code_units(abstract_code, group,
                         additional_namespace=additional_namespace,
                         additional_variables=variables)
        codeobj = create_runner_codeobj(group,
                                        abstract_code,
                                        'group_variable_get_conditional',
                                        additional_variables=variables,
                                        additional_namespace=additional_namespace,
                                        )
        return codeobj()
Beispiel #8
0
    def set_with_expression_conditional(self, group, varname, variable, cond,
                                        code, check_units=True, level=0):
        '''
        Sets a variable using a string expression and string condition. Is
        called by `VariableView.set_item` for statements such as
        ``S.var['i!=j'] = 'exp(-abs(i-j)/space_constant)*nS'``

        Parameters
        ----------
        group : `Group`
            The group providing the context for the indexing.
        varname : str
            The name of the variable to be set.
        variable : `ArrayVariable`
            The `ArrayVariable` object for the variable to be set.
        cond : str
            The string condition for which the variables should be set.
        code : str
            The code that should be executed to set the variable values.
        check_units : bool, optional
            Whether to check the units of the expression.
        level : int, optional
            How much farther to go up in the stack to find the namespace.
        '''

        abstract_code_cond = '_cond = '+cond
        abstract_code = varname + ' = ' + code
        namespace = get_local_namespace(level + 1)
        additional_namespace = ('implicit-namespace', namespace)
        variables = Variables(None)
        variables.add_auxiliary_variable('_cond', unit=Unit(1), dtype=np.bool,
                                         is_bool=True)
        check_code_units(abstract_code_cond, group,
                         additional_variables=variables,
                         additional_namespace=additional_namespace)
        # TODO: Have an additional argument to avoid going through the index
        # array for situations where iterate_all could be used
        codeobj = create_runner_codeobj(group,
                                 {'condition': abstract_code_cond,
                                  'statement': abstract_code},
                                 'group_variable_set_conditional',
                                 additional_variables=variables,
                                 additional_namespace=additional_namespace,
                                 check_units=check_units)
        codeobj()
Beispiel #9
0
    def __init__(self, group):
        if group._refractory is False:
            template_kwds = {'_uses_refractory': False}
            needed_variables = []
        else:
            template_kwds = {'_uses_refractory': True}
            needed_variables=['t', 'not_refractory', 'lastspike']
        GroupCodeRunner.__init__(self, group,
                                 'threshold',
                                 when=(group.clock, 'thresholds'),
                                 name=group.name+'_thresholder*',
                                 needed_variables=needed_variables,
                                 template_kwds=template_kwds)

        # Check the abstract code for unit mismatches (only works if the
        # namespace is already complete)
        self.update_abstract_code()
        check_code_units(self.abstract_code, self.group, ignore_keyerrors=True)
Beispiel #10
0
 def before_run(self, namespace):
     self.update_abstract_code()
     # If the GroupCodeRunner has variables, add them
     if hasattr(self, 'variables'):
         additional_variables = self.variables
     else:
         additional_variables = None
     if self.check_units:
         check_code_units(self.abstract_code, self.group,
                          additional_variables, namespace)
     self.codeobj = create_runner_codeobj(group=self.group,
                                          code=self.abstract_code,
                                          template_name=self.template,
                                          name=self.name+'_codeobject*',
                                          check_units=self.check_units,
                                          additional_variables=additional_variables,
                                          additional_namespace=namespace,
                                          needed_variables=self.needed_variables,
                                          template_kwds=self.template_kwds)
     self.code_objects[:] = [weakref.proxy(self.codeobj)]
Beispiel #11
0
    def __getitem__(self, item):
        if isinstance(item, basestring):
            variables = Variables(None)
            variables.add_auxiliary_variable("_indices", unit=Unit(1), dtype=np.int32)
            variables.add_auxiliary_variable("_cond", unit=Unit(1), dtype=np.bool)

            abstract_code = "_cond = " + item
            check_code_units(abstract_code, self.group, additional_variables=variables, level=1)
            from brian2.devices.device import get_default_codeobject_class

            codeobj = create_runner_codeobj(
                self.group,
                abstract_code,
                "group_get_indices",
                additional_variables=variables,
                level=1,
                codeobj_class=get_default_codeobject_class("codegen.string_expression_target"),
            )
            return codeobj()
        else:
            return self.indices(item)
Beispiel #12
0
    def __getitem__(self, item):
        if isinstance(item, basestring):
            variables = Variables(None)
            variables.add_auxiliary_variable('_indices', unit=Unit(1),
                                             dtype=np.int32)
            variables.add_auxiliary_variable('_cond', unit=Unit(1),
                                             dtype=np.bool)

            abstract_code = '_cond = ' + item
            check_code_units(abstract_code, self.group,
                             additional_variables=variables,
                             level=1)
            codeobj = create_runner_codeobj(self.group,
                                            abstract_code,
                                            'group_get_indices',
                                            additional_variables=variables,
                                            level=1
                                            )
            return codeobj()
        else:
            return self.group.calc_indices(item)
Beispiel #13
0
    def __init__(self, group):
        if group._refractory is False:
            template_kwds = {'_uses_refractory': False}
            needed_variables = []
        else:
            template_kwds = {'_uses_refractory': True}
            needed_variables=['t', 'not_refractory', 'lastspike']
        CodeRunner.__init__(self, group,
                            'threshold',
                            when=(group.clock, 'thresholds'),
                            name=group.name+'_thresholder*',
                            needed_variables=needed_variables,
                            template_kwds=template_kwds)

        # Check the abstract code for unit mismatches (only works if the
        # namespace is already complete)
        try:
            self.update_abstract_code(level=1)
            check_code_units(self.abstract_code, self.group)
        except KeyError:
            pass
Beispiel #14
0
    def __getitem__(self, item):
        if isinstance(item, basestring):
            variables = Variables(None)
            variables.add_auxiliary_variable('_indices', unit=Unit(1),
                                             dtype=np.int32)
            variables.add_auxiliary_variable('_cond', unit=Unit(1),
                                             dtype=np.bool)

            abstract_code = '_cond = ' + item
            check_code_units(abstract_code, self.group,
                             additional_variables=variables,
                             level=1)
            from brian2.devices.device import get_default_codeobject_class
            codeobj = create_runner_codeobj(self.group,
                                            abstract_code,
                                            'group_get_indices',
                                            additional_variables=variables,
                                            level=1,
                                            codeobj_class=get_default_codeobject_class('codegen.string_expression_target')
                                            )
            return codeobj()
        else:
            return self.indices(item)
Beispiel #15
0
    def __init__(self, group):
        if group._refractory is False:
            template_kwds = {'_uses_refractory': False}
            needed_variables = []
        else:
            template_kwds = {'_uses_refractory': True}
            needed_variables=['t', 'not_refractory', 'lastspike']
        CodeRunner.__init__(self, group,
                            'threshold',
                            code='',  # will be set in update_abstract_code
                            clock=group.clock,
                            when='thresholds',
                            order=group.order,
                            name=group.name+'_thresholder*',
                            needed_variables=needed_variables,
                            template_kwds=template_kwds)

        # Check the abstract code for unit mismatches (only works if the
        # namespace is already complete)
        try:
            self.update_abstract_code(level=1)
            check_code_units(self.abstract_code, self.group)
        except KeyError:
            pass
Beispiel #16
0
    def __getitem__(self, item):
        if isinstance(item, basestring):
            namespace = get_local_namespace(1)
            additional_namespace = ('implicit-namespace', namespace)
            variables = Variables(None)
            variables.add_auxiliary_variable('_indices', unit=Unit(1),
                                             dtype=np.int32)
            variables.add_auxiliary_variable('_cond', unit=Unit(1),
                                             dtype=np.bool,
                                             is_bool=True)

            abstract_code = '_cond = ' + item
            check_code_units(abstract_code, self.group,
                             additional_namespace=additional_namespace,
                             additional_variables=variables)
            codeobj = create_runner_codeobj(self.group,
                                            abstract_code,
                                            'group_get_indices',
                                            additional_variables=variables,
                                            additional_namespace=additional_namespace,
                                            )
            return codeobj()
        else:
            return self.group.calc_indices(item)