コード例 #1
0
ファイル: statemonitor.py プロジェクト: divyashivaram/brian2
    def __getattr__(self, item):
        # We do this because __setattr__ and __getattr__ are not active until
        # _group_attribute_access_active attribute is set, and if it is set,
        # then __getattr__ will not be called. Therefore, if getattr is called
        # with this name, it is because it hasn't been set yet and so this
        # method should raise an AttributeError to agree that it hasn't been
        # called yet.
        if item == '_group_attribute_access_active':
            raise AttributeError
        if not hasattr(self, '_group_attribute_access_active'):
            raise AttributeError

        # TODO: Decide about the interface
        if item == 't':
            return Quantity(self._t.data.copy(), dim=second.dim)
        elif item == 't_':
            return self._t.data.copy()
        elif item in self.record_variables:
            unit = self.variables[item].unit
            if have_same_dimensions(unit, 1):
                return self._values[item].data.T.copy()
            else:
                return Quantity(self._values[item].data.T.copy(),
                                dim=unit.dim)
        elif item.endswith('_') and item[:-1] in self.record_variables:
            return self._values[item[:-1]].data.T.copy()
        else:
            raise AttributeError('Unknown attribute %s' % item)
コード例 #2
0
ファイル: statemonitor.py プロジェクト: ttxtea/brian2
    def __getattr__(self, item):
        # We do this because __setattr__ and __getattr__ are not active until
        # _group_attribute_access_active attribute is set, and if it is set,
        # then __getattr__ will not be called. Therefore, if getattr is called
        # with this name, it is because it hasn't been set yet and so this
        # method should raise an AttributeError to agree that it hasn't been
        # called yet.
        if item == '_group_attribute_access_active':
            raise AttributeError
        if not hasattr(self, '_group_attribute_access_active'):
            raise AttributeError

        mon = self.monitor
        if item == 't':
            return Quantity(mon.variables['t'].get_value(), dim=second.dim)
        elif item == 't_':
            return mon.variables['t'].get_value()
        elif item in mon.record_variables:
            unit = mon.variables[item].unit
            return Quantity(mon.variables[item].get_value().T[self.indices],
                            dim=unit.dim, copy=True)
        elif item.endswith('_') and item[:-1] in mon.record_variables:
            return mon.variables[item[:-1]].get_value().T[self.indices].copy()
        else:
            raise AttributeError('Unknown attribute %s' % item)
コード例 #3
0
ファイル: test_units.py プロジェクト: treestreamymw/brian2
def test_inplace_on_scalars():
    # We want "copy semantics" for in-place operations on scalar quantities
    # in the same way as for Python scalars
    for scalar in [3 * mV, 3 * mV / mV]:
        scalar_reference = scalar
        scalar_copy = Quantity(scalar, copy=True)
        scalar += scalar_copy
        assert_equal(scalar_copy, scalar_reference)
        scalar *= 1.5
        assert_equal(scalar_copy, scalar_reference)
        scalar /= 2
        assert_equal(scalar_copy, scalar_reference)

        # also check that it worked correctly for the scalar itself
        assert_allclose(scalar, (scalar_copy + scalar_copy) * 1.5 / 2)

    # For arrays, it should use reference semantics
    for vector in [[3] * mV, [3] * mV / mV]:
        vector_reference = vector
        vector_copy = Quantity(vector, copy=True)
        vector += vector_copy
        assert_equal(vector, vector_reference)
        vector *= 1.5
        assert_equal(vector, vector_reference)
        vector /= 2
        assert_equal(vector, vector_reference)

        # also check that it worked correctly for the vector itself
        assert_allclose(vector, (vector_copy + vector_copy) * 1.5 / 2)
コード例 #4
0
ファイル: test_units.py プロジェクト: francesconero/brian2
def test_construction():
    ''' Test the construction of quantity objects '''
    q = 500 * ms
    assert_quantity(q, 0.5, second)
    q = np.float64(500) * ms
    assert_quantity(q, 0.5, second)
    q = np.array(500) * ms
    assert_quantity(q, 0.5, second)
    q = np.array([500, 1000]) * ms
    assert_quantity(q, np.array([0.5, 1]), second)
    q = Quantity(500)
    assert_quantity(q, 500, 1)
    q = Quantity(500, dim=second.dim)
    assert_quantity(q, 500, second)
    q = Quantity([0.5, 1], dim=second.dim)
    assert_quantity(q, np.array([0.5, 1]), second)
    q = Quantity(np.array([0.5, 1]), dim=second.dim)
    assert_quantity(q, np.array([0.5, 1]), second)
    q = Quantity([500 * ms, 1 * second])
    assert_quantity(q, np.array([0.5, 1]), second)
    q = Quantity.with_dimensions(np.array([0.5, 1]), second=1)
    assert_quantity(q, np.array([0.5, 1]), second)
    q = [0.5, 1] * second
    assert_quantity(q, np.array([0.5, 1]), second)

    # dimensionless quantities
    q = Quantity([1, 2, 3])
    assert_quantity(q, np.array([1, 2, 3]), Unit(1))
    q = Quantity(np.array([1, 2, 3]))
    assert_quantity(q, np.array([1, 2, 3]), Unit(1))
    q = Quantity([])
    assert_quantity(q, np.array([]), Unit(1))

    # copying/referencing a quantity
    q1 = Quantity.with_dimensions(np.array([0.5, 1]), second=1)
    q2 = Quantity(q1) # no copy
    assert_quantity(q2, np.asarray(q1), q1)
    q2[0] = 3 * second
    assert_equal(q1[0], 3*second)

    q1 = Quantity.with_dimensions(np.array([0.5, 1]), second=1)
    q2 = Quantity(q1, copy=True) # copy
    assert_quantity(q2, np.asarray(q1), q1)
    q2[0] = 3 * second
    assert_equal(q1[0], 0.5*second)

    # Illegal constructor calls
    assert_raises(TypeError, lambda: Quantity([500 * ms, 1]))
    assert_raises(TypeError, lambda: Quantity(['some', 'nonsense']))
    assert_raises(DimensionMismatchError, lambda: Quantity([500 * ms,
                                                            1 * volt]))
    assert_raises(DimensionMismatchError, lambda: Quantity([500 * ms],
                                                           dim=volt.dim))
    q = Quantity.with_dimensions(np.array([0.5, 1]), second=1)
    assert_raises(DimensionMismatchError, lambda: Quantity(q, dim=volt.dim))
コード例 #5
0
ファイル: timedarray.py プロジェクト: yzerlaut/brian2
 def timed_array_func(t, i):
     # We round according to the current defaultclock.dt
     K = _find_K(float(defaultclock.dt), dt)
     epsilon = dt / K
     time_step = np.clip(np.int_(np.round(np.asarray(t/epsilon)) / K),
                 0, len(values)-1)
     return Quantity(values[time_step, i], dim=dimensions)
コード例 #6
0
ファイル: spikegeneratorgroup.py プロジェクト: svadams/brian2
    def _check_args(self, indices, times, period, N, sorted):
        times = Quantity(times)
        if len(indices) != len(times):
            raise ValueError(
                ('Length of the indices and times array must '
                 'match, but %d != %d') % (len(indices), len(times)))
        if period < 0 * second:
            raise ValueError('The period cannot be negative.')
        elif len(times) and period <= np.max(times):
            raise ValueError(
                'The period has to be greater than the maximum of '
                'the spike times')
        if len(times) and np.min(times) < 0 * second:
            raise ValueError('Spike times cannot be negative')
        if len(indices) and (np.min(indices) < 0 or np.max(indices) >= N):
            raise ValueError('Indices have to lie in the interval [0, %d[' % N)

        times = np.asarray(times)
        indices = np.asarray(indices)
        if not sorted:
            # sort times and indices first by time, then by indices
            I = np.lexsort((indices, times))
            indices = indices[I]
            times = times[I]

        # We store the indices and times also directly in the Python object,
        # this way we can use them for checks in `before_run` even in standalone
        # TODO: Remove this when the checks in `before_run` have been moved to the template
        self._neuron_index = indices
        self._spike_time = times
        #: "Dirty flag" that will be set when spikes are changed after the
        #: `before_run` check
        self._spikes_changed = True

        return indices, times
コード例 #7
0
    def get_item(self, item, level=0, namespace=None):
        '''
        Get the value of this variable. Called by `__getitem__`.

        Parameters
        ----------
        item : slice, `ndarray` or string
            The index for the setting operation
        level : int, optional
            How much farther to go up in the stack to find the implicit
            namespace (if used, see `run_namespace`).
        namespace : dict-like, optional
            An additional namespace that is used for variable lookup (if not
            defined, the implicit namespace of local variables is used).
        '''
        variable = self.variable
        if isinstance(item, basestring):
            values = self.group.get_with_expression(self.name,
                                                    variable,
                                                    item,
                                                    level=level + 1,
                                                    run_namespace=namespace)
        else:
            values = self.group.get_with_index_array(self.name, variable, item)

        if self.unit is None:
            return values
        else:
            return Quantity(values, self.unit.dimensions)
