示例#1
0
def test_select_trains():

    trains = th.make_trains(
        [[1], [2], [3], [4]],
        duration=4,
        cfs=[0,0,1,1],
        idx=[0,1,0,1]
    )



    selected = th.select_trains(
        trains,
        cfs=1,
        idx=1
    )

    expected = th.make_trains(
        [[4]],
        duration=4,
        cfs=[1],
        idx=[1]
    )
    expected.index = [3]

    assert_frame_equal(
        selected,
        expected,
    )
示例#2
0
def test_psth_with_empty_trains():
    trains = th.make_trains(
        [[], []]
    )
    psth, bin_edges = th.psth(
        trains,
        bin_size=1,
        normalize=False
    )


    assert psth is None
    assert bin_edges is None


    ### duration != 0
    trains = th.make_trains(
        [[], []],
        duration=2
    )
    psth, bin_edges = th.psth(
        trains,
        bin_size=1,
        normalize=False
    )

    assert_equal(
        psth,
        [0,0]
    )
    assert_equal(
        bin_edges,
        [0,1,2]
    )
示例#3
0
def test_entrainment():

    trains = th.make_trains(
        [[1, 2, 3], [0, 2, 4]]
    )

    ent = th.entrainment(
        trains,
        freq=1,
        bin_size=0.1
    )

    assert_equal(ent, 0.5)




    ### NaN test
    trains = th.make_trains(
        [[1], []]
    )

    ent = th.entrainment(
        trains,
        freq=1,
        bin_size=0.1
    )

    assert np.isnan(ent)
示例#4
0
def test_trim():

    trains = th.make_trains([[1, 2], [2, 3]], duration=10, cf=1e3)

    trimmed = th.trim(trains, 1.5, 2.5)

    expected = th.make_trains([[0.5], [0.5]], duration=1, cf=1e3)

    assert_frame_equal(trimmed, expected)
示例#5
0
def test_trim_without_stop():

    trains = th.make_trains([[1, 2], [2, 3]], duration=10, cf=1e3)

    trimmed = th.trim(trains, 2)

    expected = th.make_trains([[0], [0, 1]], duration=8, cf=1e3)

    assert_frame_equal(trimmed, expected)
示例#6
0
def test_accumulate():

    trains = th.make_trains([[1], [2], [3], []], cfs=[2, 1, 2, 3])

    accumulated = th.accumulate(trains)

    expected = th.make_trains([[2], [1, 3], []], cfs=[1, 2, 3])

    assert_frame_equal(accumulated, expected)
示例#7
0
def test_from_array():

    fs = 1e3
    a = np.array([[0, 0, 0, 1, 0, 0], [0, 2, 1, 0, 0, 0]]).T

    result = th.make_trains(a, fs=fs)

    expected = th.make_trains(
        [np.array([3]) / fs, np.array([1, 1, 2]) / fs], duration=6 / fs)

    assert_frame_equal(expected, result)
示例#8
0
def test_trim():

    trains = th.make_trains([[1, 2, 3, 4], [3, 4, 5, 6]],
                            duration=8,
                            type='hsr')

    trimmed = th.trim(trains, 2, 4)

    expected = th.make_trains([[0, 1, 2], [1, 2]], duration=2, type='hsr')

    assert_frame_equal(trimmed, expected)
示例#9
0
def test_fold():
    trains = th.make_trains([[1.1, 2.1, 3.1], [2.1, 3.1, 5.1]],
                            duration=6.5,
                            cf=[1, 2])

    folded = th.fold(trains, 1)

    expected = th.make_trains(
        [[], [.1], [.1], [.1], [], [], [], [], [], [.1], [.1], [], [.1], []],
        duration=[1, 1, 1, 1, 1, 1, 0.5, 1, 1, 1, 1, 1, 1, 0.5],
        cf=[1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2])

    assert_frame_equal(
        folded,
        expected,
    )
