def setUp(self):
        # These two arrays must be such that they do not have coincidences
        # spanning across two neighbor bins assuming ms bins [0,1),[1,2),...
        self.test_array_1d_0 = [
            1.3, 7.56, 15.87, 28.23, 30.9, 34.2, 38.2, 43.2
        ]
        self.test_array_1d_1 = [1.02, 2.71, 18.82, 28.46, 28.79, 43.6]

        # Build spike trains
        self.st_0 = neo.SpikeTrain(self.test_array_1d_0,
                                   units='ms',
                                   t_stop=50.)
        self.st_1 = neo.SpikeTrain(self.test_array_1d_1,
                                   units='ms',
                                   t_stop=50.)

        # And binned counterparts
        self.binned_st = conv.BinnedSpikeTrain([self.st_0, self.st_1],
                                               t_start=0 * pq.ms,
                                               t_stop=50. * pq.ms,
                                               binsize=1 * pq.ms)
Beispiel #2
0
def _new_spiketrain_v1(cls,
                       signal,
                       t_stop,
                       units=None,
                       dtype=None,
                       copy=True,
                       sampling_rate=1.0 * pq.Hz,
                       t_start=0.0 * pq.s,
                       waveforms=None,
                       left_sweep=None,
                       name=None,
                       file_origin=None,
                       description=None,
                       array_annotations=None,
                       annotations=None,
                       segment=None,
                       unit=None):
    '''
    A function to map :meth:`BaseAnalogSignal.__new__` to function that
    does not do the unit checking. This is needed for :module:`pickle` to work.
    '''
    if annotations is None:
        annotations = {}

    if isinstance(array_annotations,
                  dict):  # these in fact are the annotations in the old API
        annotations = array_annotations

        obj = neo.SpikeTrain(signal, t_stop, units, dtype, copy, sampling_rate,
                             t_start, waveforms, left_sweep, name, file_origin,
                             description, **annotations)

    else:
        obj = neo.SpikeTrain(signal, t_stop, units, dtype, copy, sampling_rate,
                             t_start, waveforms, left_sweep, name, file_origin,
                             description, array_annotations, **annotations)

    obj.segment = segment
    obj.unit = unit
    return obj
 def test_spade_raise_error(self):
     self.assertRaises(TypeError, spade.spade, [[1, 2, 3], [3, 4, 5]],
                       1 * pq.ms, 4)
     self.assertRaises(AttributeError, spade.spade, [
         neo.SpikeTrain([1, 2, 3] * pq.s, t_stop=5 * pq.s),
         neo.SpikeTrain([3, 4, 5] * pq.s, t_stop=6 * pq.s)
     ], 1 * pq.ms, 4)
     self.assertRaises(
         AttributeError,
         spade.spade, [
             neo.SpikeTrain([1, 2, 3] * pq.s, t_stop=5 * pq.s),
             neo.SpikeTrain([3, 4, 5] * pq.s, t_stop=5 * pq.s)
         ],
         1 * pq.ms,
         4,
         min_neu=-3)
     self.assertRaises(
         AttributeError,
         spade.pvalue_spectrum, [
             neo.SpikeTrain([1, 2, 3] * pq.s, t_stop=5 * pq.s),
             neo.SpikeTrain([3, 4, 5] * pq.s, t_stop=5 * pq.s)
         ],
         1 * pq.ms,
         4,
         3 * pq.ms,
         n_surr=-3)
     self.assertRaises(AttributeError,
                       spade.test_signature_significance,
                       ((2, 3, 0.2), (2, 4, 0.1)),
                       0.01,
                       corr='try')
     self.assertRaises(AttributeError,
                       spade.approximate_stability, (),
                       np.array([]),
                       n_subsets=-3)
    def write_sorting(sorting,
                      save_path,
                      sampling_frequency,
                      check_suffix=True):
        '''
        Save sorting extractor to MEArec format.
        Parameters
        ----------
        sorting: SortingExtractor
            Sorting extractor object to be saved
        save_path: str
            .h5 or .hdf5 path
        sampling_frequency: int
            Sampling frequency in Hz

        '''
        assert HAVE_MREX, "To use the MEArec extractors, install MEArec: \n\n pip install MEArec\n\n"
        save_path = Path(save_path)
        if save_path.is_dir():
            print(
                "The file will be saved as sorting.h5 in the provided folder")
            save_path = save_path / 'sorting.h5'
        if (save_path.suffix == '.h5'
                or save_path.suffix == '.hdf5') or (not check_suffix):
            # create neo spike trains
            spiketrains = []
            for u in sorting.get_unit_ids():
                st = neo.SpikeTrain(times=sorting.get_unit_spike_train(u) /
                                    float(sampling_frequency) * pq.s,
                                    t_start=np.min(
                                        sorting.get_unit_spike_train(u) /
                                        float(sampling_frequency)) * pq.s,
                                    t_stop=np.max(
                                        sorting.get_unit_spike_train(u) /
                                        float(sampling_frequency)) * pq.s)
                st.annotate(unit_id=u)
                spiketrains.append(st)

            duration = np.max([st.t_stop.magnitude for st in spiketrains])
            info = {
                'recordings': {
                    'fs': sampling_frequency
                },
                'spiketrains': {
                    'duration': duration
                }
            }
            rec_dict = {'spiketrains': spiketrains}
            recgen = mr.RecordingGenerator(rec_dict=rec_dict, info=info)
            mr.save_recording_generator(recgen, str(save_path), verbose=False)
        else:
            raise Exception("Provide a folder or an .h5/.hdf5 as 'save_path'")
