Example #1
0
    def _run_sub_tests(self, st1, st2, lags_true):
        for window in ('valid', 'full'):
            for method in ('speed', 'memory'):
                with self.subTest(window=window, method=method):
                    binsize = 1 * pq.s
                    st1_binned = conv.BinnedSpikeTrain(st1, binsize=binsize)
                    st2_binned = conv.BinnedSpikeTrain(st2, binsize=binsize)
                    left, right = lags_true[window][(0, -1), ]
                    cch_window, lags_window = sc.cross_correlation_histogram(
                        st1_binned,
                        st2_binned,
                        window=(left, right),
                        method=method,
                    )
                    cch, lags = sc.cross_correlation_histogram(st1_binned,
                                                               st2_binned,
                                                               window=window)

                    # target cross correlation
                    cch_target = np.correlate(st1_binned.to_array()[0],
                                              st2_binned.to_array()[0],
                                              mode=window)

                    self.assertEqual(len(lags_window), cch_window.shape[0])
                    assert_array_almost_equal(cch.magnitude,
                                              cch_window.magnitude)
                    # the output is reversed since we cross-correlate
                    # st2 with st1 rather than st1 with st2 (numpy behavior)
                    assert_array_almost_equal(np.ravel(cch.magnitude),
                                              cch_target[::-1])
                    assert_array_equal(lags, lags_true[window])
                    assert_array_equal(lags, lags_window)
    def test_border_correction(self):
        '''Test if the border correction for bins at the edges is correctly
        performed'''
        cch_corrected, _ = sc.cross_correlation_histogram(
            self.binned_st1,
            self.binned_st2,
            window='full',
            border_correction=True,
            binary=False,
            kernel=None)
        cch_corrected_mem, _ = sc.cross_correlation_histogram(
            self.binned_st1,
            self.binned_st2,
            window='full',
            border_correction=True,
            binary=False,
            kernel=None,
            method='memory')
        cch, _ = sc.cross_correlation_histogram(self.binned_st1,
                                                self.binned_st2,
                                                window='full',
                                                border_correction=False,
                                                binary=False,
                                                kernel=None)
        cch_mem, _ = sc.cross_correlation_histogram(self.binned_st1,
                                                    self.binned_st2,
                                                    window='full',
                                                    border_correction=False,
                                                    binary=False,
                                                    kernel=None,
                                                    method='memory')

        self.assertEqual(np.any(np.not_equal(cch, cch_corrected)), True)
        self.assertEqual(np.any(np.not_equal(cch_mem, cch_corrected_mem)),
                         True)
Example #3
0
    def test_kernel(self):
        '''Test if the smoothing kernel is correctly defined, and wheter it is
        applied properly.'''
        smoothed_cch, _ = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, kernel=np.ones(3))
        smoothed_cch_mem, _ = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, kernel=np.ones(3),
            method='memory')

        cch, _ = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, kernel=None)
        cch_mem, _ = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, kernel=None, method='memory')

        self.assertNotEqual(smoothed_cch.all, cch.all)
        self.assertNotEqual(smoothed_cch_mem.all, cch_mem.all)

        self.assertRaises(
            ValueError, sc.cch, self.binned_st1, self.binned_st2,
            kernel=np.ones(100))
        self.assertRaises(
            ValueError, sc.cch, self.binned_st1, self.binned_st2,
            kernel=np.ones(100), method='memory')

        self.assertRaises(
            ValueError, sc.cch, self.binned_st1, self.binned_st2, kernel='BOX')
        self.assertRaises(
            ValueError, sc.cch, self.binned_st1, self.binned_st2, kernel='BOX',
            method='memory')
    def test_kernel(self):
        '''Test if the smoothing kernel is correctly defined, and wheter it is
        applied properly.'''
        smoothed_cch, _ = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, kernel=np.ones(3))
        smoothed_cch_mem, _ = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, kernel=np.ones(3),
            method='memory')

        cch, _ = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, kernel=None)
        cch_mem, _ = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, kernel=None, method='memory')

        self.assertNotEqual(smoothed_cch.all, cch.all)
        self.assertNotEqual(smoothed_cch_mem.all, cch_mem.all)

        self.assertRaises(
            ValueError, sc.cch, self.binned_st1, self.binned_st2,
            kernel=np.ones(100))
        self.assertRaises(
            ValueError, sc.cch, self.binned_st1, self.binned_st2,
            kernel=np.ones(100), method='memory')

        self.assertRaises(
            ValueError, sc.cch, self.binned_st1, self.binned_st2, kernel='BOX')
        self.assertRaises(
            ValueError, sc.cch, self.binned_st1, self.binned_st2, kernel='BOX',
            method='memory')
Example #5
0
    def test_border_correction(self):
        '''Test if the border correction for bins at the edges is correctly
        performed'''

        # check that nothing changes for valid lags
        cch_valid, _ = sc.cross_correlation_histogram(self.binned_st1,
                                                      self.binned_st2,
                                                      window='full',
                                                      border_correction=True,
                                                      binary=False,
                                                      kernel=None)
        valid_lags = sc._CrossCorrHist.get_valid_lags(self.binned_st1,
                                                      self.binned_st2)
        left_edge, right_edge = valid_lags[(0, -1), ]
        cch_builder = sc._CrossCorrHist(self.binned_st1,
                                        self.binned_st2,
                                        window=(left_edge, right_edge))
        cch_valid = cch_builder.correlate_speed(cch_mode='valid')
        cch_corrected = cch_builder.border_correction(cch_valid)

        np.testing.assert_array_equal(cch_valid, cch_corrected)

        # test the border correction for lags without full overlap
        cch_full, lags_full = sc.cross_correlation_histogram(self.binned_st1,
                                                             self.binned_st2,
                                                             window='full')

        cch_full_corrected, _ = sc.cross_correlation_histogram(
            self.binned_st1,
            self.binned_st2,
            window='full',
            border_correction=True)

        num_bins_outside_window = np.min(np.abs(
            np.subtract.outer(lags_full, valid_lags)),
                                         axis=1)

        min_num_bins = min(self.binned_st1.num_bins, self.binned_st2.num_bins)

        border_correction = (cch_full_corrected / cch_full).magnitude.flatten()

        # exclude NaNs caused by zeros in the cch
        mask = np.logical_not(np.isnan(border_correction))

        np.testing.assert_array_almost_equal(
            border_correction[mask],
            (float(min_num_bins) /
             (min_num_bins - num_bins_outside_window))[mask])
