예제 #1
0
    gs_e = gs_i + middle_height + 1

    f = d['psd_freq']
    ax = plt.subplot(gs[gs_i:gs_e, (left_width+5):])
    plt.imshow(sprops['lfp_psd'], interpolation='nearest', aspect='auto', origin='upper',
               extent=(f.min(), f.max(), nelectrodes, 0), cmap=viridis, vmin=-2., vmax=2.)
    plt.colorbar(label='Z-scored Log Power')
    plt.xlabel('Frequency (Hz)')
    plt.yticks(np.arange(nelectrodes)+0.5, d['electrode_order'])
    plt.ylabel('Electrode')

    fname = os.path.join(get_this_dir(), 'figure.svg')
    plt.savefig(fname, facecolor='w', edgecolor='none')

    plt.show()


def draw_figures():

    d = get_full_data('GreBlu9508M', 'Site4', 'Call1', 'L', 268)
    # d = get_full_data('GreBlu9508M', 'Site4', 'Call1', 'L', 277)
    plot_full_data(d, 1)

    plt.show()


if __name__ == '__main__':
    spec_colormap()
    set_font()
    draw_figures()
예제 #2
0
def plot_syllable_comps(agg, stim_id=43, syllable_order=1, data_dir='/auto/tdrive/mschachter/data'):

    sprops = get_syllable_props(agg, stim_id, syllable_order, data_dir)
    wave = sprops['wave']
    wave_t = sprops['wave_t']
    wave_si = sprops['wave_si']
    wave_ei = sprops['wave_ei']
    ps_freq = sprops['ps_freq']
    ps = sprops['ps']
    amp_env = sprops['amp_env']
    aprops = sprops['aprops']
    start_time = aprops['start_time']
    spec = sprops['spec']
    spec_t = sprops['spec_t']
    spec_freq = sprops['spec_freq']
    spec_si = sprops['spec_si']
    spec_ei = sprops['spec_ei']

    aprop_specs = dict()
    aprop_spec_props = ['maxAmp', 'meanspect', 'sal']
    for aprop in aprop_spec_props:
        aprop_specs[aprop] = get_syllable_examples(agg, aprop, data_dir, bird='GreBlu9508M')

    figsize = (23, 13)
    fig = plt.figure(figsize=figsize, facecolor='w')
    fig.subplots_adjust(top=0.95, bottom=0.08, right=0.97, left=0.06, hspace=0.30, wspace=0.30)
    gs = plt.GridSpec(3, 100)

    sp_width = 20

    ax = plt.subplot(gs[0, :sp_width])
    plt.plot((wave_t[wave_si:wave_ei] - start_time)*1e3, wave[wave_si:wave_ei], 'k-', linewidth=2.)
    plt.plot((wave_t[wave_si:wave_ei] - start_time)*1e3, amp_env[wave_si:wave_ei], 'r-', linewidth=4., alpha=0.7)
    plt.xlabel('Time (ms)')
    plt.ylabel('Waveform')
    plt.axis('tight')

    aprops_to_get = ['skewtime', 'kurtosistime', 'entropytime', 'maxAmp']
    units = ['s', '', '', 'bits', '']
    ax = plt.subplot(gs[0, sp_width:(sp_width+18)])
    txt_space = 0.1
    for k,aprop in enumerate(aprops_to_get):
        aval = aprops[aprop]
        if aval > 10:
            txt = '%s: %d' % (ACOUSTIC_PROP_NAMES[aprop], aval)
        else:
            txt = '%s: %0.2f' % (ACOUSTIC_PROP_NAMES[aprop], aval)
        txt += ' %s' % units[k]
        plt.text(0.1, 1-((k+1)*txt_space), txt, fontsize=18)
    ax.set_axis_off()
    plt.xlim(0, 1)
    plt.ylim(0, 1)
    plt.xticks([])
    plt.yticks([])

    ax = plt.subplot(gs[1, :sp_width])
    fi = (ps_freq > 0) & (ps_freq <= 8000.)
    plt.plot(ps_freq[fi]*1e-3, ps[fi], 'k-', linewidth=3., alpha=1.)
    for aprop in ['q1', 'q2', 'q3']:
        plt.axvline(aprops[aprop]*1e-3, color='#606060', linestyle='--', linewidth=3.0, alpha=0.9)
        # plt.text(aprops[aprop]*1e-3 - 0.6, 3000., aprop, fontsize=14)
    plt.ylabel("Power")
    plt.yticks([])
    plt.xlabel('Frequency (kHz)')
    plt.axis('tight')

    aprops_to_get = ['meanspect', 'stdspect', 'skewspect', 'kurtosisspect', 'entropyspect', 'q1', 'q2', 'q3']
    units = ['Hz', 'Hz', '', '', 'bits', 'Hz', 'Hz', 'Hz']
    ax = plt.subplot(gs[1, sp_width:(sp_width+18)])
    for k,aprop in enumerate(aprops_to_get):
        aval = aprops[aprop]
        if aval > 10:
            txt = '%s: %d' % (ACOUSTIC_PROP_NAMES[aprop], aval)
        else:
            txt = '%s: %0.2f' % (ACOUSTIC_PROP_NAMES[aprop], aval)
        txt += ' %s' % units[k]
        plt.text(0.1, 1-((k+1)*txt_space), txt, fontsize=18)
    ax.set_axis_off()
    plt.xlim(0, 1)
    plt.ylim(0, 1)
    plt.xticks([])
    plt.yticks([])

    spec_colormap()
    ax = plt.subplot(gs[2, :sp_width])
    plot_spectrogram((spec_t[spec_si:spec_ei]-start_time)*1e3, spec_freq*1e-3, spec[:, spec_si:spec_ei], ax, colormap='SpectroColorMap', colorbar=False)
    plt.axhline(aprops['fund']*1e-3, color='k', linestyle='--', linewidth=3.0)
    plt.ylabel("Frequency (kHz)")
    plt.xlabel('Time (ms)')

    for k,aprop in enumerate(aprop_spec_props):

        full_spec_freq, full_spec, centers, propvals, stypes = aprop_specs[aprop]

        ax = plt.subplot(gs[k, (sp_width+20):])
        full_spec_t = np.arange(full_spec.shape[1]) / sprops['spec_sample_rate']
        plot_spectrogram(full_spec_t, full_spec_freq*1e-3, full_spec, ax, colormap='SpectroColorMap', colorbar=False)
        for c,st in zip(centers,stypes):
            plt.text(c/sprops['spec_sample_rate'], 7., CALL_TYPE_NAMES[st], fontsize=20)
        pstrs = list()
        for p in propvals:
            if p > 10:
                if aprop == 'meanspect':
                    pstrs.append('%d Hz' % p)
                else:
                    pstrs.append('%d' % p)
            else:
                pstrs.append('%0.3f' % p)
        for c,p in zip(centers,pstrs):
            plt.text(c, 6, p, fontsize=20)
        # plt.xticks(centers, pstrs)
        plt.xticks([])
        plt.ylabel('Frequency (kHz)')

        scale_t = (full_spec_t.max()*0.95) - np.linspace(0, 0.050, 20)
        scale_y = np.zeros_like(scale_t) + 3
        plt.plot(scale_t, scale_y, 'k-', linewidth=4.0)
        plt.text(scale_t.min(), 2.0, '50ms', fontsize=20, fontweight='bold')

        upper_right_x = np.percentile(full_spec_t, 80)
        upper_right_y = 7
        plt.title(ACOUSTIC_PROP_FULLNAMES[aprop], fontsize=22)

    aprops_to_get = ['fund', 'fund2', 'sal', 'voice2percent', 'maxfund', 'minfund', 'cvfund']
    units = ['Hz', 'Hz', '', '', 'Hz', 'Hz', 'Hz']
    ax = plt.subplot(gs[2, sp_width:(sp_width + 18)])
    for k, aprop in enumerate(aprops_to_get):
        aval = aprops[aprop]
        if aval > 10:
            txt = '%s: %d' % (ACOUSTIC_PROP_NAMES[aprop], aval)
        else:
            txt = '%s: %0.2f' % (ACOUSTIC_PROP_NAMES[aprop], aval)
        txt += ' %s' % units[k]
        plt.text(0.1, 1 - ((k + 1) * txt_space), txt, fontsize=18)
    ax.set_axis_off()
    plt.xlim(0, 1)
    plt.ylim(0, 1)
    plt.xticks([])
    plt.yticks([])

    fname = os.path.join(get_this_dir(), 'figure.svg')
    plt.savefig(fname, facecolor='w', edgecolor='none')

    plt.show()