Beispiel #5
0
    def create_hierarchy(cls, many_to_many):
        b = neo.Block()

        for ns in range(cls.SEGMENTS):
            b.segments.append(neo.Segment())

        channels = []
        if many_to_many:
            channels = [
                neo.RecordingChannel(name='Shared %d' % i,
                                     index=i + cls.CHANNELS)
                for i in range(cls.CHANNELS / 2)
            ]

        for ng in range(cls.CHANNEL_GROUPS):
            rcg = neo.RecordingChannelGroup()
            for nu in range(cls.UNITS):
                unit = neo.Unit()
                for ns in range(cls.SEGMENTS):
                    spike = neo.Spike(0 * pq.s)
                    unit.spikes.append(spike)
                    b.segments[ns].spikes.append(spike)

                    st = neo.SpikeTrain([] * pq.s, 0 * pq.s)
                    unit.spiketrains.append(st)
                    b.segments[ns].spiketrains.append(st)

                rcg.units.append(unit)

            if not many_to_many:
                for nc in range(cls.CHANNELS):
                    rc = neo.RecordingChannel(name='Single %d' % nc, index=nc)
                    rc.recordingchannelgroups.append(rcg)
                    rcg.recordingchannels.append(rc)
            else:
                for nc in range(cls.CHANNELS):
                    if nc % 2 == 0:
                        rc = neo.RecordingChannel(name='Single %d' % (nc / 2),
                                                  index=nc / 2)
                    else:
                        rc = channels[nc / 2]
                    rc.recordingchannelgroups.append(rcg)
                    rcg.recordingchannels.append(rc)
            rcg.channel_indexes = sp.array(
                [c.index for c in rcg.recordingchannels])
            rcg.channel_names = sp.array(
                [c.name for c in rcg.recordingchannels])

            b.recordingchannelgroups.append(rcg)

        neo.io.tools.create_many_to_one_relationship(b)
        return b