示例#10
0
def main():

    fs = 10e3  # Hz
    freq = 10  # Hz

    ### Calculate spike probability over time (we want to have a
    ### periodic function for a pretty plot)
    t = np.arange(0, 1, 1 / fs)
    spike_probability = 0.2 * np.abs(np.sin(2 * np.pi * freq * t))
    rand = np.random.rand(len(spike_probability))

    ### Generate spike trains
    spike_array = np.zeros_like(spike_probability)
    spike_array[rand < spike_probability] = 1
    spike_array = np.expand_dims(spike_array, axis=1)

    spike_trains = th.make_trains(
        spike_array,
        fs=fs,
    )

    ### Plot the histogram
    th.plot_period_histogram(spike_trains, freq=freq, nbins=128, density=True)

    th.show()
示例#11
0
def test_select_trains():

    trains = th.make_trains([[1], [2], [3], [4]],
                            duration=4,
                            cfs=[0, 0, 1, 1],
                            idx=[0, 1, 0, 1])

    selected = th.select_trains(trains, cfs=1, idx=1)

    expected = th.make_trains([[4]], duration=4, cfs=[1], idx=[1])
    expected.index = [3]

    assert_frame_equal(
        selected,
        expected,
    )
示例#12
0
def test_trains_to_array():

    trains = th.make_trains([[1], [2, 3]], duration=5)

    result = th.spikes.trains_to_array(trains, fs=1)

    assert_equal(result, [[0, 0], [1, 0], [0, 1], [0, 1], [0, 0]])
示例#13
0
def test_trim_without_stop():

    trains = th.make_trains(
        [[1, 2], [2, 3]],
        duration=10,
        cf=1e3
    )

    trimmed = th.trim(trains, 2)

    expected = th.make_trains(
        [[0], [0, 1]],
        duration=8,
        cf=1e3
    )

    assert_frame_equal(trimmed, expected)
示例#14
0
def test_trim():

    trains = th.make_trains(
        [[1, 2], [2, 3]],
        duration=10,
        cf=1e3
    )

    trimmed = th.trim(trains, 1.5, 2.5)

    expected = th.make_trains(
        [[0.5], [0.5]],
        duration=1,
        cf=1e3
    )


    assert_frame_equal(trimmed, expected)
示例#15
0
def test_spike_count():
    trains = th.make_trains(
        [[0.1, 0.2, 0.3], [0.1, 0.2, 0.3]],
        duration=[2, 4]
    )

    count = th.spike_count(trains)

    assert_equal(count, 6)
示例#16
0
def test_accumulate():

    trains = th.make_trains(
        [[1], [2], [3], []],
        cfs=[2,1,2,3]
    )

    accumulated = th.accumulate(trains)

    expected = th.make_trains(
        [[2], [1,3], []],
        cfs=[1,2,3]
    )

    assert_frame_equal(
        accumulated,
        expected,
        check_like=True,
    )
示例#17
0
def test_make_empty_trains():

    spikes = [[], []]

    trains = th.make_trains(spikes)

    expected = pd.DataFrame({
        'spikes': spikes,
        'duration': np.repeat(0., len(spikes))
    })

    assert_frame_equal(trains, expected)

    trains = th.make_trains(spikes, duration=10)

    expected = pd.DataFrame({
        'spikes': spikes,
        'duration': np.repeat(10., len(spikes))
    })

    assert_frame_equal(trains, expected)
示例#18
0
def test_vector_strength():

    ### Uniform spikes
    trains = th.make_trains(
        [np.arange(0, 1, 1/3600)]
    )

    si = th.vector_strength(
        trains,
        freq=10
    )
    assert_almost_equal(si, 0)



    ### Perfect synchrony
    trains = th.make_trains(
        [np.zeros(100)],
        duration=0.1
    )
    si = th.vector_strength(
        trains,
        freq=10
    )
    assert_equal(si, 1)



    ### Carefully chosen
    trains = th.make_trains(
        [np.tile([0, 0.25], 10)]
    )

    si = th.vector_strength(
        trains,
        freq=1
    )

    assert_equal(si, np.sqrt(2)/2)
示例#19
0
def test_firing_rate():

    trains = th.make_trains(
        [[0.1, 0.4],
         [0.4, 0.5, 0.6]],
        duration=1
    )

    rate = th.firing_rate(
        trains
    )

    assert_equal(rate, 2.5)