Example #6
0
 def test_annotations(self):
     cch, _ = sc.cross_correlation_histogram(
         self.binned_st1, self.binned_st2, kernel=np.ones(3))
     target_dict = dict(window='full', border_correction=False,
                        binary=False, kernel=True,
                        normalization='counts')
     self.assertIn('cch_parameters', cch.annotations)
     self.assertEqual(cch.annotations['cch_parameters'], target_dict)
    def test_border_correction(self):
        '''Test if the border correction for bins at the edges is correctly
        performed'''
        cch_corrected, _ = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='full',
            border_correction=True, binary=False, kernel=None)
        cch_corrected_mem, _ = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='full',
            border_correction=True, binary=False, kernel=None, method='memory')
        cch, _ = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='full',
            border_correction=False, binary=False, kernel=None)
        cch_mem, _ = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='full',
            border_correction=False, binary=False, kernel=None,
            method='memory')

        self.assertNotEqual(cch.all(), cch_corrected.all())
        self.assertNotEqual(cch_mem.all(), cch_corrected_mem.all())
Example #8
0
    def test_window(self):
        """Test if the window parameter is correctly interpreted."""
        cch_win, bin_ids = sc.cch(
            self.binned_st1, self.binned_st2, window=[-30, 30])
        cch_win_mem, bin_ids_mem = sc.cch(
            self.binned_st1, self.binned_st2, window=[-30, 30],
            method='memory')

        self.assertEqual(len(bin_ids), cch_win.shape[0])
        assert_array_equal(bin_ids, np.arange(-30, 31, 1))
        assert_array_equal(
            (bin_ids - 0.5) * self.binned_st1.bin_size, cch_win.times)

        assert_array_equal(bin_ids_mem, np.arange(-30, 31, 1))
        assert_array_equal(
            (bin_ids_mem - 0.5) * self.binned_st1.bin_size, cch_win.times)

        assert_array_equal(cch_win, cch_win_mem)
        cch_unclipped, _ = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='full', binary=False)
        assert_array_equal(cch_win, cch_unclipped[19:80])

        _, bin_ids = sc.cch(
            self.binned_st1, self.binned_st2, window=[20, 30])
        _, bin_ids_mem = sc.cch(
            self.binned_st1, self.binned_st2, window=[20, 30], method='memory')

        assert_array_equal(bin_ids, np.arange(20, 31, 1))
        assert_array_equal(bin_ids_mem, np.arange(20, 31, 1))

        _, bin_ids = sc.cch(
            self.binned_st1, self.binned_st2, window=[-30, -20])

        _, bin_ids_mem = sc.cch(
            self.binned_st1, self.binned_st2, window=[-30, -20],
            method='memory')

        assert_array_equal(bin_ids, np.arange(-30, -19, 1))
        assert_array_equal(bin_ids_mem, np.arange(-30, -19, 1))

        # Check for wrong assignments to the window parameter
        # Test for window longer than the total length of the spike trains
        self.assertRaises(
            ValueError, sc.cross_correlation_histogram, self.binned_st1,
            self.binned_st2, window=[-60, 50])
        self.assertRaises(
            ValueError, sc.cross_correlation_histogram, self.binned_st1,
            self.binned_st2, window=[-50, 60])
        # Test for no integer or wrong string in input
        self.assertRaises(
            ValueError, sc.cross_correlation_histogram, self.binned_st1,
            self.binned_st2, window=[-25.5, 25.5])
        self.assertRaises(
            ValueError, sc.cross_correlation_histogram, self.binned_st1,
            self.binned_st2, window='test')
Example #9
0
def CorrelationPlot(ST, nr, bins, vis):
    b = 25001  # amount of bins the spikes get divided into
    sIO = ST
    delays = np.zeros((nr, nr))
    show = vis

    for ll in range(0, nr):
        for m in range(0, nr):
            t_end = int(max(sIO[0]))
            t_s = int(min(sIO[0]))

            ioN = sIO[m] * pq.s

            ioM = sIO[ll] * pq.s

            st = n.SpikeTrain(ioN,
                              t_start=t_s * pq.s,
                              t_stop=(t_end + 1) * pq.s)
            st2 = n.SpikeTrain(ioM,
                               t_start=t_s * pq.s,
                               t_stop=(t_end + 1) * pq.s)

            x = conv.BinnedSpikeTrain(st, num_bins=bins, t_start=t_s * pq.s)
            x2 = conv.BinnedSpikeTrain(st2, num_bins=bins, t_start=t_s * pq.s)

            cor12 = stcorr.cross_correlation_histogram(x, x2, window='full')

            window = cor12[1]
            edges = [min(window), max(window)]
            st_obj = CrossCorrHist(x, x2, window=edges)

            k = st_obj.correlate_memory()

            # why does 'binnedspiketrain' does not have attribute 'get_num_spikes'
            # the code suggests that it does.

            delay = np.where(k == max(k))
            if ll == m:
                norm_val = max(k)
            #print(delay[0][0])
            #print()
            delays[ll, m] = delay[0][0] - max(window)
            #print(delay)
            #print(len(k))
            t = np.linspace(-(t_end - t_s), (t_end - t_s), num=bins * 2 - 1)
            if show == 'yes':
                plt.figure()
                plt.title('IO cell 0 correlated with IO cell' + str(m))
                plt.plot(t, k / norm_val)
                plt.ylabel('correlation value[-]')
                plt.xlabel('bins centered around zero')
                plt.show()

    return delays
Example #10
0
def calcCCH(i, j, dataset):

    #use elephant to recreate cross_correlation_histograms
    cch = cross_correlation_histogram(
        (BinnedSpikeTrain(neoDataset[i], binsize=1 * ms)),
        (BinnedSpikeTrain(neoDataset[j], binsize=1 * ms)),
        window=[-10, 10],
        border_correction=True,
        binary=False,
        kernel=None)
    cchArray1 = np.array(cch[0][:, 0].magnitude)
    return cchArray1.max()
    def test_window(self):
        '''Test if the window parameter is correctly interpreted.'''
        cch_win, bin_ids = sc.cch(
            self.binned_st1, self.binned_st2, window=[-30, 30])
        cch_win_mem, bin_ids_mem = sc.cch(
            self.binned_st1, self.binned_st2, window=[-30, 30])

        assert_array_equal(bin_ids, np.arange(-30, 31, 1))
        assert_array_equal(
            (bin_ids - 0.5) * self.binned_st1.binsize, cch_win.times)

        assert_array_equal(bin_ids_mem, np.arange(-30, 31, 1))
        assert_array_equal(
            (bin_ids_mem - 0.5) * self.binned_st1.binsize, cch_win.times)

        assert_array_equal(cch_win, cch_win_mem)
        cch_unclipped, _ = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='full', binary=False)
        assert_array_equal(cch_win, cch_unclipped[19:80])

        _, bin_ids = sc.cch(
            self.binned_st1, self.binned_st2, window=[20, 30])
        _, bin_ids_mem = sc.cch(
            self.binned_st1, self.binned_st2, window=[20, 30], method='memory')

        assert_array_equal(bin_ids, np.arange(20, 31, 1))
        assert_array_equal(bin_ids_mem, np.arange(20, 31, 1))

        _, bin_ids = sc.cch(
            self.binned_st1, self.binned_st2, window=[-30, -20])

        _, bin_ids_mem = sc.cch(
            self.binned_st1, self.binned_st2, window=[-30, -20],
            method='memory')

        assert_array_equal(bin_ids, np.arange(-30, -19, 1))
        assert_array_equal(bin_ids_mem, np.arange(-30, -19, 1))

        # Check for wrong assignments to the window parameter
        # Test for window longer than the total length of the spike trains
        self.assertRaises(
            ValueError, sc.cross_correlation_histogram, self.binned_st1,
            self.binned_st2, window=[-60, 50])
        self.assertRaises(
            ValueError, sc.cross_correlation_histogram, self.binned_st1,
            self.binned_st2, window=[-50, 60])
        # Test for no integer or wrong string in input
        self.assertRaises(
            KeyError, sc.cross_correlation_histogram, self.binned_st1,
            self.binned_st2, window=[-25.5, 25.5])
        self.assertRaises(
            KeyError, sc.cross_correlation_histogram, self.binned_st1,
            self.binned_st2, window='test')