Beispiel #6
0
 def test_bins_spike_train_using_its_properties(self):
     a = neo.SpikeTrain(sp.array([1000.0]) * pq.ms,
                        t_start=500.0 * pq.ms,
                        t_stop=1500.0 * pq.ms)
     sampling_rate = 4.0 * pq.Hz
     expected = {0: [sp.array([0, 0, 1, 0])]}
     expectedBins = sp.array([0.5, 0.75, 1.0, 1.25, 1.5]) * pq.s
     actual, actualBins = tools.bin_spike_trains({0: [a]}, sampling_rate)
     self.assertEqual(len(expected), len(actual))
     self.assertEqual(len(expected[0]), len(actual[0]))
     assert_array_equal(expected[0][0], actual[0][0])
     assert_array_almost_equal(expectedBins,
                               actualBins.rescale(expectedBins.units))
Beispiel #7
0
    def test_bin_shuffling_empty_train(self):

        self.bin_size = 3 * pq.ms
        self.max_displacement = 10
        empty_spiketrain = neo.SpikeTrain([] * pq.ms, t_stop=500 * pq.ms)

        binned_spiketrain = conv.BinnedSpikeTrain(empty_spiketrain,
                                                  self.bin_size)
        surrogate_train = surr.bin_shuffling(
            binned_spiketrain,
            max_displacement=self.max_displacement,
            n_surrogates=1)[0]
        self.assertEqual(np.sum(surrogate_train.to_bool_array()), 0)
def test_concatenate_spiketrains():
    from exana.misc import concatenate_spiketrains
    spiketrain1 = neo.SpikeTrain(times=np.arange(10),
                                 t_stop=10, units='s',
                                 waveforms=np.ones((10,1,5)) * pq.V)
    spiketrain2 = neo.SpikeTrain(times=np.arange(10, 25),
                                 t_stop=25, units='s',
                                 waveforms=np.ones((15,1,5)) * pq.V)
    spiketrain = concatenate_spiketrains([spiketrain1, spiketrain2])
    spiketrain_true = np.concatenate((np.arange(10), np.arange(10, 25)))
    waveforms_true = np.concatenate((np.ones((10,1,5)), np.ones((15,1,5))))
    assert np.array_equal(spiketrain.times.magnitude, spiketrain_true)
    assert spiketrain.times.units == pq.s.units
    assert np.array_equal(spiketrain.waveforms.magnitude, waveforms_true)
    assert spiketrain.waveforms.units == pq.V
    assert spiketrain.t_stop == 25 * pq.s

    with pytest.raises(ValueError):
        spiketrain2 = neo.SpikeTrain(times=np.arange(10, 25),
                                     t_stop=25, units='ms',
                                     waveforms=np.ones((15,1,5)) * pq.V)
        spiketrain = concatenate_spiketrains([spiketrain1, spiketrain2])
Beispiel #9
0
    def test_dither_spike_train_false_edges(self):

        spiketrain = neo.SpikeTrain(
            [90, 150, 180, 350] * pq.ms, t_stop=500 * pq.ms)

        n_surrogates = 2
        shift = 10 * pq.ms
        surrogate_trains = surr.dither_spike_train(
            spiketrain, shift=shift, n_surrogates=n_surrogates, edges=False)

        for surrogate_train in surrogate_trains:
            for i in range(len(surrogate_train)):
                self.assertLessEqual(surrogate_train[i], spiketrain.t_stop)
Beispiel #10
0
    def test_jitter_spikes_unequal_binsize(self):

        st = neo.SpikeTrain([90, 150, 180, 480] * pq.ms, t_stop=500 * pq.ms)

        binsize = 75 * pq.ms
        surrog = surr.jitter_spikes(st, binsize=binsize, n=1)[0]

        bin_ids_orig = np.array((st.view(pq.Quantity) / binsize).rescale(
            pq.dimensionless).magnitude, dtype=int)
        bin_ids_surr = np.array((surrog.view(pq.Quantity) / binsize).rescale(
            pq.dimensionless).magnitude, dtype=int)

        self.assertTrue(np.all(bin_ids_orig == bin_ids_surr))
