Exemplo n.º 1
0
def pfreqpwr_with_hist(file_name, freqpwr_result, f_spk, gid_dict, p_dict,
                       key_types):
    f = ac.FigFreqpwrWithHist()
    f.ax['hist'].hold(True)

    xmin = 50.
    xmax = p_dict['tstop']

    f.ax['freqpwr'].plot(freqpwr_result['freq'], freqpwr_result['avgpwr'])

    # grab alpha feed data. spikes_from_file() from spikefn.py
    s_dict = spikefn.spikes_from_file(gid_dict, f_spk)

    # check for existance of alpha feed keys in s_dict.
    s_dict = spikefn.alpha_feed_verify(s_dict, p_dict)

    # Account for possible delays
    s_dict = spikefn.add_delay_times(s_dict, p_dict)

    # set number of bins (150 bins/1000ms)
    bins = 150. * (xmax - xmin) / 1000.
    hist_data = []

    # Proximal feed
    hist_data.extend(f.ax['hist'].hist(s_dict['alpha_feed_prox'].spike_list,
                                       bins,
                                       range=[xmin, xmax],
                                       color='red',
                                       label='Proximal feed')[0])

    # Distal feed
    hist_data.extend(f.ax['hist'].hist(s_dict['alpha_feed_dist'].spike_list,
                                       bins,
                                       range=[xmin, xmax],
                                       color='green',
                                       label='Distal feed')[0])

    # set hist axis props
    f.set_hist_props(hist_data)

    # axis labels
    f.ax['freqpwr'].set_xlabel('freq (Hz)')
    f.ax['freqpwr'].set_ylabel('power')
    f.ax['hist'].set_xlabel('time (ms)')
    f.ax['hist'].set_ylabel('# spikes')

    # create title
    title_str = ac.create_title(p_dict, key_types)
    f.f.suptitle(title_str)
    # title_str = [key + ': %2.1f' % p_dict[key] for key in key_types['dynamic_keys']]

    f.savepng(file_name)
    f.close()