コード例 #8
0
ファイル: functions.py プロジェクト: ttxtea/brian2
 def wrapper_function(*args):
     if not len(args) == len(self._function._arg_units):
         raise ValueError(('Function %s got %d arguments, '
                           'expected %d') % (self._function.pyfunc.__name__, len(args),
                                             len(self._function._arg_units)))
     new_args = [Quantity.with_dimensions(arg, get_dimensions(arg_unit))
                 for arg, arg_unit in zip(args, self._function._arg_units)]
     result = orig_func(*new_args)
     return_unit = self._function._return_unit
     if return_unit is 1 or return_unit.dim is DIMENSIONLESS:
         fail_for_dimension_mismatch(result,
                                     return_unit,
                                     'The function %s returned '
                                     '{value}, but it was expected '
                                     'to return a dimensionless '
                                     'quantity' % orig_func.__name__,
                                     value=result)
     else:
         fail_for_dimension_mismatch(result,
                                     return_unit,
                                     ('The function %s returned '
                                      '{value}, but it was expected '
                                      'to return a quantity with '
                                      'units %r') % (orig_func.__name__,
                                                     return_unit),
                                     value=result)
     return np.asarray(result)
コード例 #9
0
ファイル: spikegeneratorgroup.py プロジェクト: flinz/brian2
    def set_spikes(self, indices, times, period=1e100 * second, sorted=False):
        '''
        set_spikes(indices, times, period=1e100*second, sorted=False)

        Change the spikes that this group will generate.

        This can be used to set the input for a second run of a model based on
        the output of a first run (if the input for the second run is already
        known before the first run, then all the information should simply be
        included in the initial `SpikeGeneratorGroup` initializer call,
        instead).

        Parameters
        ----------
        indices : array of integers
            The indices of the spiking cells
        times : `Quantity`
            The spike times for the cells given in ``indices``. Has to have the
            same length as ``indices``.
        period : `Quantity`, optional
            If this is specified, it will repeat spikes with this period.
        sorted : bool, optional
            Whether the given indices and times are already sorted. Set to
            ``True`` if your events are already sorted (first by spike time,
            then by index), this can save significant time at construction if
            your arrays contain large numbers of spikes. Defaults to ``False``.
        '''
        times = Quantity(times)
        if len(indices) != len(times):
            raise ValueError(
                ('Length of the indices and times array must '
                 'match, but %d != %d') % (len(indices), len(times)))

        if period < 0 * second:
            raise ValueError('The period cannot be negative.')
        elif len(times) and period <= np.max(times):
            raise ValueError(
                'The period has to be greater than the maximum of '
                'the spike times')

        if not sorted:
            # sort times and indices first by time, then by indices
            rec = np.rec.fromarrays([times, indices], names=['t', 'i'])
            rec.sort()
            times = np.ascontiguousarray(rec.t)
            indices = np.ascontiguousarray(rec.i)

        self.variables['period'].set_value(period)
        self.variables['neuron_index'].resize(len(indices))
        self.variables['spike_time'].resize(len(indices))
        self.variables['spike_number'].resize(len(indices))
        self.variables['spike_number'].set_value(np.arange(len(indices)))
        self.variables['neuron_index'].set_value(indices)
        self.variables['spike_time'].set_value(times)
        self.variables['_lastindex'].set_value(0)

        # Update the internal variables used in `SpikeGeneratorGroup.before_run`
        self._neuron_index = indices
        self._spike_time = times
        self._spikes_changed = True
コード例 #10
0
ファイル: functions.py プロジェクト: francesconero/brian2
 def wrapper_function(*args):
     if not len(args) == len(self._function._arg_units):
         raise ValueError(('Function %s got %d arguments, '
                           'expected %d') % (self._function.name, len(args),
                                             len(self._function._arg_units)))
     new_args = [Quantity.with_dimensions(arg, get_dimensions(arg_unit))
                 for arg, arg_unit in zip(args, self._function._arg_units)]
     result = orig_func(*new_args)
     fail_for_dimension_mismatch(result, self._function._return_unit)
     return np.asarray(result)
コード例 #11
0
ファイル: test_units.py プロジェクト: treestreamymw/brian2
def test_list():
    '''
    Test converting to and from a list.
    '''
    values = [3 * mV, np.array([1, 2]) * mV, np.arange(12).reshape(4, 3) * mV]
    for value in values:
        l = value.tolist()
        from_list = Quantity(l)
        assert have_same_dimensions(from_list, value)
        assert_equal(from_list, value)
コード例 #12
0
ファイル: spikemonitor.py プロジェクト: ttxtea/brian2
 def _values_dict(self, first_pos, sort_indices, used_indices, var):
     sorted_values = self.state(var, use_units=False)[sort_indices]
     dim = self.variables[var].unit.dim
     event_values = {}
     current_pos = 0  # position in the all_indices array
     for idx in xrange(len(self.source)):
         if current_pos < len(used_indices) and used_indices[current_pos] == idx:
             if current_pos < len(used_indices) - 1:
                 event_values[idx] = Quantity(sorted_values[
                                              first_pos[current_pos]:
                                              first_pos[current_pos + 1]],
                                              dim=dim, copy=False)
             else:
                 event_values[idx] = Quantity(
                     sorted_values[first_pos[current_pos]:],
                     dim=dim, copy=False)
             current_pos += 1
         else:
             event_values[idx] = Quantity([], dim=dim)
     return event_values
コード例 #13
0
 def __getitem__(self, i):
     variable = self.variable
     if variable.scalar:
         if not (i == slice(None) or i == 0 or (hasattr(i, '__len__') and len(i) == 0)):
             raise IndexError('Variable is a scalar variable.')
         indices = 0
     else:
         indices = self.group.indices[self.group.variable_indices[self.name]][i]
     if self.unit is None or have_same_dimensions(self.unit, Unit(1)):
         return variable.get_value()[indices]
     else:
         return Quantity(variable.get_value()[indices], self.unit.dimensions)
コード例 #14
0
ファイル: device.py プロジェクト: SudShekhar/brian2
    def variableview_set_with_index_array(self, variableview, item, value,
                                          check_units):
        if isinstance(item, slice) and item == slice(None):
            item = 'True'
        value = Quantity(value)

        if (isinstance(item, int) or
            (isinstance(item, np.ndarray)
             and item.shape == ())) and value.size == 1:
            array_name = self.get_array_name(variableview.variable,
                                             access_data=False)
            # For a single assignment, generate a code line instead of storing the array
            self.main_queue.append(
                ('set_by_single_value', (array_name, item, float(value))))

        elif (value.size == 1 and item == 'True'
              and variableview.index_var_name == '_idx'):
            # set the whole array to a scalar value
            if have_same_dimensions(value, 1):
                # Avoid a representation as "Quantity(...)" or "array(...)"
                value = float(value)
            variableview.set_with_expression_conditional(
                cond=item, code=repr(value), check_units=check_units)
        # Simple case where we don't have to do any indexing
        elif (item == 'True' and variableview.index_var == '_idx'):
            self.fill_with_array(variableview.variable, value)
        else:
            # We have to calculate indices. This will not work for synaptic
            # variables
            try:
                indices = np.asarray(
                    variableview.indexing(item,
                                          index_var=variableview.index_var))
            except NotImplementedError:
                raise NotImplementedError(
                    ('Cannot set variable "%s" this way in '
                     'standalone, try using string '
                     'expressions.') % variableview.name)
            # Using the std::vector instead of a pointer to the underlying
            # data for dynamic arrays is fast enough here and it saves us some
            # additional work to set up the pointer
            arrayname = self.get_array_name(variableview.variable,
                                            access_data=False)
            staticarrayname_index = self.static_array('_index_' + arrayname,
                                                      indices)
            if (indices.shape != () and
                (value.shape == () or (value.size == 1 and indices.size > 1))):
                value = np.repeat(value, indices.size)
            staticarrayname_value = self.static_array('_value_' + arrayname,
                                                      value)
            self.main_queue.append(
                ('set_array_by_array', (arrayname, staticarrayname_index,
                                        staticarrayname_value)))
コード例 #15
0
ファイル: hears.py プロジェクト: zeph1yr/brian2
 def new_f(*args, **kwds):
     newargs = []
     newkwds = {}
     for arg in args:
         newargs.append(modify_arg(arg))
     for k, v in kwds.items():
         newkwds[k] = modify_arg(v)
     rv = f(*newargs, **newkwds)
     if rv.__class__==b1h.Sound:
         rv.__class__ = BridgeSound
     elif isinstance(rv, b1.Quantity):
         rv = Quantity.with_dimensions(float(rv), rv.dim._dims)
     return rv
コード例 #16
0
ファイル: hears.py プロジェクト: msGenDev/brian2
 def new_f(*args, **kwds):
     newargs = []
     newkwds = {}
     for arg in args:
         newargs.append(modify_arg(arg))
     for k, v in kwds.items():
         newkwds[k] = modify_arg(v)
     rv = f(*newargs, **newkwds)
     if rv.__class__==b1h.Sound:
         rv.__class__ = BridgeSound
     elif isinstance(rv, b1.Quantity):
         rv = Quantity.with_dimensions(float(rv), rv.dim._dims)
     return rv
コード例 #17
0
 def wrapper_function(*args):
     if not len(args) == len(self._function._arg_units):
         raise ValueError(
             ('Function %s got %d arguments, '
              'expected %d') % (self._function.name, len(args),
                                len(self._function._arg_units)))
     new_args = [
         Quantity.with_dimensions(arg, get_dimensions(arg_unit))
         for arg, arg_unit in zip(args, self._function._arg_units)
     ]
     result = orig_func(*new_args)
     fail_for_dimension_mismatch(result,
                                 self._function._return_unit)
     return np.asarray(result)