Beispiel #11
0
    def test_binned_spiketrain_neg_times_list(self):
        a = neo.SpikeTrain(
            [-6.5, 0.5, 0.7, 1.2, 3.1, 4.3, 5.5, 6.7] * pq.s,
            t_start=-7 * pq.s, t_stop=7 * pq.s)
        b = neo.SpikeTrain(
            [-0.1, -0.7, 1.2, 2.2, 4.3, 5.5, 8.0] * pq.s,
            t_start=-1 * pq.s, t_stop=8 * pq.s)
        spiketrains = [a, b]

        # not the same t_start and t_stop
        self.assertRaises(ValueError, cv.BinnedSpikeTrain,
                          spiketrains=spiketrains,
                          bin_size=self.bin_size)
        t_start, t_stop = get_common_start_stop_times(spiketrains)
        self.assertEqual(t_start, -1 * pq.s)
        self.assertEqual(t_stop, 7 * pq.s)
        x_bool = cv.BinnedSpikeTrain(spiketrains, bin_size=self.bin_size,
                                     t_start=t_start, t_stop=t_stop)
        y_bool = [[0, 1, 1, 0, 1, 1, 1, 1],
                  [1, 0, 1, 1, 0, 1, 1, 0]]

        assert_array_equal(x_bool.to_bool_array(), y_bool)
Beispiel #12
0
def input_freq(port_name, freq, duration, weight, offset=None):
    freq = pq.Quantity(freq, 'kHz')
    duration = pq.Quantity(duration, 'ms')
    isi = 1 / freq
    if offset is None:
        offset = isi
    else:
        offset = pq.Quantity(offset, 'ms')
    train = neo.SpikeTrain(numpy.arange(offset, duration, isi),
                           units='ms',
                           t_stop=duration,
                           t_start=offset)
    return (port_name, train, weight)
Beispiel #13
0
    def test_extract(self):

        # test synchrofact search taking into account adjacent bins
        # this requires an additional loop with shifted binning

        sampling_rate = 1 / pq.s

        spiketrains = [
            neo.SpikeTrain([1, 5, 9, 11, 13, 20] * pq.s, t_stop=21 * pq.s),
            neo.SpikeTrain([1, 4, 7, 12, 16, 18] * pq.s, t_stop=21 * pq.s)
        ]

        correct_annotations = np.array([[2, 2, 1, 3, 3, 1], [2, 2, 1, 3, 1,
                                                             1]])

        self._test_template(spiketrains,
                            correct_annotations,
                            sampling_rate,
                            spread=1,
                            mode='extract',
                            in_place=True,
                            deletion_threshold=2)
Beispiel #14
0
    def test_consistency_errors(self):
        a = self.spiketrain_a
        b = neo.SpikeTrain([-2, -1] * pq.s,
                           t_start=-2 * pq.s,
                           t_stop=-1 * pq.s)
        self.assertRaises(ValueError,
                          cv.BinnedSpikeTrain, [a, b],
                          t_start=5,
                          t_stop=0,
                          binsize=pq.s,
                          num_bins=10)

        b = neo.SpikeTrain([-7, -8, -9] * pq.s,
                           t_start=-9 * pq.s,
                           t_stop=-7 * pq.s)
        self.assertRaises(ValueError,
                          cv.BinnedSpikeTrain,
                          b,
                          t_start=0,
                          t_stop=10,
                          binsize=pq.s,
                          num_bins=10)
        self.assertRaises(ValueError,
                          cv.BinnedSpikeTrain,
                          a,
                          t_start=0 * pq.s,
                          t_stop=10 * pq.s,
                          binsize=3 * pq.s,
                          num_bins=10)

        b = neo.SpikeTrain([-4, -2, 0, 1] * pq.s,
                           t_start=-4 * pq.s,
                           t_stop=1 * pq.s)
        self.assertRaises(TypeError,
                          cv.BinnedSpikeTrain,
                          b,
                          binsize=-2 * pq.s,
                          t_start=-4 * pq.s,
                          t_stop=0 * pq.s)
