Ejemplo n.º 1
0
    def __call__(self, pre_size, post_size):
        try:
            assert pre_size == post_size
        except AssertionError:
            raise errors.ModelUseError(
                f'One2One connection must be defined in two groups with the same size, '
                f'but we got {pre_size} != {post_size}.')

        length = utils.size2len(pre_size)
        self.num_pre = length
        self.num_post = length

        self.pre_ids = ops.arange(length)
        self.post_ids = ops.arange(length)
        return self
Ejemplo n.º 2
0
    def run(self, duration, inputs=(), report=False, report_percent=0.1):
        """The running function.

        Parameters
        ----------
        duration : float, int, tuple, list
            The running duration.
        inputs : list, tuple
            The model inputs with the format of ``[(key, value [operation])]``.
        report : bool
            Whether report the running progress.
        report_percent : float
            The percent of progress to report.
        """

        # times
        # ------
        start, end = utils.check_duration(duration)
        times = ops.arange(start, end, backend.get_dt())
        run_length = ops.shape(times)[0]

        # build run function
        # ------------------
        self.run_func = self.build(inputs, inputs_is_formatted=False, mon_length=run_length, return_code=False)

        # run the model
        # -------------
        res = utils.run_model(self.run_func, times, report, report_percent)
        self.mon.ts = times
        return res
Ejemplo n.º 3
0
def firing_rate(sp_matrix, width, window='gaussian'):
    """Calculate the mean firing rate over in a neuron group.

    This method is adopted from Brian2.

    The firing rate in trial :math:`k` is the spike count :math:`n_{k}^{sp}`
    in an interval of duration :math:`T` divided by :math:`T`:

    .. math::

        v_k = {n_k^{sp} \\over T}

    Parameters
    ----------
    sp_matrix : bnp.ndarray
        The spike matrix which record spiking activities.
    width : int, float
        The width of the ``window`` in millisecond.
    window : str
        The window to use for smoothing. It can be a string to chose a
        predefined window:

        - `flat`: a rectangular,
        - `gaussian`: a Gaussian-shaped window.

        For the `Gaussian` window, the `width` parameter specifies the
        standard deviation of the Gaussian, the width of the actual window
        is `4 * width + dt`.
        For the `flat` window, the width of the actual window
        is `2 * width/2 + dt`.

    Returns
    -------
    rate : numpy.ndarray
        The population rate in Hz, smoothed with the given window.
    """
    # rate
    rate = ops.sum(sp_matrix, axis=1)

    # window
    dt = backend.get_dt()
    if window == 'gaussian':
        width1 = 2 * width / dt
        width2 = int(round(width1))
        window = ops.exp(-ops.arange(-width2, width2 + 1)**2 / (width1**2 * 2))
    elif window == 'flat':
        width1 = int(width / 2 / dt) * 2 + 1
        window = ops.ones(width1)
    else:
        raise ValueError('Unknown window type "{}".'.format(window))

    return np.convolve(rate, window / sum(window), mode='same')
Ejemplo n.º 4
0
    def __init__(self, size, delay_time):
        if isinstance(size, int):
            size = (size, )
        self.size = tuple(size)
        self.delay_time = delay_time

        if isinstance(delay_time, (int, float)):
            self.uniform_delay = True
            self.delay_num_step = int(math.ceil(
                delay_time / backend.get_dt())) + 1
            self.delay_data = ops.zeros((self.delay_num_step, ) + self.size)
        else:
            if not len(self.size) == 1:
                raise NotImplementedError(
                    f'Currently, BrainPy only supports 1D heterogeneous delays, while does '
                    f'not implement the heterogeneous delay with {len(self.size)}-dimensions.'
                )
            self.num = size2len(size)
            if isinstance(delay_time, type(ops.as_tensor([1]))):
                assert ops.shape(delay_time) == self.size
            elif callable(delay_time):
                delay_time2 = ops.zeros(size)
                for i in range(size[0]):
                    delay_time2[i] = delay_time()
                delay_time = delay_time2
            else:
                raise NotImplementedError(
                    f'Currently, BrainPy does not support delay type '
                    f'of {type(delay_time)}: {delay_time}')
            self.uniform_delay = False
            delay = delay_time / backend.get_dt()
            dint = ops.as_tensor(delay_time / backend.get_dt(), dtype=int)
            ddiff = (delay - dint) >= 0.5
            self.delay_num_step = ops.as_tensor(delay + ddiff, dtype=int) + 1
            self.delay_data = ops.zeros((max(self.delay_num_step), ) + size)
            self.diag = ops.arange(self.num)

        self.delay_in_idx = self.delay_num_step - 1
        if self.uniform_delay:
            self.delay_out_idx = 0
        else:
            self.delay_out_idx = ops.zeros(self.num, dtype=int)
        self.name = None
Ejemplo n.º 5
0
    def run(self, duration, inputs=(), report=False, report_percent=0.1):
        """Run the simulation for the given duration.

        This function provides the most convenient way to run the network.
        For example:

        Parameters
        ----------
        duration : int, float, tuple, list
            The amount of simulation time to run for.
        inputs : list, tuple
            The receivers, external inputs and durations.
        report : bool
            Report the progress of the simulation.
        report_percent : float
            The speed to report simulation progress.
        """
        # preparation
        start, end = utils.check_duration(duration)
        dt = backend.get_dt()
        ts = ops.arange(start, end, dt)

        # build the network
        run_length = ts.shape[0]
        format_inputs = utils.format_net_level_inputs(inputs, run_length)
        self.run_func = self.driver.build(run_length=run_length,
                                          formatted_inputs=format_inputs,
                                          return_code=False,
                                          show_code=self.show_code)

        # run the network
        res = utils.run_model(self.run_func,
                              times=ts,
                              report=report,
                              report_percent=report_percent)

        # end
        self.t_start, self.t_end = start, end
        for obj in self.all_nodes.values():
            if obj.mon.num_item > 0:
                obj.mon.ts = ts
        return res
Ejemplo n.º 6
0
    def run(self, duration, report=False, report_percent=0.1):
        if isinstance(duration, (int, float)):
            duration = [0, duration]
        elif isinstance(duration, (tuple, list)):
            assert len(duration) == 2
            duration = tuple(duration)
        else:
            raise ValueError

        # get the times
        times = ops.arange(duration[0], duration[1], backend.get_dt())
        # reshape the monitor
        for key in self.mon.keys():
            self.mon[key] = ops.zeros((len(times), ) +
                                      ops.shape(self.mon[key])[1:])
        # run the model
        run_model(run_func=self.run_func,
                  times=times,
                  report=report,
                  report_percent=report_percent)
Ejemplo n.º 7
0
 def ts(self):
     """Get the time points of the network.
     """
     return ops.arange(self.t_start, self.t_end, backend.get_dt())