示例#20
0
def test_from_array():

    fs = 1e3
    a = np.array(
        [[0,0,0,1,0,0],
         [0,2,1,0,0,0]]
    ).T

    result = th.make_trains(a, fs=fs)


    expected = th.make_trains(
        [np.array([3])/fs,
         np.array([1,1,2])/fs],
        duration = 6/fs
    )


    assert_frame_equal(
        expected,
        result
    )
示例#21
0
def test_from_arrays():

    arrays = [[1, 2, 3], [1, 3, 5, 7], [0, 8]]

    expected = {'spikes': arrays, 'duration': np.repeat(10., len(arrays))}
    expected = pd.DataFrame(expected)

    result = th.spikes._arrays_to_trains(arrays, duration=10.0)

    assert_frame_equal(result, expected)

    result = th.make_trains(arrays, duration=10.0)
    assert_frame_equal(expected, result)
示例#22
0
def test_fold():
    trains = th.make_trains(
        [[1.1, 2.1, 3.1], [2.1, 3.1, 5.1]],
        duration=6.5,
        cf=[1,2]
    )

    folded = th.fold(trains, 1)


    expected = th.make_trains(
        [[  ], [.1], [.1], [.1], [  ], [  ], [  ],
         [  ], [  ], [.1], [.1], [  ], [.1], [  ]],
        duration=[1, 1, 1, 1, 1, 1, 0.5,
                  1, 1, 1, 1, 1, 1, 0.5],
        cf=[1, 1, 1, 1, 1, 1, 1,
            2, 2, 2, 2, 2, 2, 2]
    )

    assert_frame_equal(
        folded,
        expected,
    )
示例#23
0
def test_correlation_index():

    trains = th.make_trains(
        [[1,3],
         [1,2,3]]
    )


    ci = th.correlation_index(
        trains,
        normalize=False
    )

    assert_equal(ci, 4)
示例#24
0
def test_make_empty_trains():

    spikes = [[], []]

    trains = th.make_trains(
        spikes
    )

    expected = pd.DataFrame({
        'spikes': spikes,
        'duration': np.repeat(0., len(spikes))
    })

    assert_frame_equal(
        trains,
        expected
    )






    trains = th.make_trains(
        spikes,
        duration=10
    )

    expected = pd.DataFrame({
        'spikes': spikes,
        'duration': np.repeat(10., len(spikes))
    })

    assert_frame_equal(
        trains,
        expected
    )
示例#25
0
def test_trim():

    trains = th.make_trains(
        [[1,2,3,4],
         [3,4,5,6]],
        duration=8,
        type='hsr'
    )


    trimmed = th.trim(trains, 2, 4)


    expected = th.make_trains(
        [[0,1,2], [1,2]],
        duration=2,
        type='hsr'
    )


    assert_frame_equal(
        trimmed,
        expected
    )
示例#26
0
def test_isih():

    trains = th.make_trains(
        [[1,2,3], [2,5,8]]
    )

    isih, bin_edges = th.isih(
        trains,
        bin_size=1,
    )

    assert_equal(
        isih,
        [ 0, 2, 2]
    )
    assert_equal(
        bin_edges,
        [ 0, 1, 2, 3]
    )
示例#27
0
def test_from_arrays():

    arrays = [
        [1,2,3],
        [1,3,5,7],
        [0,8]
    ]


    expected = {
        'spikes': arrays,
        'duration': np.repeat(10., len(arrays))
    }
    expected = pd.DataFrame(expected)





    result = th.spikes._arrays_to_trains(
        arrays,
        duration=10.0
    )

    assert_frame_equal(
        result,
        expected
    )




    result = th.make_trains(
        arrays,
        duration=10.0
    )
    assert_frame_equal(
        expected,
        result
    )
示例#28
0
def test_trains_to_array():


    trains = th.make_trains(
        [[1], [2,3]],
        duration=5
    )

    result = th.spikes.trains_to_array(
        trains,
        fs=1
    )


    assert_equal(
        result,
        [[0,0],
         [1,0],
         [0,1],
         [0,1],
         [0,0]]
    )