Exemplo n.º 2
0
def pdipole_evoked_aligned(ddata):
    """ over ALL trials in ALL conditions in EACH experiment
        appears to be iteration over pdipole_exp2()
    """
    # grab the original dipole from a specific dir
    dproj = fio.return_data_dir()

    runtype = 'somethingotherthandebug'
    # runtype = 'debug'

    if runtype == 'debug':
        ddate = '2013-04-08'
        dsim = 'mubaseline-04-000'
        i_ctrl = 0
    else:
        ddate = raw_input('Short date directory? ')
        dsim = raw_input('Sim name? ')
        i_ctrl = ast.literal_eval(raw_input('Sim number: '))
    dcheck = os.path.join(dproj, ddate, dsim)

    # create a blank ddata structure
    ddata_ctrl = fio.SimulationPaths()
    dsim = ddata_ctrl.read_sim(dproj, dcheck)

    # find the mu_low and mu_high in the expmtgroup names
    # this means the group names must be well formed
    for expmt_group in ddata_ctrl.expmt_groups:
        if 'mu_low' in expmt_group:
            mu_low_group = expmt_group
        elif 'mu_high' in expmt_group:
            mu_high_group = expmt_group

    # choose the first [0] from the list of the file matches for mu_low
    fdpl_mu_low = ddata_ctrl.file_match(mu_low_group, 'rawdpl')[i_ctrl]
    fparam_mu_low = ddata_ctrl.file_match(mu_low_group, 'param')[i_ctrl]
    fspk_mu_low = ddata_ctrl.file_match(mu_low_group, 'rawspk')[i_ctrl]
    fspec_mu_low = ddata_ctrl.file_match(mu_low_group, 'rawspec')[i_ctrl]

    # choose the first [0] from the list of the file matches for mu_high
    fdpl_mu_high = ddata_ctrl.file_match(mu_high_group, 'rawdpl')[i_ctrl]
    fparam_mu_high = ddata_ctrl.file_match(mu_high_group, 'param')[i_ctrl]

    # grab the relevant dipole and renormalize it for mu_low
    dpl_mu_low = Dipole(fdpl_mu_low)
    dpl_mu_low.baseline_renormalize(fparam_mu_low)

    # grab the relevant dipole and renormalize it for mu_high
    dpl_mu_high = Dipole(fdpl_mu_high)
    dpl_mu_high.baseline_renormalize(fparam_mu_high)

    # input feed information
    s = spikefn.spikes_from_file(fparam_mu_low, fspk_mu_low)
    _, p_ctrl = paramrw.read(fparam_mu_low)
    s = spikefn.alpha_feed_verify(s, p_ctrl)
    s = spikefn.add_delay_times(s, p_ctrl)

    # find tstop, assume same over all. grab the first param file, get the tstop
    tstop = paramrw.find_param(fparam_mu_low, 'tstop')

    # hard coded bin count for now
    n_bins = spikefn.bin_count(150., tstop)

    # sim_prefix
    fprefix = ddata.sim_prefix

    # create the figure name
    fname_exp = '%s_dpl_align' % (fprefix)
    fname_exp_fig = os.path.join(ddata.dsim, fname_exp + '.png')

    # create one figure comparing across all
    N_expmt_groups = len(ddata.expmt_groups)
    ax_handles = [
        'spec',
        'input',
        'dpl_mu',
        'spk',
    ]
    f_exp = ac.FigDipoleExp(ax_handles)

    # plot the ctrl dipoles
    f_exp.ax['dpl_mu'].plot(dpl_mu_low.t, dpl_mu_low.dpl, color='k')
    f_exp.ax['dpl_mu'].hold(True)
    f_exp.ax['dpl_mu'].plot(dpl_mu_high.t, dpl_mu_high.dpl)

    # function creates an f_exp.ax_twinx list and returns the index of the new feed
    f_exp.create_axis_twinx('input')

    # input hist information: predicated on the fact that the input histograms
    # should be identical for *all* of the inputs represented in this figure
    # places 2 histograms on two axes (meant to be one axis flipped)
    hists = spikefn.pinput_hist(f_exp.ax['input'], f_exp.ax_twinx['input'], s['alpha_feed_prox'].spike_list, s['alpha_feed_dist'].spike_list, n_bins)

    # grab the max counts for both hists
    # the [0] item of hist are the counts
    max_hist = np.max([np.max(hists[key][0]) for key in hists.keys()])
    ymax = 2 * max_hist

    # plot the spec here
    pc = specfn.pspec_ax(f_exp.ax['spec'], fspec_mu_low)

    # deal with the axes here
    f_exp.ax['input'].set_ylim((0, ymax))
    f_exp.ax_twinx['input'].set_ylim((ymax, 0))
    # f_exp.ax[1].set_ylim((0, ymax))

    # f_exp.ax[1].set_xlim((50., tstop))

    # turn hold on
    f_exp.ax[dpl_mu].hold(True)

    # empty list for the aggregate dipole data
    dpl_exp = []

    # go through each expmt
    # calculation is extremely redundant
    for expmt_group in ddata.expmt_groups:
        # a little sloppy, just find the param file
        # this param file was for the baseline renormalization and
        # assumes it's the same in all for this expmt_group
        # also for getting the gid_dict, also assumed to be the same
        fparam = ddata.file_match(expmt_group, 'param')[0]

        # general check to see if the aggregate dipole data exists
        if 'mu_low' in expmt_group or 'mu_high' in expmt_group:
            # check to see if these files exist
            flist = ddata.find_aggregate_file(expmt_group, 'dpl')

            # if no file exists, then find one
            if not len(flist):
                calc_aggregate_dipole(ddata)
                flist = ddata.find_aggregate_file(expmt_group, 'dpl')

            # testing the first file
            list_spk = ddata.file_match(expmt_group, 'rawspk')
            list_s_dict = [spikefn.spikes_from_file(fparam, fspk) for fspk in list_spk]
            list_evoked = [s_dict['evprox0'].spike_list[0][0] for s_dict in list_s_dict]
            lines_spk = [f_exp.ax['dpl_mu'].axvline(x=x_val, linewidth=0.5, color='r') for x_val in list_evoked]
            lines_spk = [f_exp.ax['spk'].axvline(x=x_val, linewidth=0.5, color='r') for x_val in list_evoked]

        # handle mu_low and mu_high separately
        if 'mu_low' in expmt_group:
            dpl_mu_low_ev = Dipole(flist[0])
            dpl_mu_low_ev.baseline_renormalize(fparam)
            f_exp.ax['spk'].plot(dpl_mu_low_ev.t, dpl_mu_low_ev.dpl, color='k')

            # get xlim stuff
            t0 = dpl_mu_low_ev.t[0]
            T = dpl_mu_low_ev.t[-1]

        elif 'mu_high' in expmt_group:
            dpl_mu_high_ev = Dipole(flist[0])
            dpl_mu_high_ev.baseline_renormalize(fparam)
            f_exp.ax['spk'].plot(dpl_mu_high_ev.t, dpl_mu_high_ev.dpl, color='b')

    f_exp.ax['input'].set_xlim(50., tstop)

    for ax_name in f_exp.ax_handles[2:]:
        ax.set_xlim((t0, T))

    f_exp.savepng(fname_exp_fig)
    f_exp.close()