コード例 #18
0
    def test_hdf5_store_load_result(self):
        traj_name = make_trajectory_name(self)
        file_name = make_temp_dir(
            os.path.join('brian2', 'tests', 'hdf5',
                         'test_%s.hdf5' % traj_name))
        env = Environment(trajectory=traj_name,
                          filename=file_name,
                          log_config=get_log_config(),
                          dynamic_imports=[Brian2Result],
                          add_time=False,
                          storage_service=HDF5StorageService)
        traj = env.v_trajectory
        traj.v_standard_result = Brian2Result
        traj.f_add_result('brian2.single.millivolts_single_a',
                          10 * mvolt,
                          comment='single value a')
        traj.f_add_result('brian2.single.millivolts_single_c',
                          11 * mvolt,
                          comment='single value b')

        traj.f_add_result('brian2.array.millivolts_array_a', [11, 12] * mvolt,
                          comment='array')
        traj.f_add_result('mV1', 42.0 * mV)
        # results can hold much more than a single data item:
        traj.f_add_result('ampere1',
                          1 * mA,
                          44,
                          test=300 * mV,
                          test2=[1, 2, 3],
                          test3=np.array([1, 2, 3]) * mA,
                          comment='Result keeping track of many things')
        traj.f_add_result('integer', 16)
        traj.f_add_result('kHz05', 0.5 * kHz)
        traj.f_add_result('nested_array',
                          np.array([[6., 7., 8.], [9., 10., 11.]]) * ms)
        traj.f_add_result('b2a', np.array([1., 2.]) * mV)

        traj.f_add_result('nounit',
                          Quantity(np.array([[6., 7., 8.], [9., 10., 11.]])))

        traj.f_store()

        traj2 = load_trajectory(filename=file_name,
                                name=traj_name,
                                dynamic_imports=[Brian2Result],
                                load_data=2)

        self.compare_trajectories(traj, traj2)
コード例 #19
0
            def wrapper_function(*args):
                arg_units = list(self._function._arg_units)

                if self._function.auto_vectorise:
                    arg_units += [DIMENSIONLESS]
                if not len(args) == len(arg_units):
                    raise ValueError(('Function %s got %d arguments, '
                                      'expected %d') % (self._function.pyfunc.__name__, len(args),
                                                        len(arg_units)))
                new_args = []
                for arg, arg_unit in zip(args, arg_units):
                    if arg_unit == bool or arg_unit is None or isinstance(arg_unit, str):
                        new_args.append(arg)
                    else:
                        new_args.append(Quantity.with_dimensions(arg,
                                                                 get_dimensions(arg_unit)))
                result = orig_func(*new_args)
                if isinstance(self._function._return_unit, Callable):
                    return_unit = self._function._return_unit(*[get_dimensions(a)
                                                                for a in args])
                else:
                    return_unit = self._function._return_unit
                if return_unit == bool:
                    if not (isinstance(result, bool) or
                            np.asarray(result).dtype == bool):
                        raise TypeError('The function %s returned '
                                        '%s, but it was expected '
                                        'to return a boolean '
                                        'value ' % (orig_func.__name__,
                                                    result))
                elif (isinstance(return_unit, int) and return_unit == 1) or return_unit.dim is DIMENSIONLESS:
                    fail_for_dimension_mismatch(result,
                                                return_unit,
                                                'The function %s returned '
                                                '{value}, but it was expected '
                                                'to return a dimensionless '
                                                'quantity' % orig_func.__name__,
                                                value=result)
                else:
                    fail_for_dimension_mismatch(result,
                                                return_unit,
                                                ('The function %s returned '
                                                 '{value}, but it was expected '
                                                 'to return a quantity with '
                                                 'units %r') % (orig_func.__name__,
                                                                return_unit),
                                                value=result)
                return np.asarray(result)
コード例 #20
0
ファイル: functions.py プロジェクト: brian-team/brian2
            def wrapper_function(*args):
                arg_units = list(self._function._arg_units)

                if self._function.auto_vectorise:
                    arg_units += [DIMENSIONLESS]
                if not len(args) == len(arg_units):
                    func_name = self._function.pyfunc.__name__
                    raise ValueError(
                        f"Function {func_name} got {len(args)} arguments, "
                        f"expected {len(arg_units)}.")
                new_args = []
                for arg, arg_unit in zip(args, arg_units):
                    if arg_unit == bool or arg_unit is None or isinstance(
                            arg_unit, str):
                        new_args.append(arg)
                    else:
                        new_args.append(
                            Quantity.with_dimensions(arg,
                                                     get_dimensions(arg_unit)))
                result = orig_func(*new_args)
                if isinstance(self._function._return_unit, Callable):
                    return_unit = self._function._return_unit(
                        *[get_dimensions(a) for a in args])
                else:
                    return_unit = self._function._return_unit
                if return_unit == bool:
                    if not (isinstance(result, bool)
                            or np.asarray(result).dtype == bool):
                        raise TypeError(
                            f"The function {orig_func.__name__} returned "
                            f"'{result}', but it was expected to return a "
                            f"boolean value ")
                elif (isinstance(return_unit, int) and return_unit
                      == 1) or return_unit.dim is DIMENSIONLESS:
                    fail_for_dimension_mismatch(
                        result, return_unit,
                        f"The function '{orig_func.__name__}' "
                        f"returned {result}, but it was "
                        f"expected to return a dimensionless "
                        f"quantity.")
                else:
                    fail_for_dimension_mismatch(
                        result, return_unit,
                        f"The function '{orig_func.__name__}' "
                        f"returned {result}, but it was "
                        f"expected to return a quantity with "
                        f"units {return_unit!r}.")
                return np.asarray(result)
コード例 #21
0
ファイル: statemonitor.py プロジェクト: ttxtea/brian2
 def __getattr__(self, item):
     # We do this because __setattr__ and __getattr__ are not active until
     # _group_attribute_access_active attribute is set, and if it is set,
     # then __getattr__ will not be called. Therefore, if getattr is called
     # with this name, it is because it hasn't been set yet and so this
     # method should raise an AttributeError to agree that it hasn't been
     # called yet.
     if item == '_group_attribute_access_active':
         raise AttributeError
     if not hasattr(self, '_group_attribute_access_active'):
         raise AttributeError
     if item in self.record_variables:
         unit = self.variables[item].unit
         return Quantity(self.variables[item].get_value().T,
                         dim=unit.dim, copy=True)
     elif item.endswith('_') and item[:-1] in self.record_variables:
         return self.variables[item[:-1]].get_value().T
     else:
         return Group.__getattr__(self, item)
コード例 #22
0
def addBrianQuantity2Section(sec: nixio.pycore.Section, name: str,
                             qu: Quantity) -> nixio.pycore.Property:
    propStr = qu.in_best_unit()

    if qu.shape == ():

        propFloatStr, propUnit = propStr.split(" ")
        propFloat = float(propFloatStr)

        pr = sec.create_property(name, [nixio.Value(propFloat)])

    elif len(qu.shape) == 1:

        propFloatStr, propUnit = propStr.split("] ")
        values = list(map(float, propFloatStr[2:].split()))
        pr = sec.create_property(name, [nixio.Value(val) for val in values])

    else:
        raise (ValueError("Only scalar or 1D Brian Quantities as supported"))

    pr.unit = propUnit

    return pr
コード例 #23
0
    def group_set_with_index_array(self, group, variable_name, variable, item,
                                   value, check_units):
        if isinstance(item, slice) and item == slice(None):
            item = 'True'
        value = Quantity(value)

        if value.size == 1 and item == 'True':  # set the whole array to a scalar value
            if have_same_dimensions(value, 1):
                # Avoid a representation as "Quantity(...)" or "array(...)"
                value = float(value)
            group.set_with_expression_conditional(variable_name, variable,
                                                  cond=item,
                                                  code=repr(value),
                                                  check_units=check_units)
        # Simple case where we don't have to do any indexing
        elif item == 'True' and group.variables.indices[variable_name] == '_idx':
            self.fill_with_array(variable, value)
        else:
            # We have to calculate indices. This will not work for synaptic
            # variables
            try:
                indices = group.calc_indices(item)
            except NotImplementedError:
                raise NotImplementedError(('Cannot set variable "%s" this way in '
                                           'standalone, try using string '
                                           'expressions.') % variable_name)
            # Using the std::vector instead of a pointer to the underlying
            # data for dynamic arrays is fast enough here and it saves us some
            # additional work to set up the pointer
            arrayname = self.get_array_name(variable, access_data=False)
            staticarrayname_index = self.static_array('_index_'+arrayname,
                                                      indices)
            staticarrayname_value = self.static_array('_value_'+arrayname,
                                                      value)
            self.main_queue.append(('set_array_by_array', (arrayname,
                                                           staticarrayname_index,
                                                           staticarrayname_value)))
コード例 #24
0
    def _check_args(self, indices, times, period, N, sorted, dt):
        times = Quantity(times)
        if len(indices) != len(times):
            raise ValueError(
                ('Length of the indices and times array must '
                 'match, but %d != %d') % (len(indices), len(times)))
        if period < 0 * second:
            raise ValueError('The period cannot be negative.')
        elif len(times) and period != 0 * second:
            period_bins = np.round(period / dt)
            # Note: we have to use the timestep function here, to use the same
            # binning as in the actual simulation
            max_bin = timestep(np.max(times), dt)
            if max_bin >= period_bins:
                raise ValueError('The period has to be greater than the '
                                 'maximum of the spike times')
        if len(times) and np.min(times) < 0 * second:
            raise ValueError('Spike times cannot be negative')
        if len(indices) and (np.min(indices) < 0 or np.max(indices) >= N):
            raise ValueError('Indices have to lie in the interval [0, %d[' % N)

        times = np.asarray(times)
        indices = np.asarray(indices)
        if not sorted:
            # sort times and indices first by time, then by indices
            I = np.lexsort((indices, times))
            indices = indices[I]
            times = times[I]

        # We store the indices and times also directly in the Python object,
        # this way we can use them for checks in `before_run` even in standalone
        # TODO: Remove this when the checks in `before_run` have been moved to the template
        self._neuron_index = indices
        self._spike_time = times
        self._spikes_changed = True

        return indices, times