예제 #3
0
def plot_nofund(agg, data_dir='/auto/tdrive/mschachter/data'):

    spec_colormap()

    aprops = ['fund', 'maxfund', 'minfund', 'cvfund', 'fund2', 'voice2percent',
               'stdspect', 'skewspect', 'kurtosisspect', 'entropyspect', 'sal',
               'meanspect', 'q1', 'q2', 'q3', 'skewtime', 'kurtosistime', 'entropytime', 'maxAmp']
    Xz, good_indices = agg.remove_duplicates(acoustic_props=aprops)

    stim_durs = agg.df.end_time.values - agg.df.start_time.values
    good_indices = [gi for gi in good_indices if stim_durs[gi] > 0.040 and stim_durs[gi] < 0.450]

    stims = [(stim_id, order, stim_type) for stim_id, order, stim_type in zip(agg.df.stim_id[good_indices],
                                                                              agg.df.syllable_order[good_indices],
                                                                              agg.df.stim_type[good_indices])]

    plt.figure()
    plt.hist(stim_durs[good_indices], bins=25)
    plt.show()

    fund_i = agg.acoustic_props.index('fund')
    funds = np.array([agg.Xraw[xindex, fund_i] for xindex in agg.df.xindex[good_indices]])

    print 'funds.min=%f, q1=%f, q2=%f' % (funds.min(), np.percentile(funds, 1), np.percentile(funds, 2))

    no_fund = np.where(funds <= 0)[0]
    yes_fund = np.where(funds > 0)[0]
    print 'no_fund=', no_fund

    plt.figure()
    plt.hist(funds, bins=20)
    plt.title('funds')
    # plt.show()

    # np.random.seed(1234567)
    # np.random.shuffle(no_fund)
    # np.random.shuffle(yes_fund)

    # get syllable properties for some examples of syllables with and without fundamental frequencies
    set_font(10)
    figsize = (23, 10)
    fig = plt.figure(figsize=figsize)
    fig.subplots_adjust(wspace=0.35, hspace=0.35, left=0.05, right=0.95)

    num_syllables = 5
    no_fund_i = no_fund[:num_syllables]
    yes_fund_i = yes_fund[:num_syllables]

    gs = plt.GridSpec(2, num_syllables)
    for k in range(num_syllables):

        fi = no_fund_i[k]
        f = funds[fi]
        stim_id,stim_order,stim_type = stims[fi]
        sprops = get_syllable_props(agg, stim_id, stim_order, data_dir)

        ax = plt.subplot(gs[0, k])
        si = sprops['spec_si']
        ei = sprops['spec_ei']
        plot_spectrogram(sprops['spec_t'][si:ei], sprops['spec_freq'], sprops['spec'][:, si:ei], ax=ax,
                         colormap='SpectroColorMap', colorbar=False)
        plt.title('%d_%d (%s), fund=%0.2f' % (stim_id, stim_order, stim_type, f))

        fi = yes_fund_i[k]
        f = funds[fi]
        stim_id, stim_order, stim_type = stims[fi]
        sprops = get_syllable_props(agg, stim_id, stim_order, data_dir)

        ax = plt.subplot(gs[1, k])
        si = sprops['spec_si']
        ei = sprops['spec_ei']
        plot_spectrogram(sprops['spec_t'][si:ei], sprops['spec_freq'], sprops['spec'][:, si:ei], ax=ax,
                         colormap='SpectroColorMap', colorbar=False)
        plt.title('%d_%d (%s), fund=%0.2f' % (stim_id, stim_order, stim_type, f))

    plt.show()