Example #12
0
    def test_cross_correlation_histogram(self):
        '''
        Test generic result of a cross-correlation histogram between two binned
        spike trains.
        '''
        # Calculate CCH using Elephant (normal and binary version) with
        # mode equal to 'full' (whole spike trains are correlated)
        cch_clipped, bin_ids_clipped = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='full', binary=True)
        cch_unclipped, bin_ids_unclipped = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='full', binary=False)

        cch_clipped_mem, bin_ids_clipped_mem = sc.cross_correlation_histogram(
            self.binned_st1,
            self.binned_st2,
            window='full',
            binary=True,
            method='memory')
        cch_unclipped_mem, bin_ids_unclipped_mem = sc.cross_correlation_histogram(
            self.binned_st1,
            self.binned_st2,
            window='full',
            binary=False,
            method='memory')
        # Check consistency two methods
        assert_array_equal(np.squeeze(cch_clipped.magnitude),
                           np.squeeze(cch_clipped_mem.magnitude))
        assert_array_equal(np.squeeze(cch_clipped.times),
                           np.squeeze(cch_clipped_mem.times))
        assert_array_equal(np.squeeze(cch_unclipped.magnitude),
                           np.squeeze(cch_unclipped_mem.magnitude))
        assert_array_equal(np.squeeze(cch_unclipped.times),
                           np.squeeze(cch_unclipped_mem.times))
        assert_array_almost_equal(bin_ids_clipped, bin_ids_clipped_mem)
        assert_array_almost_equal(bin_ids_unclipped, bin_ids_unclipped_mem)

        # Check normal correlation Note: Use numpy correlate to verify result.
        # Note: numpy conventions for input array 1 and input array 2 are
        # swapped compared to Elephant!
        mat1 = self.binned_st1.to_array()[0]
        mat2 = self.binned_st2.to_array()[0]
        target_numpy = np.correlate(mat2, mat1, mode='full')
        assert_array_equal(target_numpy, np.squeeze(cch_unclipped.magnitude))

        # Check correlation using binary spike trains
        mat1 = np.array(self.binned_st1.to_bool_array()[0], dtype=int)
        mat2 = np.array(self.binned_st2.to_bool_array()[0], dtype=int)
        target_numpy = np.correlate(mat2, mat1, mode='full')
        assert_array_equal(target_numpy, np.squeeze(cch_clipped.magnitude))

        # Check the time axis and bin IDs of the resulting AnalogSignalArray
        assert_array_almost_equal(
            (bin_ids_clipped - 0.5) * self.binned_st1.binsize,
            cch_unclipped.times)
        assert_array_almost_equal(
            (bin_ids_clipped - 0.5) * self.binned_st1.binsize,
            cch_clipped.times)

        # Calculate CCH using Elephant (normal and binary version) with
        # mode equal to 'valid' (only completely overlapping intervals of the
        # spike trains are correlated)
        cch_clipped, bin_ids_clipped = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='valid', binary=True)
        cch_unclipped, bin_ids_unclipped = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='valid', binary=False)
        cch_clipped_mem, bin_ids_clipped_mem = sc.cross_correlation_histogram(
            self.binned_st1,
            self.binned_st2,
            window='valid',
            binary=True,
            method='memory')
        cch_unclipped_mem, bin_ids_unclipped_mem = sc.cross_correlation_histogram(
            self.binned_st1,
            self.binned_st2,
            window='valid',
            binary=False,
            method='memory')

        # Check consistency two methods
        assert_array_equal(np.squeeze(cch_clipped.magnitude),
                           np.squeeze(cch_clipped_mem.magnitude))
        assert_array_equal(np.squeeze(cch_clipped.times),
                           np.squeeze(cch_clipped_mem.times))
        assert_array_equal(np.squeeze(cch_unclipped.magnitude),
                           np.squeeze(cch_unclipped_mem.magnitude))
        assert_array_equal(np.squeeze(cch_unclipped.times),
                           np.squeeze(cch_unclipped_mem.times))
        assert_array_equal(bin_ids_clipped, bin_ids_clipped_mem)
        assert_array_equal(bin_ids_unclipped, bin_ids_unclipped_mem)

        # Check normal correlation Note: Use numpy correlate to verify result.
        # Note: numpy conventions for input array 1 and input array 2 are
        # swapped compared to Elephant!
        mat1 = self.binned_st1.to_array()[0]
        mat2 = self.binned_st2.to_array()[0]
        target_numpy = np.correlate(mat2, mat1, mode='valid')
        assert_array_equal(target_numpy, np.squeeze(cch_unclipped.magnitude))

        # Check correlation using binary spike trains
        mat1 = np.array(self.binned_st1.to_bool_array()[0], dtype=int)
        mat2 = np.array(self.binned_st2.to_bool_array()[0], dtype=int)
        target_numpy = np.correlate(mat2, mat1, mode='valid')
        assert_array_equal(target_numpy, np.squeeze(cch_clipped.magnitude))

        # Check the time axis and bin IDs of the resulting AnalogSignalArray
        assert_array_equal((bin_ids_clipped - 0.5) * self.binned_st1.binsize,
                           cch_unclipped.times)
        assert_array_equal((bin_ids_clipped - 0.5) * self.binned_st1.binsize,
                           cch_clipped.times)

        # Check for wrong window parameter setting
        self.assertRaises(KeyError,
                          sc.cross_correlation_histogram,
                          self.binned_st1,
                          self.binned_st2,
                          window='dsaij')
        self.assertRaises(KeyError,
                          sc.cross_correlation_histogram,
                          self.binned_st1,
                          self.binned_st2,
                          window='dsaij',
                          method='memory')
    def test_window(self):
        '''Test if the window parameter is correctly interpreted.'''
        cch_win, bin_ids = sc.cch(
            self.binned_st1, self.binned_st2, window=[-30, 30])
        cch_win_mem, bin_ids_mem = sc.cch(
            self.binned_st1, self.binned_st2, window=[-30, 30])

        assert_array_equal(bin_ids, np.arange(-30, 31, 1))
        assert_array_equal(
            (bin_ids - 0.5) * self.binned_st1.binsize, cch_win.times)

        assert_array_equal(bin_ids_mem, np.arange(-30, 31, 1))
        assert_array_equal(
            (bin_ids_mem - 0.5) * self.binned_st1.binsize, cch_win.times)

        assert_array_equal(cch_win, cch_win_mem)
        cch_unclipped, _ = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='full', binary=False)
        assert_array_equal(cch_win, cch_unclipped[19:80])

        cch_win, bin_ids = sc.cch(
            self.binned_st1, self.binned_st2, window=[-25*pq.ms, 25*pq.ms])
        cch_win_mem, bin_ids_mem = sc.cch(
            self.binned_st1, self.binned_st2, window=[-25*pq.ms, 25*pq.ms],
            method='memory')

        assert_array_equal(bin_ids, np.arange(-25, 26, 1))
        assert_array_equal(
            (bin_ids - 0.5) * self.binned_st1.binsize, cch_win.times)

        assert_array_equal(bin_ids_mem, np.arange(-25, 26, 1))
        assert_array_equal(
            (bin_ids_mem - 0.5) * self.binned_st1.binsize, cch_win.times)

        assert_array_equal(cch_win, cch_win_mem)

        _, bin_ids = sc.cch(
            self.binned_st1, self.binned_st2, window=[20, 30])
        _, bin_ids_mem = sc.cch(
            self.binned_st1, self.binned_st2, window=[20, 30], method='memory')

        assert_array_equal(bin_ids, np.arange(20, 31, 1))
        assert_array_equal(bin_ids_mem, np.arange(20, 31, 1))

        _, bin_ids = sc.cch(
            self.binned_st1, self.binned_st2, window=[-30, -20])

        _, bin_ids_mem = sc.cch(
            self.binned_st1, self.binned_st2, window=[-30, -20],
            method='memory')

        assert_array_equal(bin_ids, np.arange(-30, -19, 1))
        assert_array_equal(bin_ids_mem, np.arange(-30, -19, 1))

        # Cehck for wrong assignments to the window parameter
        self.assertRaises(
            ValueError, sc.cross_correlation_histogram, self.binned_st1,
            self.binned_st2, window=[-60, 50])
        self.assertRaises(
            ValueError, sc.cross_correlation_histogram, self.binned_st1,
            self.binned_st2, window=[-60, 50], method='memory')

        self.assertRaises(
            ValueError, sc.cross_correlation_histogram, self.binned_st1,
            self.binned_st2, window=[-50, 60])
        self.assertRaises(
            ValueError, sc.cross_correlation_histogram, self.binned_st1,
            self.binned_st2, window=[-50, 60], method='memory')

        self.assertRaises(
            ValueError, sc.cross_correlation_histogram, self.binned_st1,
            self.binned_st2, window=[-25.5*pq.ms, 25*pq.ms])
        self.assertRaises(
            ValueError, sc.cross_correlation_histogram, self.binned_st1,
            self.binned_st2, window=[-25.5*pq.ms, 25*pq.ms], method='memory')

        self.assertRaises(
            ValueError, sc.cross_correlation_histogram, self.binned_st1,
            self.binned_st2, window=[-25*pq.ms, 25.5*pq.ms])
        self.assertRaises(
            ValueError, sc.cross_correlation_histogram, self.binned_st1,
            self.binned_st2, window=[-25*pq.ms, 25.5*pq.ms], method='memory')

        self.assertRaises(
            ValueError, sc.cross_correlation_histogram, self.binned_st1,
            self.binned_st2, window=[-60*pq.ms, 50*pq.ms])
        self.assertRaises(
            ValueError, sc.cross_correlation_histogram, self.binned_st1,
            self.binned_st2, window=[-60*pq.ms, 50*pq.ms], method='memory')

        self.assertRaises(
            ValueError, sc.cross_correlation_histogram, self.binned_st1,
            self.binned_st2, window=[-50*pq.ms, 60*pq.ms])
        self.assertRaises(
            ValueError, sc.cross_correlation_histogram, self.binned_st1,
            self.binned_st2, window=[-50*pq.ms, 60*pq.ms], method='memory')
    def test_cross_correlation_histogram(self):
        '''
        Test generic result of a cross-correlation histogram between two binned
        spike trains.
        '''
        # Calculate CCH using Elephant (normal and binary version) with
        # mode equal to 'full' (whole spike trains are correlated)
        cch_clipped, bin_ids_clipped = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='full',
            binary=True)
        cch_unclipped, bin_ids_unclipped = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='full', binary=False)

        cch_clipped_mem, bin_ids_clipped_mem = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='full',
            binary=True, method='memory')
        cch_unclipped_mem, bin_ids_unclipped_mem = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='full',
            binary=False, method='memory')
        # Check consistency two methods
        assert_array_equal(
            np.squeeze(cch_clipped.magnitude), np.squeeze(
                cch_clipped_mem.magnitude))
        assert_array_equal(
            np.squeeze(cch_clipped.times), np.squeeze(
                cch_clipped_mem.times))
        assert_array_equal(
            np.squeeze(cch_unclipped.magnitude), np.squeeze(
                cch_unclipped_mem.magnitude))
        assert_array_equal(
            np.squeeze(cch_unclipped.times), np.squeeze(
                cch_unclipped_mem.times))
        assert_array_almost_equal(bin_ids_clipped, bin_ids_clipped_mem)
        assert_array_almost_equal(bin_ids_unclipped, bin_ids_unclipped_mem)

        # Check normal correlation Note: Use numpy correlate to verify result.
        # Note: numpy conventions for input array 1 and input array 2 are
        # swapped compared to Elephant!
        mat1 = self.binned_st1.to_array()[0]
        mat2 = self.binned_st2.to_array()[0]
        target_numpy = np.correlate(mat2, mat1, mode='full')
        assert_array_equal(
            target_numpy, np.squeeze(cch_unclipped.magnitude))

        # Check correlation using binary spike trains
        mat1 = np.array(self.binned_st1.to_bool_array()[0], dtype=int)
        mat2 = np.array(self.binned_st2.to_bool_array()[0], dtype=int)
        target_numpy = np.correlate(mat2, mat1, mode='full')
        assert_array_equal(
            target_numpy, np.squeeze(cch_clipped.magnitude))

        # Check the time axis and bin IDs of the resulting AnalogSignalArray
        assert_array_almost_equal(
            (bin_ids_clipped - 0.5) * self.binned_st1.binsize,
            cch_unclipped.times)
        assert_array_almost_equal(
            (bin_ids_clipped - 0.5) * self.binned_st1.binsize,
            cch_clipped.times)

        # Calculate CCH using Elephant (normal and binary version) with
        # mode equal to 'valid' (only completely overlapping intervals of the
        # spike trains are correlated)
        cch_clipped, bin_ids_clipped = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='valid',
            binary=True)
        cch_unclipped, bin_ids_unclipped = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='valid',
            binary=False)
        cch_clipped_mem, bin_ids_clipped_mem = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='valid',
            binary=True, method='memory')
        cch_unclipped_mem, bin_ids_unclipped_mem = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='valid',
            binary=False, method='memory')

        # Check consistency two methods
        assert_array_equal(
            np.squeeze(cch_clipped.magnitude), np.squeeze(
                cch_clipped_mem.magnitude))
        assert_array_equal(
            np.squeeze(cch_clipped.times), np.squeeze(
                cch_clipped_mem.times))
        assert_array_equal(
            np.squeeze(cch_unclipped.magnitude), np.squeeze(
                cch_unclipped_mem.magnitude))
        assert_array_equal(
            np.squeeze(cch_unclipped.times), np.squeeze(
                cch_unclipped_mem.times))
        assert_array_equal(bin_ids_clipped, bin_ids_clipped_mem)
        assert_array_equal(bin_ids_unclipped, bin_ids_unclipped_mem)

        # Check normal correlation Note: Use numpy correlate to verify result.
        # Note: numpy conventions for input array 1 and input array 2 are
        # swapped compared to Elephant!
        mat1 = self.binned_st1.to_array()[0]
        mat2 = self.binned_st2.to_array()[0]
        target_numpy = np.correlate(mat2, mat1, mode='valid')
        assert_array_equal(
            target_numpy, np.squeeze(cch_unclipped.magnitude))

        # Check correlation using binary spike trains
        mat1 = np.array(self.binned_st1.to_bool_array()[0], dtype=int)
        mat2 = np.array(self.binned_st2.to_bool_array()[0], dtype=int)
        target_numpy = np.correlate(mat2, mat1, mode='valid')
        assert_array_equal(
            target_numpy, np.squeeze(cch_clipped.magnitude))

        # Check the time axis and bin IDs of the resulting AnalogSignalArray
        assert_array_equal(
            (bin_ids_clipped - 0.5) * self.binned_st1.binsize,
            cch_unclipped.times)
        assert_array_equal(
            (bin_ids_clipped - 0.5) * self.binned_st1.binsize,
            cch_clipped.times)

        # Check for wrong window parameter setting
        self.assertRaises(
            KeyError, sc.cross_correlation_histogram, self.binned_st1,
            self.binned_st2, window='dsaij')
        self.assertRaises(
            KeyError, sc.cross_correlation_histogram, self.binned_st1,
            self.binned_st2, window='dsaij', method='memory')