コード例 #25
0
ファイル: test_units.py プロジェクト: treestreamymw/brian2
def test_construction():
    ''' Test the construction of quantity objects '''
    q = 500 * ms
    assert_quantity(q, 0.5, second)
    q = np.float64(500) * ms
    assert_quantity(q, 0.5, second)
    q = np.array(500) * ms
    assert_quantity(q, 0.5, second)
    q = np.array([500, 1000]) * ms
    assert_quantity(q, np.array([0.5, 1]), second)
    q = Quantity(500)
    assert_quantity(q, 500, 1)
    q = Quantity(500, dim=second.dim)
    assert_quantity(q, 500, second)
    q = Quantity([0.5, 1], dim=second.dim)
    assert_quantity(q, np.array([0.5, 1]), second)
    q = Quantity(np.array([0.5, 1]), dim=second.dim)
    assert_quantity(q, np.array([0.5, 1]), second)
    q = Quantity([500 * ms, 1 * second])
    assert_quantity(q, np.array([0.5, 1]), second)
    q = Quantity.with_dimensions(np.array([0.5, 1]), second=1)
    assert_quantity(q, np.array([0.5, 1]), second)
    q = [0.5, 1] * second
    assert_quantity(q, np.array([0.5, 1]), second)

    # dimensionless quantities
    q = Quantity([1, 2, 3])
    assert_quantity(q, np.array([1, 2, 3]), Unit(1))
    q = Quantity(np.array([1, 2, 3]))
    assert_quantity(q, np.array([1, 2, 3]), Unit(1))
    q = Quantity([])
    assert_quantity(q, np.array([]), Unit(1))

    # copying/referencing a quantity
    q1 = Quantity.with_dimensions(np.array([0.5, 1]), second=1)
    q2 = Quantity(q1)  # no copy
    assert_quantity(q2, np.asarray(q1), q1)
    q2[0] = 3 * second
    assert_equal(q1[0], 3 * second)

    q1 = Quantity.with_dimensions(np.array([0.5, 1]), second=1)
    q2 = Quantity(q1, copy=True)  # copy
    assert_quantity(q2, np.asarray(q1), q1)
    q2[0] = 3 * second
    assert_equal(q1[0], 0.5 * second)

    # Illegal constructor calls
    with pytest.raises(TypeError):
        Quantity([500 * ms, 1])
    with pytest.raises(TypeError):
        Quantity(['some', 'nonsense'])
    with pytest.raises(DimensionMismatchError):
        Quantity([500 * ms, 1 * volt])
コード例 #26
0
ファイル: parameter.py プロジェクト: SmokinCaterpillar/pypet
def get_unit_fast(x):
    """ Return a `Quantity` with value 1 and the same dimensions. """
    return Quantity.with_dimensions(1, get_dimensions(x))
コード例 #27
0
def get_unit_fast(x):
    """ Return a `Quantity` with value 1 and the same dimensions. """
    return Quantity.with_dimensions(1, get_dimensions(x))
コード例 #28
0
ファイル: collector.py プロジェクト: mqcapelle/brian2tools
def collect_SpikeGenerator(spike_gen, run_namespace):
    """
    Extract information from
    'brian2.input.spikegeneratorgroup.SpikeGeneratorGroup'and
    represent them in a dictionary format

    Parameters
    ----------
    spike_gen : brian2.input.spikegeneratorgroup.SpikeGeneratorGroup
            SpikeGenerator object

    run_namespace : dict
            Namespace dictionary

    Returns
    -------
    spikegen_dict : dict
                Dictionary with extracted information
    """

    spikegen_dict = {}
    identifiers = set()
    # get name
    spikegen_dict['name'] = spike_gen.name

    # get size
    spikegen_dict['N'] = spike_gen.N

    # get indices of spiking neurons
    spikegen_dict['indices'] = spike_gen._neuron_index[:]

    # get spike times for defined neurons
    spikegen_dict['times'] = Quantity(spike_gen._spike_time[:], second)

    # get spike period (default period is 0*second will be stored if not
    # mentioned by the user)
    spikegen_dict['period'] = spike_gen.period[:]

    # `run_regularly` / CodeRunner objects of spike_gen
    # although not a very popular option
    for obj in spike_gen.contained_objects:
        if type(obj) == CodeRunner:
            if 'run_regularly' not in spikegen_dict:
                spikegen_dict['run_regularly'] = []
            spikegen_dict['run_regularly'].append({
                'name': obj.name,
                'code': obj.abstract_code,
                'dt': obj.clock.dt,
                'when': obj.when,
                'order': obj.order
            })
            identifiers = identifiers | get_identifiers(obj.abstract_code)
    # resolve group-specific identifiers
    identifiers = spike_gen.resolve_all(identifiers, run_namespace)
    # with the identifiers connected to group, prune away unwanted
    identifiers = _prepare_identifiers(identifiers)
    # check the dictionary is not empty
    if identifiers:
        spikegen_dict['identifiers'] = identifiers

    return spikegen_dict
コード例 #29
0
    def smooth_rate(self, window='gaussian', width=None):
        """
        smooth_rate(self, window='gaussian', width=None)

        Return a smooth version of the population rate.

        Parameters
        ----------
        window : str, ndarray
            The window to use for smoothing. Can be a string to chose a
            predefined window(``'flat'`` for a rectangular, and ``'gaussian'``
            for a Gaussian-shaped window). In this case the width of the window
            is determined by the ``width`` argument. Note that for the Gaussian
            window, the ``width`` parameter specifies the standard deviation of
            the Gaussian, the width of the actual window is ``4*width + dt``
            (rounded to the nearest dt). For the flat window, the width is
            rounded to the nearest odd multiple of dt to avoid shifting the rate
            in time.
            Alternatively, an arbitrary window can be given as a numpy array
            (with an odd number of elements). In this case, the width in units
            of time depends on the ``dt`` of the simulation, and no ``width``
            argument can be specified. The given window will be automatically
            normalized to a sum of 1.
        width : `Quantity`, optional
            The width of the ``window`` in seconds (for a predefined window).

        Returns
        -------
        rate : `Quantity`
            The population rate in Hz, smoothed with the given window. Note that
            the rates are smoothed and not re-binned, i.e. the length of the
            returned array is the same as the length of the ``rate`` attribute
            and can be plotted against the `PopulationRateMonitor` 's ``t``
            attribute.
        """
        if width is None and isinstance(window, str):
            raise TypeError("Need a width when using a predefined window.")
        if width is not None and not isinstance(window, str):
            raise TypeError("Can only specify a width for a predefined window")

        if isinstance(window, str):
            if window == 'gaussian':
                width_dt = int(np.round(2 * width / self.clock.dt))
                # Rounding only for the size of the window, not for the standard
                # deviation of the Gaussian
                window = np.exp(-np.arange(-width_dt, width_dt + 1)**2 * 1. /
                                (2 * (width / self.clock.dt)**2))
            elif window == 'flat':
                width_dt = int(width / 2 / self.clock.dt) * 2 + 1
                used_width = width_dt * self.clock.dt
                if abs(used_width - width) > 1e-6 * self.clock.dt:
                    logger.info(f'width adjusted from {width} to {used_width}',
                                'adjusted_width',
                                once=True)
                window = np.ones(width_dt)
            else:
                raise NotImplementedError(
                    f'Unknown pre-defined window "{window}"')
        else:
            try:
                window = np.asarray(window)
            except TypeError:
                raise TypeError(f"Cannot use a window of type {type(window)}")
            if window.ndim != 1:
                raise TypeError("The provided window has to be "
                                "one-dimensional.")
            if len(window) % 2 != 1:
                raise TypeError("The window has to have an odd number of "
                                "values.")
        return Quantity(np.convolve(self.rate_,
                                    window * 1. / sum(window),
                                    mode='same'),
                        dim=hertz.dim)