示例#29
0
def test_psth():

    trains = th.make_trains(
        [[0.5, 1.5, 2.5],
         [0.5, 2.5]]
    )

    psth, bin_edges = th.psth(
        trains,
        bin_size=1,
        normalize=False
    )


    assert_equal(
        psth,
        [2, 1, 2]
    )
    assert_equal(
        bin_edges,
        [0, 1, 2, 3]
    )
示例#30
0
def test_shuffled_autocorrelogram():

    trains = th.make_trains(
        [[1,3],
         [1,2,3]]
    )

    sac, bin_edges = th.shuffled_autocorrelogram(
        trains,
        coincidence_window=1,
        analysis_window=3,
        normalize=False
    )


    assert_equal(
        bin_edges,
        [-2., -1.,  0.,  1.,  2.,  3.]
    )
    assert_equal(
        sac,
        [2, 2, 4, 2, 2]
    )
示例#31
0
def main():

    fs = 10e3                   # Hz
    freq = 10                   # Hz


    ### Calculate spike probability over time (we want to have a
    ### periodic function for a pretty plot)
    t = np.arange(0, 1, 1/fs)
    spike_probability = 0.2 * np.abs(np.sin(2 * np.pi * freq * t))
    rand = np.random.rand(len(spike_probability))




    ### Generate spike trains
    spike_array = np.zeros_like(spike_probability)
    spike_array[rand < spike_probability] = 1
    spike_array = np.expand_dims(spike_array, axis=1)

    spike_trains = th.make_trains(
        spike_array,
        fs=fs,
    )




    ### Plot the histogram
    th.plot_period_histogram(
        spike_trains,
        freq=freq,
        nbins=128,
        density=True
    )

    th.show()