예제 #4
0
def draw_figures(data_dir='/auto/tdrive/mschachter/data', bird='GreBlu9508M', output_dir='/auto/tdrive/mschachter/data/sounds'):

    spec_colormap()

    exp_dir = os.path.join(data_dir, bird)
    exp_file = os.path.join(exp_dir, '%s.h5' % bird)
    stim_file = os.path.join(exp_dir, 'stims.h5')
    
    exp = Experiment.load(exp_file, stim_file)
    
    bird = exp.bird_name
    all_stim_ids = list()
    # iterate through the segments and get the stim ids from each epoch table
    for seg in exp.get_all_segments():
        etable = exp.get_epoch_table(seg)
        stim_ids = etable['id'].unique()
        all_stim_ids.extend(stim_ids)

    stim_ids = np.unique(all_stim_ids)

    stim_info = list()
    for stim_id in stim_ids:
        si = exp.stim_table['id'] == stim_id
        assert si.sum() == 1, "More than one stimulus defined for id=%d" % stim_id
        stype = exp.stim_table['type'][si].values[0]
        if stype == 'call':
            stype = exp.stim_table['callid'][si].values[0]

        # get sound pressure waveform
        sound = exp.sound_manager.reconstruct(stim_id)
        waveform = np.array(sound.squeeze())
        sample_rate = float(sound.samplerate)
        stim_dur = len(waveform) / sample_rate

        stim_info.append( (stim_id, stype, sample_rate, waveform, stim_dur))

    durations = np.array([x[-1] for x in stim_info])
    max_dur = durations.max()
    min_dur = durations.min()

    max_fig_size = 15.
    min_fig_size = 5.

    for stim_id,stype,sample_rate,waveform,stim_dur in stim_info:

        fname = os.path.join(output_dir, '%s_stim_%d.wav' % (stype, stim_id))
        print 'Writing %s...' % fname
        wavfile.write(fname, sample_rate, waveform)

        dfrac = (stim_dur - min_dur) / (max_dur - min_dur)
        fig_width = dfrac*(max_fig_size - min_fig_size) + min_fig_size

        spec_t,spec_freq,spec,rms = spectrogram(waveform, sample_rate, sample_rate, 136., min_freq=300, max_freq=8000,
                                                log=True, noise_level_db=80, rectify=True, cmplx=False)

        figsize = (fig_width, 5)
        fig = plt.figure(figsize=figsize)
        plot_spectrogram(spec_t, spec_freq, spec, colormap='SpectroColorMap', colorbar=False)
        plt.title('Stim %d: %s' % (stim_id, stype))

        fname = os.path.join(output_dir, '%s_stim_%d.png' % (stype, stim_id))
        plt.savefig(fname, facecolor='w')
        plt.close('all')