コード例 #30
0
ファイル: spikegeneratorgroup.py プロジェクト: flinz/brian2
    def __init__(self,
                 N,
                 indices,
                 times,
                 dt=None,
                 clock=None,
                 period=1e100 * second,
                 when='thresholds',
                 order=0,
                 sorted=False,
                 name='spikegeneratorgroup*',
                 codeobj_class=None):

        Group.__init__(self,
                       dt=dt,
                       clock=clock,
                       when=when,
                       order=order,
                       name=name)

        # Let other objects know that we emit spikes events
        self.events = {'spike': None}

        self.codeobj_class = codeobj_class

        times = Quantity(times)
        if N < 1 or int(N) != N:
            raise TypeError('N has to be an integer >=1.')
        N = int(
            N)  # Make sure that it is an integer, values such as 10.0 would
        # otherwise make weave compilation fail
        if len(indices) != len(times):
            raise ValueError(
                ('Length of the indices and times array must '
                 'match, but %d != %d') % (len(indices), len(times)))
        if period < 0 * second:
            raise ValueError('The period cannot be negative.')
        elif len(times) and period <= np.max(times):
            raise ValueError(
                'The period has to be greater than the maximum of '
                'the spike times')
        if len(times) and np.min(times) < 0 * second:
            raise ValueError('Spike times cannot be negative')
        if len(indices) and (np.min(indices) < 0 or np.max(indices) >= N):
            raise ValueError('Indices have to lie in the interval [0, %d[' % N)

        self.start = 0
        self.stop = N

        if not sorted:
            # sort times and indices first by time, then by indices
            rec = np.rec.fromarrays([times, indices], names=['t', 'i'])
            rec.sort()
            times = np.ascontiguousarray(rec.t)
            indices = np.ascontiguousarray(rec.i)

        self.variables = Variables(self)

        # We store the indices and times also directly in the Python object,
        # this way we can use them for checks in `before_run` even in standalone
        # TODO: Remove this when the checks in `before_run` have been moved to the template
        self._spike_time = times
        self._neuron_index = indices

        # standard variables
        self.variables.add_constant('N', unit=Unit(1), value=N)
        self.variables.add_array('period',
                                 unit=second,
                                 size=1,
                                 constant=True,
                                 read_only=True,
                                 scalar=True)
        self.variables.add_arange('i', N)
        self.variables.add_dynamic_array('spike_number',
                                         values=np.arange(len(indices)),
                                         size=len(indices),
                                         unit=Unit(1),
                                         dtype=np.int32,
                                         read_only=True,
                                         constant=True,
                                         index='spike_number',
                                         unique=True)
        self.variables.add_dynamic_array('neuron_index',
                                         values=indices,
                                         size=len(indices),
                                         unit=Unit(1),
                                         dtype=np.int32,
                                         index='spike_number',
                                         read_only=True,
                                         constant=True)
        self.variables.add_dynamic_array('spike_time',
                                         values=times,
                                         size=len(times),
                                         unit=second,
                                         index='spike_number',
                                         read_only=True,
                                         constant=True)
        self.variables.add_array('_spikespace',
                                 size=N + 1,
                                 unit=Unit(1),
                                 dtype=np.int32)
        self.variables.add_array('_lastindex',
                                 size=1,
                                 values=0,
                                 unit=Unit(1),
                                 dtype=np.int32,
                                 read_only=True,
                                 scalar=True)
        self.variables.create_clock_variables(self._clock)

        #: Remember the dt we used the last time when we checked the spike bins
        #: to not repeat the work for multiple runs with the same dt
        self._previous_dt = None

        #: "Dirty flag" that will be set when spikes are changed after the
        #: `before_run` check
        self._spikes_changed = True

        CodeRunner.__init__(self,
                            self,
                            code='',
                            template='spikegenerator',
                            clock=self._clock,
                            when=when,
                            order=order,
                            name=None)

        # Activate name attribute access
        self._enable_group_attributes()

        self.variables['period'].set_value(period)