def run_exp(c_freq, itd, str_e, str_i):
    # br.globalprefs.set_global_preferences(useweave=True, openmp=True, usecodegen=True,
    #                                       usecodegenweave=True )

    br.defaultclock.dt = 20E-6 * second

    #Basic Parameters
    fs_coch = 100e3  # s/second
    duration = 100E-3  # seconds##
    pad = 20E-3  # second
    n_neuron = 300
    dbspl = 50
    n_neuron = 500
    dt_coch = 1 / fs_coch
    n_pad = int(pad / dt_coch)
    n_itd = int(itd / dt_coch)
    const_dt = 100e-6

    sound = audio.generate_tone(c_freq, duration, fs_coch)
    sound = sound * audio.cosine_fade_window(sound, 20e-3, fs_coch)
    sound = coch.set_dbspl(sound, dbspl)
    sound = np.concatenate((np.zeros(n_pad), sound, np.zeros(n_pad)))
    sound = audio.delay_signal(sound, np.abs(itd), fs_coch)

    if itd < 0:
        sound = sound[:, ::-1]
    duration = len(sound) / fs_coch

    # construct ipsi and contra-lateral ANF trains and convert them to
    # neuron groups
    cochlea_train_left = coch.run_zilany2014(sound=sound[:, 0],
                                             fs=fs_coch,
                                             anf_num=(n_neuron, 0, 0),
                                             cf=c_freq,
                                             species='human',
                                             seed=0)

    cochlea_train_right = coch.run_zilany2014(sound=sound[:, 1],
                                              fs=fs_coch,
                                              anf_num=(n_neuron, 0, 0),
                                              cf=c_freq,
                                              species='human',
                                              seed=0)

    anf_group_left = coch.make_brian_group(cochlea_train_left)
    anf_group_right = coch.make_brian_group(cochlea_train_right)

    # Setup a new mso group and new gbc groups
    mso_group_left = make_mso_group(n_neuron)
    mso_group_right = make_mso_group(n_neuron)

    gbc_group_left = cochlea_to_gbc(anf_group_left, n_neuron)
    gbc_group_right = cochlea_to_gbc(anf_group_right, n_neuron)

    # Synaptic connections for the groups
    syn_mso_l_in_ipsi, syn_mso_l_in_contra = inhibitory_to_mso(
        mso_group=mso_group_left,
        ipsi_group=gbc_group_left['neuron_groups'][0],
        contra_group=gbc_group_right['neuron_groups'][0],
        strength=str_i,
        ipsi_delay=0,
        contra_delay=-0.6e-3 + const_dt)

    syn_mso_r_in_ipsi, syn_mso_r_in_contra = inhibitory_to_mso(
        mso_group=mso_group_right,
        ipsi_group=gbc_group_right['neuron_groups'][0],
        contra_group=gbc_group_left['neuron_groups'][0],
        strength=str_i,
        ipsi_delay=0,
        contra_delay=-0.6e-3 + const_dt)

    syn_mso_l_ex_ipsi, syn_mso_l_ex_contra = excitatory_to_mso(
        mso_group=mso_group_left,
        ipsi_group=anf_group_left,
        contra_group=anf_group_right,
        strength=str_e,
        contra_delay=const_dt)

    syn_mso_r_ex_ipsi, syn_mso_r_ex_contra = excitatory_to_mso(
        mso_group=mso_group_right,
        ipsi_group=anf_group_right,
        contra_group=anf_group_left,
        strength=str_e,
        contra_delay=const_dt)

    sp_mon_left = br.SpikeMonitor(mso_group_left, record=True)
    sp_mon_right = br.SpikeMonitor(mso_group_right, record=True)

    network = ([
        mso_group_left, mso_group_right, anf_group_left, anf_group_right,
        syn_mso_l_ex_ipsi, syn_mso_l_ex_contra, syn_mso_l_in_ipsi,
        syn_mso_l_in_contra, syn_mso_r_ex_ipsi, syn_mso_r_ex_contra,
        syn_mso_r_in_ipsi, syn_mso_r_in_contra, sp_mon_left, sp_mon_right
    ] + gbc_group_left['neuron_groups'] + gbc_group_right['neuron_groups'])

    run(duration, network)

    mso_train_left = thorns.make_trains(sp_mon_left)
    mso_train_right = thorns.make_trains(sp_mon_right)

    return {'spikes_left': mso_train_left, 'spikes_right': mso_train_right}
def main():

    fs = 100e3  # s
    cf = 600  # Hz
    duration = 50e-3  # s

    # Simulation sampling frequency
    cn.set_fs(40e3)  # Hz

    # Generate sound
    sound = wv.ramped_tone(
        fs=fs,
        freq=cf,
        duration=duration,
        dbspl=30,
    )

    # Generate ANF trains
    anf_trains = cochlea.run_zilany2014(
        sound=sound,
        fs=fs,
        anf_num=(300, 0, 0),  # (HSR, MSR, LSR)
        cf=cf,
        species='cat',
        seed=0,
    )

    # Generate ANF and GBC groups
    anfs = cn.make_anf_group(anf_trains)
    gbcs = cn.make_gbc_group(100)

    # Connect ANFs and GBCs
    synapses = brian.Connection(
        anfs,
        gbcs,
        'ge_syn',
    )

    convergence = 20

    weight = cn.synaptic_weight(pre='anf', post='gbc', convergence=convergence)

    synapses.connect_random(anfs,
                            gbcs,
                            p=convergence / len(anfs),
                            fixed=True,
                            weight=weight)

    # Monitors for the GBCs
    spikes = brian.SpikeMonitor(gbcs)

    # Run the simulation
    cn.run(duration=len(sound) / fs, objects=[anfs, gbcs, synapses, spikes])

    # Present the results
    gbc_trains = th.make_trains(spikes)

    fig, ax = plt.subplots(2, 1)

    th.plot_raster(anf_trains, ax=ax[0])
    th.plot_raster(gbc_trains, ax=ax[1])

    plt.show()