Exemplo n.º 3
0
def calc_avgdpl_stimevoked(ddata):
    for expmt_group in ddata.expmt_groups:
        # create the filename
        dexp = ddata.dexpmt_dict[expmt_group]
        fname_short = '%s-%s-dpl' % (ddata.sim_prefix, expmt_group)
        fname_data = os.path.join(dexp, fname_short + '.txt')

        # grab the list of raw data dipoles and assoc params in this expmt
        fdpl_list = ddata.file_match(expmt_group, 'rawdpl')
        param_list = ddata.file_match(expmt_group, 'param')
        spk_list = ddata.file_match(expmt_group, 'rawspk')

        # actual list of Dipole() objects
        dpl_list = [Dipole(fdpl) for fdpl in fdpl_list]
        t_truncated = []

        # iterate through the lists, grab the spike time, phase align the signals,
        # cut them to length, and then mean the dipoles
        for dpl, f_spk, f_param in zip(dpl_list, spk_list, param_list):
            _, p = paramrw.read(f_param)

            # grab the corresponding relevant starting spike time
            s = spikefn.spikes_from_file(f_param, f_spk)
            s = spikefn.alpha_feed_verify(s, p)
            s = spikefn.add_delay_times(s, p)

            # t_evoked is the same for all of the cells in these simulations
            t_evoked = s['evprox0'].spike_list[0][0]

            # attempt to give a 50 ms buffer
            if t_evoked > 50.:
                t0 = t_evoked - 50.
            else:
                t0 = t_evoked

            # truncate the dipole related vectors
            dpl.t = dpl.t[dpl.t > t0]
            dpl.dpl['agg'] = dpl.dpl['agg'][dpl.t > t0]
            t_truncated.append(dpl.t[0])

        # find the t0_max value to compare on other dipoles
        t_truncated -= np.max(t_truncated)

        for dpl, t_adj in zip(dpl_list, t_truncated):
            # negative numbers mean that this vector needs to be shortened by that many ms
            T_new = dpl.t[-1] + t_adj
            dpl.dpl['agg'] = dpl.dpl['agg'][dpl.t < T_new]
            dpl.t = dpl.t[dpl.t < T_new]

            if dpl is dpl_list[0]:
                dpl_total = dpl.dpl['agg']

            else:
                dpl_total += dpl.dpl['agg']

        dpl_mean = dpl_total / len(dpl_list)
        t_dpl = dpl_list[0].t

        # write this data to the file
        with open(fname_data, 'w') as f:
            for t, x in zip(t_dpl, dpl_mean):
                f.write("%03.3f\t%5.4f\n" % (t, x))
Exemplo n.º 4
0
def aggregate_with_hist(f, ax, f_spec, f_dpl, f_spk, f_param):
    # load param dict
    _, p_dict = paramrw.read(f_param)

    # load spec data from file
    spec = specfn.Spec(f_spec)
    # data_spec = np.load(f_spec)

    # timevec = data_spec['time']
    # freqvec = data_spec['freq']
    # TFR = data_spec['TFR']

    xmin = timevec[0]
    xmax = p_dict['tstop']
    x = (xmin, xmax)

    pc = spec.plot_TFR(ax['spec'], layer='agg', xlim=x)
    # pc = ax['spec'].imshow(TFR, extent=[timevec[0], timevec[-1], freqvec[-1], freqvec[0]], aspect='auto', origin='upper')
    f.f.colorbar(pc,
                 ax=ax['spec'],
                 norm=plt.colors.Normalize(vmin=0, vmax=90000),
                 cmap=plt.get_cmap('jet'))

    # grab the dipole data
    dpl = dipolefn.Dipole(f_dpl)
    dpl.plot(ax['dipole'], x, layer='agg')
    # data_dipole = np.loadtxt(open(f_dpl, 'r'))

    # t_dpl = data_dipole[xmin/p_dict['dt']:, 0]
    # dp_total = data_dipole[xmin/p_dict['dt']:, 1]

    # ax['dipole'].plot(t_dpl, dp_total)

    # grab alpha feed data. spikes_from_file() from spikefn.py
    s_dict = spikefn.spikes_from_file(f_param, f_spk)

    # check for existance of alpha feed keys in s_dict.
    s_dict = spikefn.alpha_feed_verify(s_dict, p_dict)

    # Account for possible delays
    s_dict = spikefn.add_delay_times(s_dict, p_dict)

    # set number of bins (150 bins/1000ms)
    bins = 150. * (xmax - xmin) / 1000.

    hist = {}

    # Proximal feed
    hist['feed_prox'] = ax['feed_prox'].hist(
        s_dict['alpha_feed_prox'].spike_list,
        bins,
        range=[xmin, xmax],
        color='red',
        label='Proximal feed')

    # Distal feed
    hist['feed_dist'] = ax['feed_dist'].hist(
        s_dict['alpha_feed_dist'].spike_list,
        bins,
        range=[xmin, xmax],
        color='green',
        label='Distal feed')

    # for now, set the xlim for the other one, force it!
    ax['dipole'].set_xlim(x)
    ax['spec'].set_xlim(x)
    ax['feed_prox'].set_xlim(x)
    ax['feed_dist'].set_xlim(x)

    # set hist axis props
    f.set_hist_props(ax, hist)

    # axis labels
    ax['spec'].set_xlabel('Time (ms)')
    ax['spec'].set_ylabel('Frequency (Hz)')

    # Add legend to histogram
    for key in ax.keys():
        if 'feed' in key:
            ax[key].legend()