コード例 #31
0
ファイル: network.py プロジェクト: squiba/brian2
class Network(Nameable):
    '''
    Network(*objs, name='network*')
    
    The main simulation controller in Brian

    `Network` handles the running of a simulation. It contains a set of Brian
    objects that are added with `~Network.add`. The `~Network.run` method
    actually runs the simulation. The main run loop, determining which
    objects get called in what order is described in detail in the notes below.
    The objects in the `Network` are accesible via their names, e.g.
    `net['neurongroup']` would return the `NeuronGroup` with this name.
    
    Parameters
    ----------
    objs : (`BrianObject`, container), optional
        A list of objects to be added to the `Network` immediately, see
        `~Network.add`.
    name : str, optional
        An explicit name, if not specified gives an automatically generated name

    Notes
    -----
    
    The main run loop performs the following steps:
    
    1. Prepare the objects if necessary, see `~Network.prepare`.
    2. Determine the end time of the simulation as `~Network.t`+``duration``.
    3. Determine which set of clocks to update. This will be the clock with the
       smallest value of `~Clock.t`. If there are several with the same value,
       then all objects with these clocks will be updated simultaneously.
       Set `~Network.t` to the clock time.
    4. If the `~Clock.t` value of these clocks is past the end time of the
       simulation, stop running. If the `Network.stop` method or the
       `stop` function have been called, stop running. Set `~Network.t` to the
       end time of the simulation.
    5. For each object whose `~BrianObject.clock` is set to one of the clocks from the
       previous steps, call the `~BrianObject.update` method. This method will
       not be called if the `~BrianObject.active` flag is set to ``False``.
       The order in which the objects are called is described below.
    6. Increase `Clock.t` by `Clock.dt` for each of the clocks and return to
       step 2. 
    
    The order in which the objects are updated in step 4 is determined by
    the `Network.schedule` and the objects `~BrianObject.when` and
    `~BrianObject.order` attributes. The `~Network.schedule` is a list of
    string names. Each `~BrianObject.when` attribute should be one of these
    strings, and the objects will be updated in the order determined by the
    schedule. The default schedule is
    ``['start', 'groups', 'thresholds', 'synapses', 'resets', 'end']``. In
    addition to the names provided in the schedule, automatic names starting
    with ``before_`` and ``after_`` can be used. That means that all objects
    with ``when=='before_start'`` will be updated first, then
    those with ``when=='start'``, ``when=='after_start'``,
    ``when=='before_groups'``, ``when=='groups'`` and so forth. If several
    objects have the same `~BrianObject.when` attribute, then the order is
    determined by the `~BrianObject.order` attribute (lower first).
    
    See Also
    --------
    
    MagicNetwork, run, stop
    '''
    def __init__(self, *objs, **kwds):
        #: The list of objects in the Network, should not normally be modified
        #: directly.
        #: Note that in a `MagicNetwork`, this attribute only contains the
        #: objects during a run: it is filled in `before_run` and emptied in
        #: `after_run`
        self.objects = []

        name = kwds.pop('name', 'network*')

        if kwds:
            raise TypeError("Only keyword argument to Network is 'name'.")

        Nameable.__init__(self, name=name)

        #: Current time as a float
        self.t_ = 0.0

        for obj in objs:
            self.add(obj)

        #: Stored state of objects (store/restore)
        self._stored_state = {}

        # Stored profiling information (if activated via the keyword option)
        self._profiling_info = None

        self._schedule = None

    t = property(
        fget=lambda self: Quantity(self.t_, dim=second.dim, copy=False),
        doc='''
                     Current simulation time in seconds (`Quantity`)
                     ''')

    @device_override('network_get_profiling_info')
    def get_profiling_info(self):
        '''
        The only reason this is not directly implemented in `profiling_info`
        is to allow devices (e.g. `CPPStandaloneDevice`) to overwrite this.
        '''
        if self._profiling_info is None:
            raise ValueError('(No profiling info collected (did you run with '
                             'profile=True?)')
        return sorted(self._profiling_info,
                      key=lambda item: item[1],
                      reverse=True)

    @property
    def profiling_info(self):
        '''
        The time spent in executing the various `CodeObject`\ s.

        A list of ``(name, time)`` tuples, containing the name of the
        `CodeObject` and the total execution time for simulations of this object
        (as a `Quantity` with unit `second`). The list is sorted descending
        with execution time.

        Profiling has to be activated using the ``profile`` keyword in `run` or
        `Network.run`.
        '''
        return self.get_profiling_info()

    _globally_stopped = False

    def __getitem__(self, item):
        if not isinstance(item, basestring):
            raise TypeError(('Need a name to access objects in a Network, '
                             'got {type} instead').format(type=type(item)))
        for obj in self.objects:
            if obj.name == item:
                return obj

        raise KeyError('No object with name "%s" found' % item)

    def __delitem__(self, key):
        if not isinstance(key, basestring):
            raise TypeError(('Need a name to access objects in a Network, '
                             'got {type} instead').format(type=type(key)))

        for obj in self.objects:
            if obj.name == key:
                self.remove(obj)
                return

        raise KeyError('No object with name "%s" found' % key)

    def __contains__(self, item):
        for obj in self.objects:
            if obj.name == item:
                return True
        return False

    def __len__(self):
        return len(self.objects)

    def __iter__(self):
        return iter(self.objects)

    def add(self, *objs):
        """
        Add objects to the `Network`
        
        Parameters
        ----------
        
        objs : (`BrianObject`, container)
            The `BrianObject` or container of Brian objects to be added. Specify
            multiple objects, or lists (or other containers) of objects.
            Containers will be added recursively. If the container is a `dict`
            then it will add the values from the dictionary but not the keys.
            If you want to add the keys, do ``add(objs.keys())``.
        """
        for obj in objs:
            if isinstance(obj, BrianObject):
                if obj._network is not None:
                    raise RuntimeError(
                        '%s has already been simulated, cannot '
                        'add it to the network. If you were '
                        'trying to remove and add an object to '
                        'temporarily stop it from being run, '
                        'set its active flag to False instead.' % obj.name)
                if obj not in self.objects:  # Don't include objects twice
                    self.objects.append(obj)
                self.add(obj.contained_objects)
            else:
                # allow adding values from dictionaries
                if isinstance(obj, Mapping):
                    self.add(*obj.values())
                else:
                    try:
                        for o in obj:
                            # The following "if" looks silly but avoids an infinite
                            # recursion if a string is provided as an argument
                            # (which might occur during testing)
                            if o is obj:
                                raise TypeError()
                            self.add(o)
                    except TypeError:
                        raise TypeError(
                            "Can only add objects of type BrianObject, "
                            "or containers of such objects to Network")

    def remove(self, *objs):
        '''
        Remove an object or sequence of objects from a `Network`.
        
        Parameters
        ----------
        
        objs : (`BrianObject`, container)
            The `BrianObject` or container of Brian objects to be removed. Specify
            multiple objects, or lists (or other containers) of objects.
            Containers will be removed recursively.
        '''
        for obj in objs:
            if isinstance(obj, BrianObject):
                self.objects.remove(obj)
                self.remove(obj.contained_objects)
            else:
                try:
                    for o in obj:
                        self.remove(o)
                except TypeError:
                    raise TypeError("Can only remove objects of type "
                                    "BrianObject, or containers of such "
                                    "objects from Network")

    def _full_state(self):
        state = {}
        for obj in self.objects:
            if hasattr(obj, '_full_state'):
                state[obj.name] = obj._full_state()
        clocks = set([obj.clock for obj in self.objects])
        for clock in clocks:
            state[clock.name] = clock._full_state()
        # Store the time as "0_t" -- this name is guaranteed not to clash with
        # the name of an object as names are not allowed to start with a digit
        state['0_t'] = self.t_
        return state

    @device_override('network_store')
    def store(self, name='default', filename=None):
        '''
        store(name='default', filename=None)

        Store the state of the network and all included objects.

        Parameters
        ----------
        name : str, optional
            A name for the snapshot, if not specified uses ``'default'``.
        filename : str, optional
            A filename where the state should be stored. If not specified, the
            state will be stored in memory.

        Notes
        -----
        The state stored to disk can be restored with the `Network.restore`
        function. Note that it will only restore the *internal state* of all
        the objects (including undelivered spikes) -- the objects have to
        exist already and they need to have the same name as when they were
        stored. Equations, thresholds, etc. are *not* stored -- this is
        therefore not a general mechanism for object serialization. Also, the
        format of the file is not guaranteed to work across platforms or
        versions. If you are interested in storing the state of a network for
        documentation or analysis purposes use `Network.get_states` instead.
        '''
        clocks = [obj.clock for obj in self.objects]
        # Make sure that all clocks are up to date
        for clock in clocks:
            clock._set_t_update_dt(target_t=self.t)

        state = self._full_state()
        if filename is None:
            self._stored_state[name] = state
        else:
            # A single file can contain several states, so we'll read in the
            # existing file first if it exists
            if os.path.exists(filename):
                with open(filename, 'rb') as f:
                    store_state = pickle.load(f)
            else:
                store_state = {}
            store_state[name] = state

            with open(filename, 'wb') as f:
                pickle.dump(store_state, f, protocol=pickle.HIGHEST_PROTOCOL)

    @device_override('network_restore')
    def restore(self, name='default', filename=None):
        '''
        restore(name='default', filename=None)

        Retore the state of the network and all included objects.

        Parameters
        ----------
        name : str, optional
            The name of the snapshot to restore, if not specified uses
            ``'default'``.
        filename : str, optional
            The name of the file from where the state should be restored. If
            not specified, it is expected that the state exist in memory
            (i.e. `Network.store` was previously called without the ``filename``
            argument).
        '''
        if filename is None:
            state = self._stored_state[name]
        else:
            with open(filename, 'rb') as f:
                state = pickle.load(f)[name]
        self.t_ = state['0_t']
        clocks = set([obj.clock for obj in self.objects])
        restored_objects = set()
        for obj in self.objects:
            if obj.name in state:
                obj._restore_from_full_state(state[obj.name])
                restored_objects.add(obj.name)
            elif hasattr(obj, '_restore_from_full_state'):
                raise KeyError(
                    ('Stored state does not have a stored state for '
                     '"%s". Note that the names of all objects have '
                     'to be identical to the names when they were '
                     'stored.') % obj.name)
        for clock in clocks:
            clock._restore_from_full_state(state[clock.name])
        clock_names = {c.name for c in clocks}

        unnused = set(state.keys()) - restored_objects - clock_names - {'0_t'}
        if len(unnused):
            raise KeyError('The stored state contains the state of the '
                           'following objects which were not present in the '
                           'network: %s. Note that the names of all objects '
                           'have to be identical to the names when they were '
                           'stored.' % (', '.join(unnused)))

    def get_states(self,
                   units=True,
                   format='dict',
                   subexpressions=False,
                   read_only_variables=True,
                   level=0):
        '''
        Return a copy of the current state variable values of objects in the
        network.. The returned arrays are copies of the actual arrays that
        store the state variable values, therefore changing the values in the
        returned dictionary will not affect the state variables.

        Parameters
        ----------
        vars : list of str, optional
            The names of the variables to extract. If not specified, extract
            all state variables (except for internal variables, i.e. names that
            start with ``'_'``). If the ``subexpressions`` argument is ``True``,
            the current values of all subexpressions are returned as well.
        units : bool, optional
            Whether to include the physical units in the return value. Defaults
            to ``True``.
        format : str, optional
            The output format. Defaults to ``'dict'``.
        subexpressions: bool, optional
            Whether to return subexpressions when no list of variable names
            is given. Defaults to ``False``. This argument is ignored if an
            explicit list of variable names is given in ``vars``.
        read_only_variables : bool, optional
            Whether to return read-only variables (e.g. the number of neurons,
            the time, etc.). Setting it to ``False`` will assure that the
            returned state can later be used with `set_states`. Defaults to
            ``True``.
        level : int, optional
            How much higher to go up the stack to resolve external variables.
            Only relevant if extracting subexpressions that refer to external
            variables.

        Returns
        -------
        values : dict
            A dictionary mapping object names to the state variables of that
            object, in the specified ``format``.

        See Also
        --------
        VariableOwner.get_states
        '''
        states = dict()
        for obj in self.objects:
            if hasattr(obj, 'get_states'):
                states[obj.name] = obj.get_states(
                    vars=None,
                    units=units,
                    format=format,
                    subexpressions=subexpressions,
                    read_only_variables=read_only_variables,
                    level=level + 1)
        return states

    def set_states(self, values, units=True, format='dict', level=0):
        '''
        Set the state variables of objects in the network.

        Parameters
        ----------
        values : dict
            A dictionary mapping object names to objects of ``format``, setting
            the states of this object.
        units : bool, optional
            Whether the ``values`` include physical units. Defaults to ``True``.
        format : str, optional
            The format of ``values``. Defaults to ``'dict'``
        level : int, optional
            How much higher to go up the stack to _resolve external variables.
            Only relevant when using string expressions to set values.

        See Also
        --------
        Group.set_states
        '''
        # For the moment, 'dict' is the only supported format -- later this will
        # be made into an extensible system, see github issue #306
        for obj_name, obj_values in values.iteritems():
            if obj_name not in self:
                raise KeyError(("Network does not include a network with "
                                "name '%s'.") % obj_name)
            self[obj_name].set_states(obj_values,
                                      units=units,
                                      format=format,
                                      level=level + 1)

    def _get_schedule(self):
        if self._schedule is None:
            return list(prefs.core.network.default_schedule)
        else:
            return list(self._schedule)

    def _set_schedule(self, schedule):
        if schedule is None:
            self._schedule = None
            logger.debug('Resetting network {self.name} schedule to '
                         'default schedule')
        else:
            if (not isinstance(schedule, Sequence) or
                    not all(isinstance(slot, basestring)
                            for slot in schedule)):
                raise TypeError('Schedule has to be None or a sequence of '
                                'scheduling slots')
            if any(
                    slot.startswith('before_') or slot.startswith('after_')
                    for slot in schedule):
                raise ValueError('Slot names are not allowed to start with '
                                 '"before_" or "after_" -- such slot names '
                                 'are created automatically based on the '
                                 'existing slot names.')
            self._schedule = list(schedule)
            logger.debug(
                "Setting network {self.name} schedule to "
                "{self._schedule}".format(self=self), "_set_schedule")

    schedule = property(fget=_get_schedule,
                        fset=_set_schedule,
                        doc='''
        List of ``when`` slots in the order they will be updated, can be modified.
        
        See notes on scheduling in `Network`. Note that additional ``when``
        slots can be added, but the schedule should contain at least all of the
        names in the default schedule:
        ``['start', 'groups', 'thresholds', 'synapses', 'resets', 'end']``.

        The schedule can also be set to ``None``, resetting it to the default
        schedule set by the `core.network.default_schedule` preference.
        ''')

    def _sort_objects(self):
        '''
        Sorts the objects in the order defined by the schedule.
        
        Objects are sorted first by their ``when`` attribute, and secondly
        by the ``order`` attribute. The order of the ``when`` attribute is
        defined by the ``schedule``. In addition to the slot names defined in
        the schedule, automatic slot names starting with ``before_`` and
        ``after_`` can be used (e.g. the slots ``['groups', 'thresholds']``
        allow to use ``['before_groups', 'groups', 'after_groups',
        'before_thresholds', 'thresholds', 'after_thresholds']`).

        Final ties are resolved using the objects' names, leading to an
        arbitrary but deterministic sorting.
        '''
        # Provided slot names are assigned positions 1, 4, 7, ...
        # before_... names are assigned positions 0, 3, 6, ...
        # after_... names are assigned positions 2, 5, 8, ...
        when_to_int = dict(
            (when, 1 + i * 3) for i, when in enumerate(self.schedule))
        when_to_int.update(
            ('before_' + when, i * 3) for i, when in enumerate(self.schedule))
        when_to_int.update(('after_' + when, 2 + i * 3)
                           for i, when in enumerate(self.schedule))
        self.objects.sort(
            key=lambda obj: (when_to_int[obj.when], obj.order, obj.name))

    def check_dependencies(self):
        all_ids = [obj.id for obj in self.objects]
        for obj in self.objects:
            for dependency in obj._dependencies:
                if not dependency in all_ids:
                    raise ValueError(('"%s" has been included in the network '
                                      'but not the object on which it '
                                      'depends.') % obj.name)

    @device_override('network_before_run')
    def before_run(self, run_namespace):
        '''
        before_run(namespace)

        Prepares the `Network` for a run.
        
        Objects in the `Network` are sorted into the correct running order, and
        their `BrianObject.before_run` methods are called.

        Parameters
        ----------
        run_namespace : dict-like, optional
            A namespace in which objects which do not define their own
            namespace will be run.
        '''
        from brian2.devices.device import get_device, all_devices

        prefs.check_all_validated()

        # Check names in the network for uniqueness
        names = [obj.name for obj in self.objects]
        non_unique_names = [
            name for name, count in Counter(names).iteritems() if count > 1
        ]
        if len(non_unique_names):
            formatted_names = ', '.join("'%s'" % name
                                        for name in non_unique_names)
            raise ValueError(
                'All objects in a network need to have unique '
                'names, the following name(s) were used more than '
                'once: %s' % formatted_names)

        self._stopped = False
        Network._globally_stopped = False

        device = get_device()
        if device.network_schedule is not None:
            # The device defines a fixed network schedule
            if device.network_schedule != self.schedule:
                # TODO: The human-readable name of a device should be easier to get
                device_name = all_devices.keys()[all_devices.values().index(
                    device)]
                logger.warn(
                    ("The selected device '{device_name}' only "
                     "supports a fixed schedule, but this schedule is "
                     "not consistent with the network's schedule. The "
                     "simulation will use the device's schedule.\n"
                     "Device schedule: {device.network_schedule}\n"
                     "Network schedule: {net.schedule}\n"
                     "Set the network schedule explicitly or set the "
                     "core.network.default_schedule preference to "
                     "avoid this warning.").format(device_name=device_name,
                                                   device=device,
                                                   net=self),
                    name_suffix='schedule_conflict',
                    once=True)

        self._sort_objects()

        logger.debug(
            "Preparing network {self.name} with {numobj} "
            "objects: {objnames}".format(
                self=self,
                numobj=len(self.objects),
                objnames=', '.join(obj.name for obj in self.objects)),
            "before_run")

        self.check_dependencies()

        for obj in self.objects:
            if obj.active:
                try:
                    obj.before_run(run_namespace)
                except Exception as ex:
                    raise brian_object_exception(
                        "An error occurred when preparing an object.", obj, ex)

        # Check that no object has been run as part of another network before
        for obj in self.objects:
            if obj._network is None:
                obj._network = self.id
            elif obj._network != self.id:
                raise RuntimeError(('%s has already been run in the '
                                    'context of another network. Use '
                                    'add/remove to change the objects '
                                    'in a simulated network instead of '
                                    'creating a new one.') % obj.name)

        logger.debug(
            "Network {self.name} uses {num} "
            "clocks: {clocknames}".format(
                self=self,
                num=len(self._clocks),
                clocknames=', '.join('%s (dt=%s)' % (obj.name, obj.dt)
                                     for obj in self._clocks)), "before_run")

    @device_override('network_after_run')
    def after_run(self):
        '''
        after_run()
        '''
        for obj in self.objects:
            if obj.active:
                obj.after_run()

    def _nextclocks(self):
        clocks_times_dt = [(c, self._clock_variables[c][1][0],
                            self._clock_variables[c][2][0])
                           for c in self._clocks]
        minclock, min_time, minclock_dt = min(clocks_times_dt,
                                              key=lambda k: k[1])
        curclocks = set(clock for clock, time, dt in clocks_times_dt
                        if (time == min_time or abs(time - min_time) /
                            min(minclock_dt, dt) < Clock.epsilon_dt))
        return minclock, curclocks

    @device_override('network_run')
    @check_units(duration=second, report_period=second)
    def run(self,
            duration,
            report=None,
            report_period=10 * second,
            namespace=None,
            profile=True,
            level=0):
        '''
        run(duration, report=None, report_period=60*second, namespace=None, level=0)
        
        Runs the simulation for the given duration.
        
        Parameters
        ----------
        duration : `Quantity`
            The amount of simulation time to run for.
        report : {None, 'text', 'stdout', 'stderr', function}, optional
            How to report the progress of the simulation. If ``None``, do not
            report progress. If ``'text'`` or ``'stdout'`` is specified, print
            the progress to stdout. If ``'stderr'`` is specified, print the
            progress to stderr. Alternatively, you can specify a callback
            ``callable(elapsed, complete, duration)`` which will be passed
            the amount of time elapsed as a `Quantity`, the
            fraction complete from 0.0 to 1.0 and the total duration of the
            simulation (in biological time).
            The function will always be called at the beginning and the end
            (i.e. for fractions 0.0 and 1.0), regardless of the `report_period`.
        report_period : `Quantity`
            How frequently (in real time) to report progress.
        namespace : dict-like, optional
            A namespace that will be used in addition to the group-specific
            namespaces (if defined). If not specified, the locals
            and globals around the run function will be used.
        profile : bool, optional
            Whether to record profiling information (see
            `Network.profiling_info`). Defaults to ``True``.
        level : int, optional
            How deep to go up the stack frame to look for the locals/global
            (see `namespace` argument). Only used by run functions that call
            this run function, e.g. `MagicNetwork.run` to adjust for the
            additional nesting.

        Notes
        -----
        The simulation can be stopped by calling `Network.stop` or the
        global `stop` function.
        '''
        self._clocks = set([obj.clock for obj in self.objects])
        # We get direct references to the underlying variables for all clocks
        # to avoid expensive access during the run loop
        self._clock_variables = {
            c: (c.variables['timestep'].get_value(),
                c.variables['t'].get_value(), c.variables['dt'].get_value())
            for c in self._clocks
        }
        t_start = self.t
        t_end = self.t + duration
        for clock in self._clocks:
            clock.set_interval(self.t, t_end)

        # Get the local namespace
        if namespace is None:
            namespace = get_local_namespace(level=level + 3)

        self.before_run(namespace)

        if len(self.objects) == 0:
            return  # TODO: raise an error? warning?

        # Find the first clock to be updated (see note below)
        clock, curclocks = self._nextclocks()
        start_time = time.time()

        logger.debug(
            "Simulating network '%s' from time %s to %s." %
            (self.name, t_start, t_end), 'run')

        if report is not None:
            report_period = float(report_period)
            next_report_time = start_time + report_period
            if report == 'text' or report == 'stdout':
                report_callback = TextReport(sys.stdout)
            elif report == 'stderr':
                report_callback = TextReport(sys.stderr)
            elif isinstance(report, basestring):
                raise ValueError(('Do not know how to handle report argument '
                                  '"%s".' % report))
            elif callable(report):
                report_callback = report
            else:
                raise TypeError(('Do not know how to handle report argument, '
                                 'it has to be one of "text", "stdout", '
                                 '"stderr", or a callable function/object, '
                                 'but it is of type %s') % type(report))
            report_callback(0 * second, 0.0, t_start, duration)

        profiling_info = defaultdict(float)

        timestep, _, _ = self._clock_variables[clock]
        running = timestep[0] < clock._i_end
        while running and not self._stopped and not Network._globally_stopped:
            timestep, t, dt = self._clock_variables[clock]
            # update the network time to this clock's time
            self.t_ = t[0]
            if report is not None:
                current = time.time()
                if current > next_report_time:
                    report_callback((current - start_time) * second,
                                    (self.t_ - float(t_start)) / float(t_end),
                                    t_start, duration)
                    next_report_time = current + report_period
                # update the objects with this clock
            for obj in self.objects:
                if obj._clock in curclocks and obj.active:
                    if profile:
                        obj_time = time.time()
                        obj.run()
                        profiling_info[obj.name] += (time.time() - obj_time)
                    else:
                        obj.run()

            # tick the clock forward one time step
            for c in curclocks:
                timestep, t, dt = self._clock_variables[c]
                timestep[0] += 1
                t[0] = timestep[0] * dt[0]

            # find the next clocks to be updated. The < operator for Clock
            # determines that the first clock to be updated should be the one
            # with the smallest t value, unless there are several with the
            # same t value in which case we update all of them
            clock, curclocks = self._nextclocks()

            if device._maximum_run_time is not None and time.time(
            ) - start_time > float(device._maximum_run_time):
                self._stopped = True
            else:
                timestep, _, _ = self._clock_variables[clock]
                running = timestep < clock._i_end

        end_time = time.time()
        if self._stopped or Network._globally_stopped:
            self.t_ = clock.t_
        else:
            self.t_ = float(t_end)

        device._last_run_time = end_time - start_time
        if duration > 0:
            device._last_run_completed_fraction = (self.t - t_start) / duration
        else:
            device._last_run_completed_fraction = 1.0

        # check for nans
        for obj in self.objects:
            if isinstance(obj, Group):
                obj._check_for_invalid_states()

        if report is not None:
            report_callback((end_time - start_time) * second, 1.0, t_start,
                            duration)
        self.after_run()

        logger.debug(("Finished simulating network '%s' "
                      "(took %.2fs)") % (self.name, end_time - start_time),
                     'run')
        # Store profiling info (or erase old info to avoid confusion)
        if profile:
            self._profiling_info = [(name, t * second)
                                    for name, t in profiling_info.iteritems()]
            # Dump a profiling summary to the log
            logger.debug('\n' + str(profiling_summary(self)))
        else:
            self._profiling_info = None

    @device_override('network_stop')
    def stop(self):
        '''
        stop()

        Stops the network from running, this is reset the next time `Network.run` is called.
        '''
        self._stopped = True

    def __repr__(self):
        return '<%s at time t=%s, containing objects: %s>' % (
            self.__class__.__name__, str(self.t), ', '.join(
                (obj.__repr__() for obj in self.objects)))