示例#34
0
def run_matlab_auditory_periphery(
        sound,
        fs,
        anf_num,
        cf,
        seed,
        params_name='Normal',
        matlab_session=None
):
    """Run Matlab Auditory Periphery [MAP]_ model by Ray Meddis.  This
    function does not implement the model, but wraps the model
    implementation using `matlab_wrapper`.  The model takes sound
    signal as input and outputs auditory nerve spike trains.

    In order to run it, make sure that all necessary [MAP]_ model
    files are in `MATLABPATH`.  You should be able to run `MAP1_14`
    function in MATLAB first!

    Requires MATLAB, *matlab_wrapper*, *thorns* and [MAP]_ in
    `MATLABPATH`.


    Parameters
    ----------
    sound : array_like
        Input sound.
    fs : float
        Sampling frequency of the sound.
    anf_num : tuple
        Number of auditory nerve fibers per channel (HSR#, MSR#, LSR#).
    cf : float or array_like or tuple
        The center frequency(s) of the simulated auditory nerve fibers.
        If float, then defines a single frequency channel.  If
        array_like (e.g. list or ndarray), then the frequencies are
        used.  If tuple, then must have exactly 3 elements (min_cf,
        max_cf, num_cf) and the frequencies are calculated using the
        Greenwood function.
    seed : int
        Random seed.
    params_name : str, optional Tail of the parameter filename
        (parameterStore/MAPparams<params_name>.m).  Refer to MAP
        documentation for the details.
    matlab_session : MatlabSession or None, optional
        MatlabSession object from `matlab_wrapper` module.  If `None`,
        then new session is generated.


    Returns
    -------
    spike_trains
        Auditory nerve spike trains.


    References
    ----------

    .. [MAP] http://www.essexpsychology.macmate.me/HearingLab/modelling.html

    """

    ### Validate `anf_num`
    assert len(anf_num) == 3


    ### Validate `cf`
    if isinstance(cf, tuple):
        assert len(cf) == 3
    elif np.isscalar(cf):
        pass
    elif len(cf) == 3:
        raise RuntimeError("Three frequency channels are forbidden, because they mask the tuple (min_cf, max_cf, cf_num).")


    ### Generate matlab_wrapper session as needed
    if matlab_session is None:
        matlab = matlab_wrapper.MatlabSession(options='-nosplash -singleCompThread')
    else:
        matlab = matlab_session

    matlab.eval("clear all")
    matlab.eval("clearvars -global")

    ### Set Matlab environment
    matlab.workspace.rng(seed)

    matlab.eval("global dtSpikes ANoutput savedBFlist")

    matlab.workspace.MAP1_14(
        sound,
        float(fs),
        np.array(cf, dtype=float),
        params_name,
        'spikes',
        ['AN_IHCsynapseParams.numFibers={};'.format(max(anf_num)),
         'AN_IHCsynapseParams.spikesTargetSampleRate={};'.format(fs)],
        nout=0
    )


    ### Collect results from Matlab
    anf_raw = matlab.workspace.ANoutput

    cf_raw = matlab.workspace.savedBFlist
    cf_raw = np.atleast_1d(cf_raw)

    dt_raw = matlab.workspace.dtSpikes



    ### Make trains
    all_trains = th.make_trains(
        anf_raw.T,
        fs=1/dt_raw
    )

    cf_col = np.tile(np.repeat(cf_raw,anf_num[0]), 3)
    type_col = np.repeat(['lsr', 'msr', 'hsr'], len(cf_raw)*anf_num[0])

    all_trains['type'] = type_col
    all_trains['cf'] = cf_col



    n = {
        'hsr': anf_num[0],
        'msr': anf_num[1],
        'lsr': anf_num[2],
    }

    ### Discard trains.  We want only anf_num == (HSR#, MSR#, LSR#)
    anf_trains = []
    for name,group in all_trains.groupby(['type','cf']):
        typ,cf = name

        sel = group.iloc[0:n[typ]]

        anf_trains.append(sel)


    anf_trains = pd.concat(anf_trains)

    return anf_trains