Beispiel #15
0
 def test_integration(self):
     """
     The test is written according to the notebook (for developers only):
     https://github.com/INM-6/elephant-tutorials/blob/master/
     simple_test_asset.ipynb
     """
     # define parameters
     np.random.seed(1)
     size_group = 3
     size_sse = 3
     T = 60 * pq.ms
     delay = 9 * pq.ms
     bins_between_sses = 3
     time_between_sses = 9 * pq.ms
     # ground truth for pmats
     starting_bin_1 = int((delay / self.bin_size).magnitude.item())
     starting_bin_2 = int(
         (2 * delay / self.bin_size + time_between_sses / self.bin_size
          ).magnitude.item())
     indices_pmat_1 = np.arange(starting_bin_1, starting_bin_1 + size_sse)
     indices_pmat_2 = np.arange(starting_bin_2,
                                starting_bin_2 + size_sse)
     indices_pmat = (np.concatenate((indices_pmat_1, indices_pmat_2)),
                     np.concatenate((indices_pmat_2, indices_pmat_1)))
     # generate spike trains
     spiketrains = [neo.SpikeTrain([index_spiketrain,
                                    index_spiketrain +
                                    size_sse +
                                    bins_between_sses] * self.bin_size
                                   + delay + 1 * pq.ms,
                                   t_stop=T)
                    for index_group in range(size_group)
                    for index_spiketrain in range(size_sse)]
     index_proba = {
         "high": (np.array([9, 9, 10, 10, 10, 11, 11]),
                  np.array([3, 4, 3, 4, 5, 4, 5])),
         "medium": (np.array([8, 8, 9, 9, 9, 10, 10,
                              10, 11, 11, 11, 12, 12]),
                    np.array([2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6, 5, 6])),
         "low": (np.array([7, 8, 8, 9, 9, 9, 10, 10, 10,
                           11, 11, 11, 12, 12, 12, 13, 13]),
                 np.array([2, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5,
                           6, 5, 6, 7, 6, 7]))
     }
     expected_sses = {1: {(9, 3): {0, 3, 6}, (10, 4): {1, 4, 7},
                          (11, 5): {2, 5, 8}}}
     self._test_integration_subtest(spiketrains,
                                    spiketrains_y=spiketrains,
                                    indices_pmat=indices_pmat,
                                    index_proba=index_proba,
                                    expected_sses=expected_sses)
Beispiel #16
0
def segment_from_recording_device(devices,
                                  variables_to_include,
                                  id_lists,
                                  t_stop,
                                  name="segment00"):
    """
    Extract data from a NEST recording device and return it as a Neo Segment object.    
    """
    def get_data(device, variable, id_list):
        events = nest.GetStatus(device, 'events')[0]
        ids = events['senders']
        values = events[variable]
        data = {}
        for id in id_list:
            data[id] = values[ids == id]
        assert len(data) > 0
        return data

    segment = neo.Segment(name=name, rec_datetime=datetime.now())

    for device, variable, id_list in zip(devices, variables_to_include,
                                         id_lists):
        print(name, device, variable)
        data = get_data(device, variable, id_list)
        if variable == 'times':
            print("  adding spiketrain")
            id0 = min(id_list)
            segment.spiketrains = [
                neo.SpikeTrain(spiketrain,
                               t_start=0.0,
                               t_stop=t_stop,
                               units='ms',
                               source_id=id,
                               source_index=id - id0)
                for id, spiketrain in data.items()
            ]
        else:
            print("  adding signal")
            source_ids = np.array(id_list)
            channel_indices = source_ids - source_ids.min()
            signal_array = np.vstack(data.values()).T
            segment.analogsignalarrays = [
                neo.AnalogSignalArray(signal_array,
                                      units='mV',
                                      t_start=0.0 * ms,
                                      sampling_period=0.1 * ms,
                                      name=variable,
                                      channel_index=channel_indices,
                                      source_ids=source_ids)
            ]
    return segment