コード例 #32
0
ファイル: hears.py プロジェクト: zeph1yr/brian2
def convert_unit_b1_to_b2(val):
    return Quantity.with_dimensions(float(val), arg.dim._dims)
コード例 #33
0
class Clock(Nameable):
    '''
    An object that holds the simulation time and the time step.
    
    Parameters
    ----------
    dt : float
        The time step of the simulation as a float
    name : str, optional
        An explicit name, if not specified gives an automatically generated name

    Notes
    -----
    Clocks are run in the same `Network.run` iteration if `~Clock.t` is the
    same. The condition for two
    clocks to be considered as having the same time is
    ``abs(t1-t2)<epsilon*abs(t1)``, a standard test for equality of floating
    point values. The value of ``epsilon`` is ``1e-14``.
    '''
    def __init__(self, dt, name='clock*'):
        self._i = 0
        #: The internally used dt. Note that right after a change of dt, this
        #: will not equal the new dt (which is stored in `Clock._new_dt`). Call
        #: `Clock._set_t_update_t` to update the internal clock representation.
        self._dt = float(dt)
        self._new_dt = None
        Nameable.__init__(self, name=name)
        logger.debug(
            "Created clock {self.name} with dt={self._dt}".format(self=self))

    @check_units(t=second)
    def _set_t_update_dt(self, t=0 * second):
        dt = self._new_dt if self._new_dt is not None else self._dt
        t = float(t)
        if dt != self._dt:
            self._new_dt = None  # i.e.: i is up-to-date for the dt
            # Only allow a new dt which allows to correctly set the new time step
            if t != self.t_:
                old_t = np.uint64(np.round(t / self._dt)) * self._dt
                new_t = np.uint64(np.round(t / dt)) * dt
                error_t = t
            else:
                old_t = np.uint64(np.round(self.t_ / self._dt)) * self._dt
                new_t = np.uint64(np.round(self.t_ / dt)) * dt
                error_t = self.t_
            if abs(new_t - old_t) > self.epsilon:
                raise ValueError(('Cannot set dt from {old} to {new}, the '
                                  'time {t} is not a multiple of '
                                  '{new}').format(old=self.dt,
                                                  new=dt * second,
                                                  t=error_t * second))
            self._dt = dt

        new_i = np.uint64(np.round(t / dt))
        new_t = new_i * self.dt_
        if new_t == t or np.abs(new_t - t) <= self.epsilon * np.abs(new_t):
            self._i = new_i
        else:
            self._i = np.uint64(np.ceil(t / dt))
        logger.debug(
            "Setting Clock {self.name} to t={self.t}, dt={self.dt}".format(
                self=self))

    def __str__(self):
        if self._new_dt is None:
            return 'Clock ' + self.name + ': t = ' + str(
                self.t) + ', dt = ' + str(self.dt)
        else:
            return 'Clock ' + self.name + ': t = ' + str(
                self.t) + ', (new) dt = ' + str(self._new_dt * second)

    def __repr__(self):
        return 'Clock(dt=%r, name=%r)' % (self._new_dt * second if self._new_dt
                                          is not None else self.dt, self.name)

    def tick(self):
        '''
        Advances the clock by one time step.
        '''
        self._i += 1

    @check_units(end=second)
    def _set_t_end(self, end):
        self._i_end = np.uint64(float(end) / self.dt_)

    @property
    def t_(self):
        'The simulation time as a float (in seconds)'
        return float(self._i * self._dt)

    @property
    def t(self):
        'The simulation time in seconds'
        return self.t_ * second

    def _get_dt_(self):
        if self._new_dt is None:
            return self._dt
        else:
            return self._new_dt

    @check_units(dt_=1)
    def _set_dt_(self, dt_):
        self._new_dt = dt_

    @check_units(dt=second)
    def _set_dt(self, dt):
        self._new_dt = float(dt)

    dt = property(
        fget=lambda self: Quantity(self.dt_, dim=second.dim),
        fset=_set_dt,
        doc='''The time step of the simulation in seconds.''',
    )
    dt_ = property(
        fget=_get_dt_,
        fset=_set_dt_,
        doc='''The time step of the simulation as a float (in seconds)''')
    t_end = property(fget=lambda self: self._i_end * self.dt_ * second,
                     doc='The time the simulation will end (in seconds)')

    @check_units(start=second, end=second)
    def set_interval(self, start, end):
        '''
        set_interval(self, start, end)
        
        Set the start and end time of the simulation.
        
        Sets the start and end value of the clock precisely if
        possible (using epsilon) or rounding up if not. This assures that
        multiple calls to `Network.run` will not re-run the same time step.      
        '''
        self._set_t_update_dt(t=start)
        end = float(end)
        i_end = np.uint64(np.round(end / self.dt_))
        t_end = i_end * self.dt_
        if t_end == end or np.abs(t_end - end) <= self.epsilon * np.abs(t_end):
            self._i_end = i_end
        else:
            self._i_end = np.uint64(np.ceil(end / self.dt_))

    @property
    def running(self):
        '''
        A ``bool`` to indicate whether the current simulation is running.
        '''
        return self._i < self._i_end

    epsilon = 1e-14