示例#35
0
def run_matlab_auditory_periphery(
        sound,
        fs,
        anf_num,
        cf,
        seed,
        params_name='Normal',
        matlab_session=None
):
    """Run Matlab Auditory Periphery [MAP]_ model by Ray Meddis.  This
    function does not implement the model, but wraps the model
    implementation using `matlab_wrapper`.  The model takes sound
    signal as input and outputs auditory nerve spike trains.

    In order to run it, make sure that all necessary [MAP]_ model
    files are in `MATLABPATH`.  You should be able to run `MAP1_14`
    function in MATLAB first!

    Requires MATLAB, *matlab_wrapper*, *thorns* and [MAP]_ in
    `MATLABPATH`.


    Parameters
    ----------
    sound : array_like
        Input sound.
    fs : float
        Sampling frequency of the sound.
    anf_num : tuple
        Number of auditory nerve fibers per channel (HSR#, MSR#, LSR#).
    cf : float or array_like or tuple
        The center frequency(s) of the simulated auditory nerve fibers.
        If float, then defines a single frequency channel.  If
        array_like (e.g. list or ndarray), then the frequencies are
        used.  If tuple, then must have exactly 3 elements (min_cf,
        max_cf, num_cf) and the frequencies are calculated using the
        Greenwood function.
    seed : int
        Random seed.
    params_name : str, optional Tail of the parameter filename
        (parameterStore/MAPparams<params_name>.m).  Refer to MAP
        documentation for the details.
    matlab_session : MatlabSession or None, optional
        MatlabSession object from `matlab_wrapper` module.  If `None`,
        then new session is generated.


    Returns
    -------
    spike_trains
        Auditory nerve spike trains.


    References
    ----------

    .. [MAP] http://www.essexpsychology.macmate.me/HearingLab/modelling.html

    """

    ### Validate `anf_num`
    assert len(anf_num) == 3


    ### Validate `cf`
    if isinstance(cf, tuple):
        assert len(cf) == 3
    elif np.isscalar(cf):
        pass
    elif len(cf) == 3:
        raise RuntimeError("Three frequency channels are forbidden, because they mask the tuple (min_cf, max_cf, cf_num).")


    ### Generate matlab_wrapper session as needed
    if matlab_session is None:
        matlab = matlab_wrapper.MatlabSession(options='-nosplash -singleCompThread')
    else:
        matlab = matlab_session

    matlab.eval("clear all")
    matlab.eval("clearvars -global")

    ### Set Matlab environment
    matlab.workspace.rng(seed)

    matlab.eval("global dtSpikes ANoutput savedBFlist")

    matlab.workspace.MAP1_14(
        sound,
        float(fs),
        np.array(cf, dtype=float),
        params_name,
        'spikes',
        ['AN_IHCsynapseParams.numFibers={};'.format(max(anf_num)),
         'AN_IHCsynapseParams.spikesTargetSampleRate={};'.format(fs)],
        nout=0
    )


    ### Collect results from Matlab
    anf_raw = matlab.workspace.ANoutput

    cf_raw = matlab.workspace.savedBFlist
    cf_raw = np.atleast_1d(cf_raw)

    dt_raw = matlab.workspace.dtSpikes



    ### Make trains
    all_trains = th.make_trains(
        anf_raw.T,
        fs=1/dt_raw
    )

    cf_col = np.tile(np.repeat(cf_raw,anf_num[0]), 3)
    type_col = np.repeat(['lsr', 'msr', 'hsr'], len(cf_raw)*anf_num[0])

    all_trains['type'] = type_col
    all_trains['cf'] = cf_col



    n = {
        'hsr': anf_num[0],
        'msr': anf_num[1],
        'lsr': anf_num[2],
    }

    ### Discard trains.  We want only anf_num == (HSR#, MSR#, LSR#)
    anf_trains = []
    for name,group in all_trains.groupby(['type','cf']):
        typ,cf = name

        sel = group.iloc[0:n[typ]]

        anf_trains.append(sel)


    anf_trains = pd.concat(anf_trains)

    return anf_trains