def build_block(data_file):
    """(plaintextfile_path) -> neo.core.block.Block
    Thie function reads a plain text file (data_file) with the data exported (per waveform) from Plexon Offline Sorter after sorting and returns a neo.Block with spiketrains ordered in any number of 10 minute segments.

    For practicality and Plexon management of channels names, units and channels have been ignored in the block structure."""

    raw_data = pd.read_csv(data_file, sep=',', header=0, usecols=[0, 1, 2])
    ord_times = raw_data.groupby(['Channel Name', 'Unit'])['Timestamp']
    new_block = neo.Block()
    chx = neo.ChannelIndex(index=None, name='MEA_60')
    new_block.channel_indexes.append(chx)
    # Next line will not work properly if last spike happens
    # exactly at the end of the recording
    num_segments = range(int(raw_data['Timestamp'].max() // 600 + 1))
    for ind in num_segments:
        seg = neo.Segment(name='segment {}'.format(ind), index=ind)
        new_block.segments.append(seg)

    for name, group in ord_times:
        time_stamps = ord_times.get_group(name).values
        inter = 600  # Number of seconds in 10 minutes
        first_seg = neo.SpikeTrain(
            time_stamps[time_stamps < inter], units='sec', t_start=0,  t_stop=inter)
        new_block.segments[0].spiketrains.append(first_seg)
        new_unit = neo.Unit(name=name)
        sptrs = [first_seg]
        for seg in num_segments[1:-1]:
            seg_train = neo.SpikeTrain(time_stamps[(time_stamps > seg * inter) & (time_stamps < ((seg + 1) * inter))],
                                       units='sec', t_start=(seg * inter), t_stop=((seg + 1) * inter))
            new_block.segments[seg].spiketrains.append(seg_train)
            sptrs.append(seg_train)
        last_seg = neo.SpikeTrain(time_stamps[time_stamps > (num_segments[-1] * inter)], units='sec',
                                  t_start=(num_segments[-1]) * inter, t_stop=((num_segments[-1] + 1) * inter))
        new_block.segments[num_segments[-1]].spiketrains.append(last_seg)
        sptrs.append(last_seg)
        new_unit.spiketrains = sptrs
        chx.units.append(new_unit)
    return new_block
    def test_dither_spike_train_false_edges(self):

        st = neo.SpikeTrain([90, 150, 180, 350] * pq.ms, t_stop=500 * pq.ms)

        nr_surr = 2
        shift = 10 * pq.ms
        surrs = surr.dither_spike_train(st,
                                        shift=shift,
                                        n=nr_surr,
                                        edges=False)

        for surrog in surrs:
            for i in range(len(surrog)):
                self.assertLessEqual(surrog[i], st.t_stop)
Beispiel #19
0
    def test_dither_spike_train_output_decimals(self):
        st = neo.SpikeTrain([90, 150, 180, 350] * pq.ms, t_stop=500 * pq.ms)

        n_surrogates = 2
        shift = 10 * pq.ms
        surrogate_trains = surr.dither_spike_train(
            st, shift=shift, n_surrogates=n_surrogates, decimals=3)

        for surrogate_train in surrogate_trains:
            for i in range(len(surrogate_train)):
                self.assertNotEqual(surrogate_train[i] -
                                    int(surrogate_train[i]) *
                                    pq.ms, surrogate_train[i] -
                                    surrogate_train[i])
Beispiel #20
0
    def test_timescale_errors(self):
        spikes = neo.SpikeTrain([1, 5, 7, 8] * pq.ms, t_stop=10 * pq.ms)
        binsize = 1 * pq.ms
        spikes_bin = conv.BinnedSpikeTrain(spikes, binsize)

        # Tau max with no units
        tau_max = 1
        self.assertRaises(ValueError,
                          sc.spike_train_timescale, spikes_bin, tau_max)

        # Tau max that is not a multiple of the binsize
        tau_max = 1.1 * pq.ms
        self.assertRaises(ValueError,
                          sc.spike_train_timescale, spikes_bin, tau_max)
Beispiel #21
0
    def test_dither_spikes_false_edges(self):

        st = neo.SpikeTrain([90, 150, 180, 350] * pq.ms, t_stop=500 * pq.ms)

        n_surrogates = 2
        dither = 10 * pq.ms
        surrogate_trains = surr.dither_spikes(st,
                                              dither=dither,
                                              n_surrogates=n_surrogates,
                                              edges=False)

        for surrogate_train in surrogate_trains:
            for i in range(len(surrogate_train)):
                self.assertLessEqual(surrogate_train[i], st.t_stop)
Beispiel #22
0
    def test_filter_process_with_spiketrain_h05(self):
        st = neo.SpikeTrain(self.test_array, units='s', t_stop=2.1)
        target = self.targ_h05
        res = mft._filter_process(0.5 * pq.s, 0.5 * pq.s, st, 2.01 * pq.s,
                                  np.array([[0.5], [1.7], [0.4]]))
        assert_array_almost_equal(res[1], target[1], decimal=3)

        self.assertRaises(ValueError, mft._filter_process, 0.5, 0.5 * pq.s, st,
                          2.01 * pq.s, np.array([[0.5], [1.7], [0.4]]))
        self.assertRaises(ValueError, mft._filter_process, 0.5 * pq.s, 0.5, st,
                          2.01 * pq.s, np.array([[0.5], [1.7], [0.4]]))
        self.assertRaises(ValueError, mft._filter_process, 0.5 * pq.s,
                          0.5 * pq.s, self.test_array, 2.01 * pq.s,
                          np.array([[0.5], [1.7], [0.4]]))
Beispiel #23
0
    def test_trial_shuffling_empty_train_concatenated(self):

        empty_spiketrain = neo.SpikeTrain([] * pq.ms, t_stop=500 * pq.ms)
        trial_length = 200 * pq.ms
        trial_separation = 50 * pq.ms

        dither = 10 * pq.ms
        surrogate_train = surr._trial_shifting_of_concatenated_spiketrain(
            empty_spiketrain,
            dither=dither,
            n_surrogates=1,
            trial_length=trial_length,
            trial_separation=trial_separation)[0]
        self.assertEqual(len(surrogate_train), 0)
Beispiel #24
0
    def test_spread_0(self):

        # basic test with a minimum number of two spikes per synchrofact
        # only taking into account multiple spikes
        # within one bin of size 1 / sampling_rate

        sampling_rate = 1 / pq.s

        spiketrains = [
            neo.SpikeTrain([1, 5, 9, 11, 16, 19] * pq.s, t_stop=20 * pq.s),
            neo.SpikeTrain([1, 4, 8, 12, 16, 18] * pq.s, t_stop=20 * pq.s)
        ]

        correct_annotations = np.array([[2, 1, 1, 1, 2, 1], [2, 1, 1, 1, 2,
                                                             1]])

        self._test_template(spiketrains,
                            correct_annotations,
                            sampling_rate,
                            spread=0,
                            mode='delete',
                            in_place=True,
                            deletion_threshold=2)
Beispiel #25
0
    def test_randomise_spikes_output_decimals(self):
        spiketrain = neo.SpikeTrain([90, 150, 180, 350] * pq.ms,
                                    t_stop=500 * pq.ms)

        n_surrogates = 2
        surrogate_trains = surr.randomise_spikes(spiketrain,
                                                 n_surrogates=n_surrogates,
                                                 decimals=3)

        for surrogate_train in surrogate_trains:
            for i in range(len(surrogate_train)):
                self.assertNotEqual(
                    surrogate_train[i] - int(surrogate_train[i]) * pq.ms,
                    surrogate_train[i] - surrogate_train[i])
    def test_spiketrains_findable(self):

        # same test as `test_spread_0` with the addition of
        # a neo structure: we must not overwrite the spiketrain
        # list of the segment before determining the index

        sampling_rate = 1 / pq.s

        segment = neo.Segment()

        segment.spiketrains = [neo.SpikeTrain([1, 5, 9, 11, 16, 19] * pq.s,
                                              t_stop=20*pq.s),
                               neo.SpikeTrain([1, 4, 8, 12, 16, 18] * pq.s,
                                              t_stop=20*pq.s)]

        segment.create_relationship()

        correct_annotations = np.array([[2, 1, 1, 1, 2, 1],
                                        [2, 1, 1, 1, 2, 1]])

        self._test_template(segment.spiketrains, correct_annotations,
                            sampling_rate, spread=0, mode='delete',
                            in_place=True, deletion_threshold=2)
Beispiel #27
0
    def test_binarize_with_spiketrain_round(self):
        st = neo.SpikeTrain(self.test_array_1d,
                            units='ms',
                            t_stop=10.0,
                            sampling_rate=10.0)
        times = np.arange(0, 10. + .1, .1)
        target = np.zeros_like(times).astype('bool')
        for time in np.round(self.test_array_1d, 1):
            target[get_nearest(times, time)] = True
        times = pq.Quantity(times, units='ms')

        res, tres = cv.binarize(st, return_times=True)
        assert_array_almost_equal(res, target, decimal=9)
        assert_array_almost_equal(tres, times, decimal=9)
Beispiel #28
0
def multiTag2SpikeTrain(tag, tStart, tStop):
    '''
    Create a neo.spiketrain from nix.multitag
    :param tag: nix.multitag
    :param tStart: float, time of start of the spike train in units of the multitag
    :param tStop: float, time of stop of the spike train in units of the multitag
    :return: neo.spiketrain
    '''

    sp = neo.SpikeTrain(times=[], t_start=tStart, t_stop=tStop, units=qu.s)

    if len(tag.positions):
        spikeTimes = np.array(tag.positions) * qu.Quantity(1, tag.units[0])

        spikeTimesFiltered = spikeTimes[np.logical_and(spikeTimes > tStart,
                                                       spikeTimes < tStop)]

        if spikeTimesFiltered.shape[0]:
            sp = neo.SpikeTrain(times=spikeTimesFiltered.magnitude,
                                t_start=tStart,
                                t_stop=tStop,
                                units=tag.units[0])
    return sp
Beispiel #29
0
 def test_trains(self):
     trains = {}
     trains[0] = neo.SpikeTrain(
         sp.zeros(2) * pq.ms,
         0 * pq.ms,
         waveforms=[[[-1, -2], [1, 2]], [[-1, -2], [1, 2]]] * pq.mV)
     trains[1] = trains[0]
     means = {}
     means[1] = neo.Spike(0 * pq.ms, waveform=[[-1, -1], [1, 1]] * pq.mV)
     exp = qa.variance_explained(trains, means)
     self.assertAlmostEqual(exp[0][0], 1)
     self.assertAlmostEqual(exp[0][0], 1)
     self.assertAlmostEqual(exp[1][0], 1)
     self.assertAlmostEqual(exp[1][1], 0.75)
Beispiel #30
0
def concatenate_spike_trains(trains):
    """ Concatenates spike trains.

    :param sequence trains: :class:`neo.core.SpikeTrain` objects to
        concatenate.
    :returns: A spike train consisting of the concatenated spike trains. The
        spikes will be in the order of the given spike trains and ``t_start``
        and ``t_stop`` will be set to the minimum and maximum value.
    :rtype: :class:`neo.core.SpikeTrain`
    """

    t_start, t_stop = maximum_spike_train_interval({0: trains})
    return neo.SpikeTrain(
        spq.concatenate([train.view(type=pq.Quantity) for train in trains]),
        t_start=t_start, t_stop=t_stop)