Example #15
0
def cch(block, unit1=0, unit2=1):
    # Load the data

    sts1 = [segment.spiketrains[unit1] for segment in block.segments]
    sts2 = [segment.spiketrains[unit2] for segment in block.segments]

    # Compute the CCH
    w = 2 * pq.ms  # binsize for CCH
    maxlag = 200 * pq.ms  # maximum correlation lag
    Nlags = int((maxlag / w).simplified)
    CCH = neo.AnalogSignal(np.zeros(2 * Nlags + 1) * pq.dimensionless,
                           sampling_period=w,
                           t_start=-maxlag)

    for st1, st2 in zip(sts1, sts2):
        CCH += corr.cross_correlation_histogram(conv.BinnedSpikeTrain(st1, w),
                                                conv.BinnedSpikeTrain(st2, w),
                                                window=[-Nlags, Nlags],
                                                border_correction=False,
                                                binary=True)[0]
    CCH = CCH / float(len(sts1))

    # Compute PSTH
    psth1 = stats.time_histogram(sts1, binsize=w, output='rate').rescale('Hz')
    psth2 = stats.time_histogram(sts2, binsize=w, output='rate').rescale('Hz')
    # Compute ISI dist
    ISIpdf1 = misc.isi_pdf(sts1, bins=w, rng=[0 * pq.s, None], density=True)
    ISIpdf2 = misc.isi_pdf(sts2, bins=w, rng=[0 * pq.s, None], density=True)

    # plot
    plt.figure(figsize=(12, 8))
    plt.subplots_adjust(top=.85,
                        right=.85,
                        left=.2,
                        bottom=.1,
                        hspace=.7,
                        wspace=.3)
    num_row, num_col = 4, 3
    ax = plt.subplot2grid((num_row, num_col), (0, 0), rowspan=1, colspan=2)
    misc.raster(sts1, ms=2, xlabel='time', ylabel='trial id', color='r')

    plt.subplot2grid((num_row, num_col), (1, 0),
                     rowspan=1,
                     colspan=2,
                     sharex=ax)
    misc.raster(sts2, ms=2, xlabel='time', ylabel='trial id', color='b')

    plt.subplot2grid((num_row, num_col), (2, 0),
                     rowspan=2,
                     colspan=2,
                     sharex=ax)
    plt.title('PSTH')
    plt.plot(psth1.times, psth1, color='r')
    plt.plot(psth2.times, psth2, color='b')
    ax.set_xlim(0, 4010)  #max(psth1.times.magnitude))

    plt.subplot2grid((num_row, num_col), (0, 2), rowspan=1, colspan=1)
    plt.plot([len(st) for st in sts1],
             range(1,
                   len(sts1) + 1),
             '.-',
             ms=5,
             color='r')
    plt.title('Spike Count')
    plt.ylabel('trial id')
    plt.subplot2grid((num_row, num_col), (1, 2), rowspan=1, colspan=1)
    plt.plot([len(st) for st in sts2],
             range(1,
                   len(sts2) + 1),
             '.-',
             ms=5,
             color='b')
    plt.ylabel('trial id')

    plt.subplot2grid((num_row, num_col), (2, 2), rowspan=2, colspan=1)
    plt.plot(ISIpdf1.times, ISIpdf1, color='r')
    plt.plot(ISIpdf2.times, ISIpdf2, color='b')
    plt.title('ISI distribution')

    # Plot the CCH
    plt.figure(figsize=(12, 8))
    plt.subplot2grid((2, 2), (1, 1), rowspan=2, colspan=2)
    plt.plot(CCH.times.rescale(pq.ms), CCH, 'k-', label='raw CCH')
    plt.title('CCH')
    plt.xlabel('time lag (%s)' % (CCH.times.units.__str__().split(' ')[-1]))
    plt.ylabel('counts')
    plt.xlim(-maxlag, maxlag)
    plt.legend()
    plt.show()