示例#36
0
def main():

    Fs = float(100e3)
    #The entire simulation must be done at a common sampling frequency. As the Zilany model takes a minimum sampling frequency of 100KHz, everything is upsampled to that

    #Extracting speech signal and pre-processing:
    dictsample = sio.loadmat(
        'resampled.mat'
    )  #Resampled.mat is simply a speech signal resampled to 100KHz, here you can have anything that is sampled at 100KHz, be it a segment of a song or any arbritary signal. There is no file path because we assume that this file is the same directory
    sample = dictsample['newstory']
    #newstory is just the key title for the array
    sample = sample.flatten()  #making the signal a Row vector
    duration = float(2)
    #This is how long you want your sample to be, we take 2 seconds of the speech signal because it contains significant amount of vowel sounds but you can change this number to anything
    index = int(duration * Fs)
    #Converting the duration wanted into an index value using the sampling frequency
    mysample = sample[0:index]
    #Selecting the desired duration of signal interms of index value
    wv.set_dbspl(
        mysample, 78
    )  #setting the level to 78 dB SPL. SPL is the sound pressure level. This is an arbritary number and can be changed.

    brian.defaultclock.dt = 0.01 * ms
    #This coincides with the desired sampling frequency of 100KHz

    # Generate spike trains from Auditory Nerve Fibres using Cochlea Package
    anf_trains = cochlea.run_zilany2014(
        sound=mysample,
        fs=Fs,
        anf_num=(
            13, 3, 1
        ),  # (Amount of High spike rate, Medium spike rate, Low spike rate fibres. You can choose these as you want but these numbers are taken from the Verhulst et.al 2015 paper)
        cf=(125, 8000, 30),
        species='human',  #This can be changed to cat as well 
        seed=0,
        powerlaw=
        'approximate'  #The latest implementation of the Zilany model includes the power law representation however we do not want this to be too computationally intensive. Therefore we pick approximate
    )

    # Generate ANF and GBC groups in Brian using inbuilt functions in the Cochlear Nucleus package

    anfs = cn.make_anf_group(
        anf_trains
    )  #The amount of neurons for the Auditory Nerve = 30 * Amount of Fibres
    gbcs = cn.make_gbc_group(
        200
    )  #200 is the number of neurons for globular bushy cells in the cochlear nucleus. You can change this to any number but it doesn't affect the result

    # Connect ANFs and GBCs using the synapses class in Brian
    synapses = brian.Connection(
        anfs,
        gbcs,
        'ge_syn',
        delay=5 *
        ms  #This is important to make sure that there is a delay between the groups
    )

    #this value of convergence is taken from the Cochlear Nucleus documentation
    convergence = 20

    weight = cn.synaptic_weight(pre='anf', post='gbc', convergence=convergence)

    #Initiating the synaptic connections to be random with a fixed probability p that is proportional to the synaptic convergence
    synapses.connect_random(
        anfs,
        gbcs,
        p=convergence / len(anfs),
        fixed=True,
        weight=weight,
    )

    # Monitors for the GBCs. Brian Spike Monitors are objects that basically collect the amount of spikes in a neuron group
    gbc_spikes = brian.SpikeMonitor(gbcs)

    # Run the simulation using the run function in the CN package. This basically uses Brian's run function
    cn.run(
        duration=duration,
        objects=[anfs, gbcs, synapses,
                 gbc_spikes]  #include ANpop and CN pop in this if you need to
    )

    gbc_trains = th.make_trains(gbc_spikes)

    #Extracting the spike times for both AN and CN groups
    CNspikes = gbc_trains['spikes']
    ANspikes = anf_trains['spikes']

    #Converting dict format to array format so that spike train data is basically a one dimensional array or row vector of times where spikes occur
    CN_spikes = np.asarray(CNspikes)
    AN_spikes = np.asarray(ANspikes)

    #Saving it in the appropriate format so that we can do further processing in MATLAB
    data = {'CN': CN_spikes, 'AN': AN_spikes}
    sio.savemat('Spiketrains', data)

    #If you want to plot the rasters of these spike trains in MATPLOTLIB, you can use the following code:

    fig, ax = plt.subplots(2, 1)

    th.plot_raster(anf_trains, ax=ax[0])
    th.plot_raster(gbc_trains, ax=ax[1])
    plt.show()
    plt.tight_layout()