コード例 #34
0
ファイル: clocks.py プロジェクト: treestreamymw/brian2
class Clock(VariableOwner):
    '''
    An object that holds the simulation time and the time step.
    
    Parameters
    ----------
    dt : float
        The time step of the simulation as a float
    name : str, optional
        An explicit name, if not specified gives an automatically generated name

    Notes
    -----
    Clocks are run in the same `Network.run` iteration if `~Clock.t` is the
    same. The condition for two
    clocks to be considered as having the same time is
    ``abs(t1-t2)<epsilon*abs(t1)``, a standard test for equality of floating
    point values. The value of ``epsilon`` is ``1e-14``.
    '''
    def __init__(self, dt, name='clock*'):
        # We need a name right away because some devices (e.g. cpp_standalone)
        # need a name for the object when creating the variables
        Nameable.__init__(self, name=name)
        self._old_dt = None
        self.variables = Variables(self)
        self.variables.add_array('timestep',
                                 size=1,
                                 dtype=np.int64,
                                 read_only=True,
                                 scalar=True)
        self.variables.add_array('t',
                                 dimensions=second.dim,
                                 size=1,
                                 dtype=np.double,
                                 read_only=True,
                                 scalar=True)
        self.variables.add_array('dt',
                                 dimensions=second.dim,
                                 size=1,
                                 values=float(dt),
                                 dtype=np.float,
                                 read_only=True,
                                 constant=True,
                                 scalar=True)
        self.variables.add_constant('N', value=1)
        self._enable_group_attributes()
        self.dt = dt
        logger.diagnostic("Created clock {name} with dt={dt}".format(
            name=self.name, dt=self.dt))

    @check_units(t=second)
    def _set_t_update_dt(self, target_t=0 * second):
        new_dt = self.dt_
        old_dt = self._old_dt
        target_t = float(target_t)
        if old_dt is not None and new_dt != old_dt:
            self._old_dt = None
            # Only allow a new dt which allows to correctly set the new time step
            check_dt(new_dt, old_dt, target_t)

        new_timestep = self._calc_timestep(target_t)
        # Since these attributes are read-only for normal users, we have to
        # update them via the variables object directly
        self.variables['timestep'].set_value(new_timestep)
        self.variables['t'].set_value(new_timestep * new_dt)
        logger.diagnostic("Setting Clock {name} to t={t}, dt={dt}".format(
            name=self.name, t=self.t, dt=self.dt))

    def _calc_timestep(self, target_t):
        '''
        Calculate the integer time step for the target time. If it cannot be
        exactly represented (up to 0.01% of dt), round up.

        Parameters
        ----------
        target_t : float
            The target time in seconds

        Returns
        -------
        timestep : int
            The target time in integers (based on dt)
        '''
        new_i = np.int64(np.round(target_t / self.dt_))
        new_t = new_i * self.dt_
        if (new_t == target_t
                or np.abs(new_t - target_t) / self.dt_ <= Clock.epsilon_dt):
            new_timestep = new_i
        else:
            new_timestep = np.int64(np.ceil(target_t / self.dt_))
        return new_timestep

    def __repr__(self):
        return 'Clock(dt=%r, name=%r)' % (self.dt, self.name)

    def _get_dt_(self):
        return self.variables['dt'].get_value().item()

    @check_units(dt_=1)
    def _set_dt_(self, dt_):
        self._old_dt = self._get_dt_()
        self.variables['dt'].set_value(dt_)

    @check_units(dt=second)
    def _set_dt(self, dt):
        self._set_dt_(float(dt))

    dt = property(
        fget=lambda self: Quantity(self.dt_, dim=second.dim),
        fset=_set_dt,
        doc='''The time step of the simulation in seconds.''',
    )
    dt_ = property(
        fget=_get_dt_,
        fset=_set_dt_,
        doc='''The time step of the simulation as a float (in seconds)''')

    @check_units(start=second, end=second)
    def set_interval(self, start, end):
        '''
        set_interval(self, start, end)

        Set the start and end time of the simulation.

        Sets the start and end value of the clock precisely if
        possible (using epsilon) or rounding up if not. This assures that
        multiple calls to `Network.run` will not re-run the same time step.      
        '''
        self._set_t_update_dt(target_t=start)
        end = float(end)
        self._i_end = self._calc_timestep(end)
        if self._i_end > 2**40:
            logger.warn(
                'The end time of the simulation has been set to {}, '
                'which based on the dt value of {} means that {} '
                'time steps will be simulated. This can lead to '
                'numerical problems, e.g. the times t will not '
                'correspond to exact multiples of '
                'dt.'.format(str(end * second), str(self.dt), self._i_end),
                'many_timesteps')

    #: The relative difference for times (in terms of dt) so that they are
    #: considered identical.
    epsilon_dt = 1e-4
コード例 #35
0
ファイル: hears.py プロジェクト: msGenDev/brian2
def convert_unit_b1_to_b2(val):
    return Quantity.with_dimensions(float(val), arg.dim._dims)