Example #16
0
    def test_cross_correlation_histogram(self):
        '''
        Test generic result of a cross-correlation histogram between two binned
        spike trains.
        '''
        # Calculate CCH using Elephant (normal and binary version) with
        # mode equal to 'full' (whole spike trains are correlated)
        cch_clipped, bin_ids_clipped = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='full',
            binary=True)
        cch_unclipped, bin_ids_unclipped = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='full', binary=False)

        cch_clipped_mem, bin_ids_clipped_mem = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='full',
            binary=True, method='memory')
        cch_unclipped_mem, bin_ids_unclipped_mem = \
            sc.cross_correlation_histogram(
                self.binned_st1, self.binned_st2, window='full',
                binary=False, method='memory')
        # Check consistency two methods
        assert_array_equal(
            np.squeeze(cch_clipped.magnitude), np.squeeze(
                cch_clipped_mem.magnitude))
        assert_array_equal(
            np.squeeze(cch_clipped.times), np.squeeze(
                cch_clipped_mem.times))
        assert_array_equal(
            np.squeeze(cch_unclipped.magnitude), np.squeeze(
                cch_unclipped_mem.magnitude))
        assert_array_equal(
            np.squeeze(cch_unclipped.times), np.squeeze(
                cch_unclipped_mem.times))
        assert_array_almost_equal(bin_ids_clipped, bin_ids_clipped_mem)
        assert_array_almost_equal(bin_ids_unclipped, bin_ids_unclipped_mem)

        # Check normal correlation Note: Use numpy correlate to verify result.
        # Note: numpy conventions for input array 1 and input array 2 are
        # swapped compared to Elephant!
        mat1 = self.binned_st1.to_array()[0]
        mat2 = self.binned_st2.to_array()[0]
        target_numpy = np.correlate(mat2, mat1, mode='full')
        assert_array_equal(
            target_numpy, np.squeeze(cch_unclipped.magnitude))

        # Check cross correlation function for several displacements tau
        # Note: Use Elephant corrcoeff to verify result
        tau = [-25.0, 0.0, 13.0]  # in ms
        for t in tau:
            # adjust t_start, t_stop to shift by tau
            t0 = np.min([self.st_1.t_start + t * pq.ms, self.st_2.t_start])
            t1 = np.max([self.st_1.t_stop + t * pq.ms, self.st_2.t_stop])
            st1 = neo.SpikeTrain(self.st_1.magnitude + t, units='ms',
                                 t_start=t0 * pq.ms, t_stop=t1 * pq.ms)
            st2 = neo.SpikeTrain(self.st_2.magnitude, units='ms',
                                 t_start=t0 * pq.ms, t_stop=t1 * pq.ms)
            binned_sts = conv.BinnedSpikeTrain([st1, st2],
                                               binsize=1 * pq.ms,
                                               t_start=t0 * pq.ms,
                                               t_stop=t1 * pq.ms)
            # caluclate corrcoef
            corrcoef = sc.corrcoef(binned_sts)[1, 0]

            # expand t_stop to have two spike trains with same length as st1,
            # st2
            st1 = neo.SpikeTrain(self.st_1.magnitude, units='ms',
                                 t_start=self.st_1.t_start,
                                 t_stop=self.st_1.t_stop + np.abs(t) * pq.ms)
            st2 = neo.SpikeTrain(self.st_2.magnitude, units='ms',
                                 t_start=self.st_2.t_start,
                                 t_stop=self.st_2.t_stop + np.abs(t) * pq.ms)
            binned_st1 = conv.BinnedSpikeTrain(
                st1, t_start=0 * pq.ms, t_stop=(50 + np.abs(t)) * pq.ms,
                binsize=1 * pq.ms)
            binned_st2 = conv.BinnedSpikeTrain(
                st2, t_start=0 * pq.ms, t_stop=(50 + np.abs(t)) * pq.ms,
                binsize=1 * pq.ms)
            # calculate CCHcoef and take value at t=tau
            CCHcoef, _ = sc.cch(binned_st1, binned_st2,
                                cross_corr_coef=True)
            left_edge = - binned_st1.num_bins + 1
            tau_bin = int(t / float(binned_st1.binsize.magnitude))
            assert_array_equal(
                corrcoef, CCHcoef[tau_bin - left_edge].magnitude)

        # Check correlation using binary spike trains
        mat1 = np.array(self.binned_st1.to_bool_array()[0], dtype=int)
        mat2 = np.array(self.binned_st2.to_bool_array()[0], dtype=int)
        target_numpy = np.correlate(mat2, mat1, mode='full')
        assert_array_equal(
            target_numpy, np.squeeze(cch_clipped.magnitude))

        # Check the time axis and bin IDs of the resulting AnalogSignal
        assert_array_almost_equal(
            (bin_ids_clipped - 0.5) * self.binned_st1.binsize,
            cch_unclipped.times)
        assert_array_almost_equal(
            (bin_ids_clipped - 0.5) * self.binned_st1.binsize,
            cch_clipped.times)

        # Calculate CCH using Elephant (normal and binary version) with
        # mode equal to 'valid' (only completely overlapping intervals of the
        # spike trains are correlated)
        cch_clipped, bin_ids_clipped = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='valid',
            binary=True)
        cch_unclipped, bin_ids_unclipped = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='valid',
            binary=False)
        cch_clipped_mem, bin_ids_clipped_mem = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='valid',
            binary=True, method='memory')
        cch_unclipped_mem, bin_ids_unclipped_mem = \
            sc.cross_correlation_histogram(
                self.binned_st1, self.binned_st2, window='valid',
                binary=False, method='memory')

        # Check consistency two methods
        assert_array_equal(
            np.squeeze(cch_clipped.magnitude), np.squeeze(
                cch_clipped_mem.magnitude))
        assert_array_equal(
            np.squeeze(cch_clipped.times), np.squeeze(
                cch_clipped_mem.times))
        assert_array_equal(
            np.squeeze(cch_unclipped.magnitude), np.squeeze(
                cch_unclipped_mem.magnitude))
        assert_array_equal(
            np.squeeze(cch_unclipped.times), np.squeeze(
                cch_unclipped_mem.times))
        assert_array_equal(bin_ids_clipped, bin_ids_clipped_mem)
        assert_array_equal(bin_ids_unclipped, bin_ids_unclipped_mem)

        # Check normal correlation Note: Use numpy correlate to verify result.
        # Note: numpy conventions for input array 1 and input array 2 are
        # swapped compared to Elephant!
        mat1 = self.binned_st1.to_array()[0]
        mat2 = self.binned_st2.to_array()[0]
        target_numpy = np.correlate(mat2, mat1, mode='valid')
        assert_array_equal(
            target_numpy, np.squeeze(cch_unclipped.magnitude))

        # Check correlation using binary spike trains
        mat1 = np.array(self.binned_st1.to_bool_array()[0], dtype=int)
        mat2 = np.array(self.binned_st2.to_bool_array()[0], dtype=int)
        target_numpy = np.correlate(mat2, mat1, mode='valid')
        assert_array_equal(
            target_numpy, np.squeeze(cch_clipped.magnitude))

        # Check the time axis and bin IDs of the resulting AnalogSignal
        assert_array_equal(
            (bin_ids_clipped - 0.5) * self.binned_st1.binsize,
            cch_unclipped.times)
        assert_array_equal(
            (bin_ids_clipped - 0.5) * self.binned_st1.binsize,
            cch_clipped.times)

        # Check for wrong window parameter setting
        self.assertRaises(
            KeyError, sc.cross_correlation_histogram, self.binned_st1,
            self.binned_st2, window='dsaij')
        self.assertRaises(
            KeyError, sc.cross_correlation_histogram, self.binned_st1,
            self.binned_st2, window='dsaij', method='memory')
Example #17
0
    connectionDictionary = connectionDict
    for i in range(len(neoDataset)):
        for j in range(len(neoDataset)):
            #if i != j:
            connectionDictionary[i][j] = connectionDictionary[i][j] + calcCCH(
                i, j, neoDataset)
    return connectionDictionary


#This code will produce a single cross correlogram
binned_st1 = BinnedSpikeTrain(neoDataset[0], binsize=1 * ms)
binned_st2 = BinnedSpikeTrain(neoDataset[5], binsize=1 * ms)

cch = cross_correlation_histogram(binned_st1,
                                  binned_st2,
                                  window=[-10, 10],
                                  border_correction=True,
                                  binary=True,
                                  kernel=None)
print(cch)
cchArray = cch[0][:, 0].magnitude.round()
cchArrayTime = cch[0].times.magnitude
cchArrayNP = np.array(cchArray)
print("argmax is:", cchArrayNP.max())

print(corrcoef(x, binary=True))

#calculate the cross-correlograms of the entire dataset,
#produce the corresponding correlation matrix
'''
print(calcCCH(8,9,neoDataset))
correlationArray = generateCorrelationMatrix(neoDataset)
Example #18
0
    def test_window(self):
        '''Test if the window parameter is correctly interpreted.'''
        cch_win, bin_ids = sc.cch(self.binned_st1,
                                  self.binned_st2,
                                  window=[-30, 30])
        cch_win_mem, bin_ids_mem = sc.cch(self.binned_st1,
                                          self.binned_st2,
                                          window=[-30, 30])

        assert_array_equal(bin_ids, np.arange(-30, 31, 1))
        assert_array_equal((bin_ids - 0.5) * self.binned_st1.binsize,
                           cch_win.times)

        assert_array_equal(bin_ids_mem, np.arange(-30, 31, 1))
        assert_array_equal((bin_ids_mem - 0.5) * self.binned_st1.binsize,
                           cch_win.times)

        assert_array_equal(cch_win, cch_win_mem)
        cch_unclipped, _ = sc.cross_correlation_histogram(self.binned_st1,
                                                          self.binned_st2,
                                                          window='full',
                                                          binary=False)
        assert_array_equal(cch_win, cch_unclipped[19:80])

        cch_win, bin_ids = sc.cch(self.binned_st1,
                                  self.binned_st2,
                                  window=[-25 * pq.ms, 25 * pq.ms])
        cch_win_mem, bin_ids_mem = sc.cch(self.binned_st1,
                                          self.binned_st2,
                                          window=[-25 * pq.ms, 25 * pq.ms],
                                          method='memory')

        assert_array_equal(bin_ids, np.arange(-25, 26, 1))
        assert_array_equal((bin_ids - 0.5) * self.binned_st1.binsize,
                           cch_win.times)

        assert_array_equal(bin_ids_mem, np.arange(-25, 26, 1))
        assert_array_equal((bin_ids_mem - 0.5) * self.binned_st1.binsize,
                           cch_win.times)

        assert_array_equal(cch_win, cch_win_mem)

        _, bin_ids = sc.cch(self.binned_st1, self.binned_st2, window=[20, 30])
        _, bin_ids_mem = sc.cch(self.binned_st1,
                                self.binned_st2,
                                window=[20, 30],
                                method='memory')

        assert_array_equal(bin_ids, np.arange(20, 31, 1))
        assert_array_equal(bin_ids_mem, np.arange(20, 31, 1))

        _, bin_ids = sc.cch(self.binned_st1,
                            self.binned_st2,
                            window=[-30, -20])

        _, bin_ids_mem = sc.cch(self.binned_st1,
                                self.binned_st2,
                                window=[-30, -20],
                                method='memory')

        assert_array_equal(bin_ids, np.arange(-30, -19, 1))
        assert_array_equal(bin_ids_mem, np.arange(-30, -19, 1))

        # Cehck for wrong assignments to the window parameter
        self.assertRaises(ValueError,
                          sc.cross_correlation_histogram,
                          self.binned_st1,
                          self.binned_st2,
                          window=[-60, 50])
        self.assertRaises(ValueError,
                          sc.cross_correlation_histogram,
                          self.binned_st1,
                          self.binned_st2,
                          window=[-60, 50],
                          method='memory')

        self.assertRaises(ValueError,
                          sc.cross_correlation_histogram,
                          self.binned_st1,
                          self.binned_st2,
                          window=[-50, 60])
        self.assertRaises(ValueError,
                          sc.cross_correlation_histogram,
                          self.binned_st1,
                          self.binned_st2,
                          window=[-50, 60],
                          method='memory')

        self.assertRaises(ValueError,
                          sc.cross_correlation_histogram,
                          self.binned_st1,
                          self.binned_st2,
                          window=[-25.5 * pq.ms, 25 * pq.ms])
        self.assertRaises(ValueError,
                          sc.cross_correlation_histogram,
                          self.binned_st1,
                          self.binned_st2,
                          window=[-25.5 * pq.ms, 25 * pq.ms],
                          method='memory')

        self.assertRaises(ValueError,
                          sc.cross_correlation_histogram,
                          self.binned_st1,
                          self.binned_st2,
                          window=[-25 * pq.ms, 25.5 * pq.ms])
        self.assertRaises(ValueError,
                          sc.cross_correlation_histogram,
                          self.binned_st1,
                          self.binned_st2,
                          window=[-25 * pq.ms, 25.5 * pq.ms],
                          method='memory')

        self.assertRaises(ValueError,
                          sc.cross_correlation_histogram,
                          self.binned_st1,
                          self.binned_st2,
                          window=[-60 * pq.ms, 50 * pq.ms])
        self.assertRaises(ValueError,
                          sc.cross_correlation_histogram,
                          self.binned_st1,
                          self.binned_st2,
                          window=[-60 * pq.ms, 50 * pq.ms],
                          method='memory')

        self.assertRaises(ValueError,
                          sc.cross_correlation_histogram,
                          self.binned_st1,
                          self.binned_st2,
                          window=[-50 * pq.ms, 60 * pq.ms])
        self.assertRaises(ValueError,
                          sc.cross_correlation_histogram,
                          self.binned_st1,
                          self.binned_st2,
                          window=[-50 * pq.ms, 60 * pq.ms],
                          method='memory')
    def test_cross_correlation_histogram(self):
        '''
        Test generic result of a cross-correlation histogram between two binned
        spike trains.
        '''
        # Calculate CCH using Elephant (normal and binary version) with
        # mode equal to 'full' (whole spike trains are correlated)
        cch_clipped, bin_ids_clipped = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='full',
            binary=True)
        cch_unclipped, bin_ids_unclipped = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='full', binary=False)

        cch_clipped_mem, bin_ids_clipped_mem = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='full',
            binary=True, method='memory')
        cch_unclipped_mem, bin_ids_unclipped_mem = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='full',
            binary=False, method='memory')
        # Check consistency two methods
        assert_array_equal(
            np.squeeze(cch_clipped.magnitude), np.squeeze(
                cch_clipped_mem.magnitude))
        assert_array_equal(
            np.squeeze(cch_clipped.times), np.squeeze(
                cch_clipped_mem.times))
        assert_array_equal(
            np.squeeze(cch_unclipped.magnitude), np.squeeze(
                cch_unclipped_mem.magnitude))
        assert_array_equal(
            np.squeeze(cch_unclipped.times), np.squeeze(
                cch_unclipped_mem.times))
        assert_array_almost_equal(bin_ids_clipped, bin_ids_clipped_mem)
        assert_array_almost_equal(bin_ids_unclipped, bin_ids_unclipped_mem)

        # Check normal correlation Note: Use numpy correlate to verify result.
        # Note: numpy conventions for input array 1 and input array 2 are
        # swapped compared to Elephant!
        mat1 = self.binned_st1.to_array()[0]
        mat2 = self.binned_st2.to_array()[0]
        target_numpy = np.correlate(mat2, mat1, mode='full')
        assert_array_equal(
            target_numpy, np.squeeze(cch_unclipped.magnitude))


        # Check cross correlation function for several displacements tau
        # Note: Use Elephant corrcoeff to verify result 
        tau = [-25.0, 0.0, 13.0] # in ms
        for t in tau:
            # adjust t_start, t_stop to shift by tau
            t0 = np.min([self.st_1.t_start+t*pq.ms, self.st_2.t_start])
            t1 = np.max([self.st_1.t_stop+t*pq.ms, self.st_2.t_stop])            
            st1 = neo.SpikeTrain(self.st_1.magnitude+t, units='ms',
                                t_start = t0*pq.ms, t_stop = t1*pq.ms)           
            st2 = neo.SpikeTrain(self.st_2.magnitude, units='ms',
                                t_start = t0*pq.ms, t_stop = t1*pq.ms)              
            binned_sts = conv.BinnedSpikeTrain([st1, st2],
                                               binsize=1*pq.ms,
                                               t_start = t0*pq.ms,
                                               t_stop = t1*pq.ms)
            # caluclate corrcoef
            corrcoef = sc.corrcoef(binned_sts)[1,0]    
            
            # expand t_stop to have two spike trains with same length as st1, st2
            st1 = neo.SpikeTrain(self.st_1.magnitude, units='ms',
                                t_start = self.st_1.t_start, 
                                t_stop = self.st_1.t_stop+np.abs(t)*pq.ms)           
            st2 = neo.SpikeTrain(self.st_2.magnitude, units='ms',
                                t_start = self.st_2.t_start, 
                                t_stop = self.st_2.t_stop+np.abs(t)*pq.ms)
            binned_st1 = conv.BinnedSpikeTrain(
                st1, t_start=0*pq.ms, t_stop=(50+np.abs(t))*pq.ms,
                binsize=1 * pq.ms)
            binned_st2 = conv.BinnedSpikeTrain(
                st2, t_start=0 * pq.ms, t_stop=(50+np.abs(t))*pq.ms,
                binsize=1 * pq.ms)
            # calculate CCHcoef and take value at t=tau
            CCHcoef, _  = sc.cch(binned_st1, binned_st2, 
                               cross_corr_coef=True)
            l = - binned_st1.num_bins + 1
            tau_bin = int(t/float(binned_st1.binsize.magnitude))
            assert_array_equal(corrcoef, CCHcoef[tau_bin-l].magnitude)
            

        # Check correlation using binary spike trains
        mat1 = np.array(self.binned_st1.to_bool_array()[0], dtype=int)
        mat2 = np.array(self.binned_st2.to_bool_array()[0], dtype=int)
        target_numpy = np.correlate(mat2, mat1, mode='full')
        assert_array_equal(
            target_numpy, np.squeeze(cch_clipped.magnitude))

        # Check the time axis and bin IDs of the resulting AnalogSignal
        assert_array_almost_equal(
            (bin_ids_clipped - 0.5) * self.binned_st1.binsize,
            cch_unclipped.times)
        assert_array_almost_equal(
            (bin_ids_clipped - 0.5) * self.binned_st1.binsize,
            cch_clipped.times)

        # Calculate CCH using Elephant (normal and binary version) with
        # mode equal to 'valid' (only completely overlapping intervals of the
        # spike trains are correlated)
        cch_clipped, bin_ids_clipped = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='valid',
            binary=True)
        cch_unclipped, bin_ids_unclipped = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='valid',
            binary=False)
        cch_clipped_mem, bin_ids_clipped_mem = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='valid',
            binary=True, method='memory')
        cch_unclipped_mem, bin_ids_unclipped_mem = sc.cross_correlation_histogram(
            self.binned_st1, self.binned_st2, window='valid',
            binary=False, method='memory')

        # Check consistency two methods
        assert_array_equal(
            np.squeeze(cch_clipped.magnitude), np.squeeze(
                cch_clipped_mem.magnitude))
        assert_array_equal(
            np.squeeze(cch_clipped.times), np.squeeze(
                cch_clipped_mem.times))
        assert_array_equal(
            np.squeeze(cch_unclipped.magnitude), np.squeeze(
                cch_unclipped_mem.magnitude))
        assert_array_equal(
            np.squeeze(cch_unclipped.times), np.squeeze(
                cch_unclipped_mem.times))
        assert_array_equal(bin_ids_clipped, bin_ids_clipped_mem)
        assert_array_equal(bin_ids_unclipped, bin_ids_unclipped_mem)

        # Check normal correlation Note: Use numpy correlate to verify result.
        # Note: numpy conventions for input array 1 and input array 2 are
        # swapped compared to Elephant!
        mat1 = self.binned_st1.to_array()[0]
        mat2 = self.binned_st2.to_array()[0]
        target_numpy = np.correlate(mat2, mat1, mode='valid')
        assert_array_equal(
            target_numpy, np.squeeze(cch_unclipped.magnitude))

        # Check correlation using binary spike trains
        mat1 = np.array(self.binned_st1.to_bool_array()[0], dtype=int)
        mat2 = np.array(self.binned_st2.to_bool_array()[0], dtype=int)
        target_numpy = np.correlate(mat2, mat1, mode='valid')
        assert_array_equal(
            target_numpy, np.squeeze(cch_clipped.magnitude))

        # Check the time axis and bin IDs of the resulting AnalogSignal
        assert_array_equal(
            (bin_ids_clipped - 0.5) * self.binned_st1.binsize,
            cch_unclipped.times)
        assert_array_equal(
            (bin_ids_clipped - 0.5) * self.binned_st1.binsize,
            cch_clipped.times)

        # Check for wrong window parameter setting
        self.assertRaises(
            KeyError, sc.cross_correlation_histogram, self.binned_st1,
            self.binned_st2, window='dsaij')
        self.assertRaises(
            KeyError, sc.cross_correlation_histogram, self.binned_st1,
            self.binned_st2, window='dsaij', method='memory')