예제 #1
0
def runsim():
    t0 = time.time()  # clock start time

    pc.set_maxstep(
        10)  # sets the default max solver step in ms (purposefully large)

    for elec in lelec:
        elec.setup()
        elec.LFPinit()

    h.finitialize(
    )  # initialize cells to -65 mV, after all the NetCon delays have been specified
    if pcID == 0:
        for tt in range(0, int(h.tstop), printdt):
            h.cvode.event(tt, prsimtime)  # print time callbacks

    h.fcurrent()
    h.frecord_init(
    )  # set state variables if they have been changed since h.finitialize
    pc.psolve(h.tstop)  # actual simulation - run the solver
    pc.barrier()

    # these calls aggregate data across procs/nodes
    pc.allreduce(dp_rec_L2, 1)
    pc.allreduce(
        dp_rec_L5,
        1)  # combine dp_rec on every node, 1=add contributions together
    for elec in lelec:
        elec.lfp_final()
    net.aggregate_currents(
    )  # aggregate the currents independently on each proc
    # combine net.current{} variables on each proc
    pc.allreduce(net.current['L5Pyr_soma'], 1)
    pc.allreduce(net.current['L2Pyr_soma'], 1)

    pc.barrier()

    # write time and calculated dipole to data file only if on the first proc
    # only execute this statement on one proc
    savedat(p, pcID, t_vec, dp_rec_L2, dp_rec_L5, net)

    for elec in lelec:
        print('end; t_vec.size()', t_vec.size(), 'elec.lfp_t.size()',
              elec.lfp_t.size())

    if pcID == 0:
        if debug: print("Simulation run time: %4.4f s" % (time.time() - t0))
        if debug: print("Simulation directory is: %s" % ddir.dsim)
        if paramrw.find_param(doutf['file_param'],
                              'save_spec_data') or usingOngoingInputs(
                                  doutf['file_param']):
            runanalysis(p, doutf['file_param'], doutf['file_dpl_norm'],
                        doutf['file_spec'])  # run spectral analysis
        if paramrw.find_param(doutf['file_param'], 'save_figs'):
            savefigs(ddir, p, p_exp)  # save output figures

    pc.barrier()  # make sure all done in case multiple trials
예제 #2
0
def exec_show_dpl_max(ddata, opts={}):
    p = {
        'layer': 'L5',
        'n_sim': 0,
        'n_trial': 0,
    }
    args_check(p, opts)

    expmt_group = ddata.expmt_groups[0]

    n = p['n_sim'] + p['n_sim']*p['n_trial']

    fdpl = ddata.file_match(expmt_group, 'rawdpl')[n]
    fparam = ddata.file_match(expmt_group, 'param')[n]

    T = paramrw.find_param(fparam, 'tstop')
    xlim = (50., T)

    dpl = dipolefn.Dipole(fdpl)
    dpl.baseline_renormalize(fparam)
    dpl.convert_fAm_to_nAm()

    # add this data to the dict for the string output mapping
    p['dpl_max'] = dpl.lim(p['layer'], xlim)[1]
    p['units'] = dpl.units

    print "The maximal value for the dipole is %(dpl_max)4.3f %(units)s for sim=%(n_sim)i, trial=%(n_trial)i in layer %(layer)s" % (p)
예제 #3
0
def savedat(p, rank, t_vec, dp_rec_L2, dp_rec_L5, net):
    global doutf
    # write time and calculated dipole to data file only if on the first proc
    # only execute this statement on one proc
    if rank == 0:
        # write params to the file
        paramrw.write(doutf['file_param'], p, net.gid_dict)
        # write the raw dipole
        with open(doutf['file_dpl'], 'w') as f:
            for k in range(int(t_vec.size())):
                f.write("%03.3f\t" % t_vec.x[k])
                f.write("%5.4f\t" % (dp_rec_L2.x[k] + dp_rec_L5.x[k]))
                f.write("%5.4f\t" % dp_rec_L2.x[k])
                f.write("%5.4f\n" % dp_rec_L5.x[k])
        # renormalize the dipole and save
        dpl = Dipole(
            doutf['file_dpl'])  # fix to allow init from data rather than file
        dpl.baseline_renormalize(doutf['file_param'])
        dpl.convert_fAm_to_nAm()
        dconf['dipole_scalefctr'] = dpl.scale(
            paramrw.find_param(doutf['file_param'], 'dipole_scalefctr'))
        dpl.smooth(
            paramrw.find_param(doutf['file_param'], 'dipole_smooth_win') /
            h.dt)
        dpl.write(doutf['file_dpl_norm'])
        # write the somatic current to the file
        # for now does not write the total but just L2 somatic and L5 somatic
        with open(doutf['file_current'], 'w') as fc:
            for t, i_L2, i_L5 in zip(t_vec.x, net.current['L2Pyr_soma'].x,
                                     net.current['L5Pyr_soma'].x):
                fc.write("%03.3f\t" % t)
                # fc.write("%5.4f\t" % (i_L2 + i_L5))
                fc.write("%5.4f\t" % i_L2)
                fc.write("%5.4f\n" % i_L5)
    # write output spikes
    file_spikes_tmp = fio.file_spike_tmp(dproj)
    spikes_write(net, file_spikes_tmp)
    # move the spike file to the spike dir
    if rank == 0: shutil.move(file_spikes_tmp, doutf['file_spikes'])
    if p['save_vsoma']: save_volt()
    if p['save_cai']: save_cai()
    if p['save_ica']: save_ica()
    for i, elec in enumerate(lelec):
        elec.lfpout(fn=doutf['file_lfp'].split('.txt')[0] + '_' + str(i) +
                    '.txt',
                    tvec=t_vec)
예제 #4
0
 def baseline_renormalize(self, f_param):
     # only baseline renormalize if the units are fAm
     if self.units == 'fAm':
         N_pyr_x = paramrw.find_param(f_param, 'N_pyr_x')
         N_pyr_y = paramrw.find_param(f_param, 'N_pyr_y')
         # N_pyr cells in grid. This is PER LAYER
         N_pyr = N_pyr_x * N_pyr_y
         # dipole offset calculation: increasing number of pyr cells (L2 and L5, simultaneously)
         # with no inputs resulted in an aggregate dipole over the interval [50., 1000.] ms that
         # eventually plateaus at -48 fAm. The range over this interval is something like 3 fAm
         # so the resultant correction is here, per dipole
         # dpl_offset = N_pyr * 50.207
         dpl_offset = {
             # these values will be subtracted
             'L2': N_pyr * 0.0443,
             'L5': N_pyr * -49.0502
             # 'L5': N_pyr * -48.3642,
             # will be calculated next, this is a placeholder
             # 'agg': None,
         }
         # L2 dipole offset can be roughly baseline shifted over the entire range of t
         self.dpl['L2'] -= dpl_offset['L2']
         # L5 dipole offset should be different for interval [50., 500.] and then it can be offset
         # slope (m) and intercept (b) params for L5 dipole offset
         # uncorrected for N_cells
         # these values were fit over the range [37., 750.)
         m = 3.4770508e-3
         b = -51.231085
         # these values were fit over the range [750., 5000]
         t1 = 750.
         m1 = 1.01e-4
         b1 = -48.412078
         # piecewise normalization
         self.dpl['L5'][self.t <= 37.] -= dpl_offset['L5']
         self.dpl['L5'][(self.t > 37.)
                        & (self.t < t1)] -= N_pyr * (m * self.t[
                            (self.t > 37.) & (self.t < t1)] + b)
         self.dpl['L5'][
             self.t >= t1] -= N_pyr * (m1 * self.t[self.t >= t1] + b1)
         # recalculate the aggregate dipole based on the baseline normalized ones
         self.dpl['agg'] = self.dpl['L2'] + self.dpl['L5']
     else:
         print(
             "Warning, no dipole renormalization done because units were in %s"
             % (self.units))
예제 #5
0
def pdipole_grid(ddata):
    # iterate through expmt_groups
    for expmt_group in ddata.expmt_groups:
        fname_short = "%s-%s-dpl.png" % (ddata.sim_prefix, expmt_group)
        fname = os.path.join(ddata.dsim, expmt_group, fname_short)

        # simple usage, just checks how many dipole files (total in an expmt)
        # and then plots dumbly to a grid
        dpl_list = ddata.file_match(expmt_group, 'rawdpl')
        param_list = ddata.file_match(expmt_group, 'param')

        # assume tstop is the same everywhere
        tstop = paramrw.find_param(param_list[0], 'tstop')

        # length of the dpl list
        N_dpl = len(dpl_list)

        # make a 5-col figure
        N_cols = 5

        # force int arithmetic
        # this is the BASE number of rows, one might be added!
        N_rows = int(N_dpl) // int(N_cols)

        # if the mod is not 0, add a row
        if (N_dpl % N_cols):
            N_rows += 1

        # print(N_dpl, N_cols, N_rows)
        f = ac.FigGrid(N_rows, N_cols, tstop)

        l = []
        r = 0
        for ax_list in f.ax:
            l.extend([(r,c) for c in range(len(ax_list))])
            r += 1

        # automatically truncates the loc list to the size of dpl_list
        for loc, fdpl, fparam in zip(l, dpl_list, param_list):
            r = loc[0]
            c = loc[1]
            pdipole_ax(f.ax[r][c], fdpl, fparam)

        f.savepng(fname)
        f.close()
예제 #6
0
def exec_welch_max(ddata, opts):
    p = {
        'f_min': 0.,
    }

    args_check(p, opts)

    # assume first expmt_group for now
    expmt_group = ddata.expmt_groups[0]

    # grab list of dipoles
    list_dpl = ddata.file_match(expmt_group, 'rawdpl')
    list_param = ddata.file_match(expmt_group, 'param')

    # iterate through dipoles
    for fdpl, fparam in zip(list_dpl, list_param):
        # grab the dt (needed for the Welch)
        dt = paramrw.find_param(fparam, 'dt')

        # grab the dipole
        dpl = dipolefn.Dipole(fdpl)
        dpl.baseline_renormalize(fparam)
        dpl.convert_fAm_to_nAm()

        # create empty pgram
        pgram = dict.fromkeys(dpl.dpl)
        pgram_max = dict.fromkeys(dpl.dpl)

        # perform stationary Welch, since we're not saving this data yet
        for key in pgram.keys():
            pgram[key] = specfn.Welch(dpl.t, dpl.dpl[key], dt)

            # create a mask based on f min
            fmask = (pgram[key].f > p['f_min'])
            P_cut = pgram[key].P[fmask]
            f_cut = pgram[key].f[fmask]

            p_max = np.max(P_cut)
            f_max = f_cut[P_cut == p_max]
            # p_max = np.max(pgram[key].P)
            # f_max = pgram[key].f[pgram[key].P == p_max]

            # not clear why saving for now
            pgram_max[key] = (f_max, p_max)
            print "Max power for %s was %.3e at %4.2f Hz, with f min set to %4.2f" % (key, p_max, f_max, p['f_min'])
예제 #7
0
파일: simdat.py 프로젝트: nrnhines/hnn
  def setupaxdipole (self):
    dinty = self.getInputs()

    # whether to draw the specgram - should draw if user saved it or have ongoing, poisson, or tonic inputs
    DrawSpec = False
    try:
      DrawSpec = find_param(dfile['outparam'],'save_spec_data') or OngoingInputs or PoissonInputs or TonicInputs
    except:
      pass

    gRow = 0

    if dinty['Ongoing'] or dinty['Evoked']: gRow = 2

    if DrawSpec: # dipole axis takes fewer rows if also drawing specgram
      self.axdipole = ax = self.figure.add_subplot(self.G[gRow:5,0]); # dipole
    else:
      self.axdipole = ax = self.figure.add_subplot(self.G[gRow:-1,0]); # dipole
예제 #8
0
파일: simdat.py 프로젝트: ramcdougal/hnn
    def plotsimdat(self):

        if not updatedat(self.paramf):
            return  # if no data from sim, or data load problem return

        self.clearaxes()
        plt.close(self.figure)
        if len(ddat.keys()) == 0: return

        dinty = self.getInputs(
        )  # get dict of input types used (influences which/how plots drawn)

        # whether to draw the specgram - should draw if user saved it or have ongoing, poisson, or tonic inputs
        DrawSpec = find_param(
            dfile['outparam'], 'save_spec_data'
        ) or dinty['Ongoing'] or dinty['Poisson'] or dinty['Tonic']
        try:
            ds = None
            xl = (0, find_param(dfile['outparam'], 'tstop'))
            dt = find_param(dfile['outparam'], 'dt')

            # get spectrogram if it exists, then adjust axis limits but only if drawing spectrogram
            if DrawSpec and 'spec' in ddat:
                if ddat['spec'] is not None:
                    ds = ddat['spec']  # spectrogram
                    xl = (ds['time'][0], ds['time'][-1]
                          )  # use specgram time limits

            gRow = 0

            sampr = 1e3 / dt  # dipole sampling rate
            sidx, eidx = int(sampr * xl[0] / 1e3), int(
                sampr * xl[1] /
                1e3)  # use these indices to find dipole min,max

            if dinty['Ongoing'] or dinty['Evoked'] or dinty['Poisson']:
                xo = self.plotinputhist(xl, dinty)
                if xo: gRow = xo[1]

            if DrawSpec:  # dipole axis takes fewer rows if also drawing specgram
                self.axdipole = ax = self.figure.add_subplot(self.G[gRow:5, 0])
                # dipole
                self.lax.append(ax)
            else:
                self.axdipole = ax = self.figure.add_subplot(self.G[gRow:-1,
                                                                    0])
                # dipole
                self.lax.append(ax)

            N_trials = self.getNTrials()
            if debug: print('simdat: N_trials:', N_trials)

            yl = [
                np.amin(ddat['dpl'][sidx:eidx, 1]),
                np.amax(ddat['dpl'][sidx:eidx, 1])
            ]

            if N_trials > 1 and dconf['drawindivdpl'] and len(
                    ddat['dpltrials']
            ) > 0:  # plot dipoles from individual trials
                for dpltrial in ddat['dpltrials']:
                    ax.plot(dpltrial[:, 0],
                            dpltrial[:, 1],
                            color='gray',
                            linewidth=self.gui.linewidth)
                    yl[0] = min(yl[0], dpltrial[sidx:eidx, 1].min())
                    yl[1] = max(yl[1], dpltrial[sidx:eidx, 1].max())

            if dinty['Evoked']:
                self.drawEVInputTimes(ax, yl, 0.1,
                                      (xl[1] - xl[0]) * .02)  #15.0)
            #if dinty['Evoked']: self.drawEVInputTimes(ax,yl,0.1,15.0)

            if conf.dconf['drawavgdpl'] or N_trials <= 1:
                # this is the average dipole (across trials)
                # it's also the ONLY dipole when running a single trial
                ax.plot(ddat['dpl'][:, 0],
                        ddat['dpl'][:, 1],
                        'k',
                        linewidth=self.gui.linewidth + 2)

            scalefctr = getscalefctr(self.paramf)
            NEstPyr = int(self.getNPyr() * scalefctr)

            if NEstPyr > 0:
                ax.set_ylabel(r'Dipole (nAm $\times$ ' + str(scalefctr) +
                              ')\nFrom Estimated ' + str(NEstPyr) + ' Cells',
                              fontsize=dconf['fontsize'])
            else:
                ax.set_ylabel(r'Dipole (nAm $\times$ ' + str(scalefctr) +
                              ')\n',
                              fontsize=dconf['fontsize'])
            ax.set_xlim(xl)
            ax.set_ylim(yl)

            if DrawSpec:  #
                if debug:
                    print('ylim is : ', np.amin(ddat['dpl'][sidx:eidx, 1]),
                          np.amax(ddat['dpl'][sidx:eidx, 1]))
                gRow = 6
                self.axspec = ax = self.figure.add_subplot(self.G[gRow:10, 0])
                # specgram
                self.lax.append(ax)
                cax = ax.imshow(ds['TFR'],
                                extent=(ds['time'][0], ds['time'][-1],
                                        ds['freq'][-1], ds['freq'][0]),
                                aspect='auto',
                                origin='upper',
                                cmap=plt.get_cmap('jet'))
                ax.set_ylabel('Frequency (Hz)', fontsize=dconf['fontsize'])
                ax.set_xlabel('Time (ms)', fontsize=dconf['fontsize'])
                ax.set_xlim(xl)
                ax.set_ylim(ds['freq'][-1], ds['freq'][0])
                cbaxes = self.figure.add_axes([0.6, 0.49, 0.3, 0.005])
                cb = plt.colorbar(
                    cax, cax=cbaxes,
                    orientation='horizontal')  # horizontal to save space
                for ax in self.lax:
                    if ax: ax.set_xlim(xl)
        except:
            print('ERR: in plotsimdat')
        self.figure.subplots_adjust(left=0.07,
                                    right=0.99,
                                    bottom=0.08,
                                    top=0.99,
                                    hspace=0.1,
                                    wspace=0.1)  # reduce padding
예제 #9
0
from conf import dconf

if dconf['fontsize'] > 0: plt.rcParams['font.size'] = dconf['fontsize']
else: dconf['fontsize'] = 10

tstop = -1
ntrial = 1
scalefctr = 30e3
dplpath = ''
paramf = ''
for i in range(len(sys.argv)):
    if sys.argv[i].endswith('.txt'):
        dplpath = sys.argv[i]
    elif sys.argv[i].endswith('.param'):
        paramf = sys.argv[i]
        scalefctr = paramrw.find_param(paramf, 'dipole_scalefctr')
        if type(scalefctr) != float and type(scalefctr) != int:
            scalefctr = 30e3
        tstop = paramrw.find_param(paramf, 'tstop')
        ntrial = paramrw.quickgetprm(paramf, 'N_trials', int)

basedir = os.path.join(dconf['datdir'],
                       paramf.split(os.path.sep)[-1].split('.param')[0])

ddat = {}
ddat['dpltrials'] = readdpltrials(basedir, ntrial)
try:
    ddat['dpl'] = np.loadtxt(os.path.join(basedir, 'dpl.txt'))
except:
    print('Could not load', dplpath)
    quit()
예제 #10
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()
예제 #11
0
def pkernel(dfig_dpl, f_dpl, f_spk, f_spec, f_current, f_spec_current, f_param, ax_handles, spec_cmap='jet'):
    T = paramrw.find_param(f_param, 'tstop')
    xlim = (50., T)

    # into the pdipole directory, this will plot dipole, spec, and spikes
    # create the axis handle
    f = ac.FigDipoleExp(ax_handles)

    # create the figure name
    fprefix = fio.strip_extprefix(f_dpl) + '-dpl'
    fname = os.path.join(dfig_dpl, fprefix + '.png')

    # grab the dipole
    dpl = dipolefn.Dipole(f_dpl)
    dpl.convert_fAm_to_nAm()

    # plot the dipole to the agg axes
    dpl.plot(f.ax['dpl_agg'], xlim)
    dpl.plot(f.ax['dpl_agg_L5'], xlim)
    # f.ax['dpl_agg_L5'].hold(True)
    # dpl.plot(f.ax['dpl_agg_L5'], xlim, 'L5')

    # plot individual dipoles
    dpl.plot(f.ax['dpl'], xlim, 'L2')
    dpl.plot(f.ax['dpl_L5'], xlim, 'L5')

    # f.ysymmetry(f.ax['dpl'])
    # print dpl.max('L5', (0., -1)), dpl.max('L5', (50., -1))
    # print f.ax['dpl_L5'].get_ylim()
    # f.ax['dpl_L5'].set_ylim((-1e5, 1e5))
    # f.ysymmetry(f.ax['dpl_L5'])

    # plot the current
    I_soma = currentfn.SynapticCurrent(f_current)
    I_soma.plot_to_axis(f.ax['I_soma'], 'L2')
    I_soma.plot_to_axis(f.ax['I_soma_L5'], 'L5')

    # plot the dipole-based spec data
    pc = specfn.pspec_ax(f.ax['spec_dpl'], f_spec, xlim, 'L2')
    f.f.colorbar(pc, ax=f.ax['spec_dpl'])

    pc = specfn.pspec_ax(f.ax['spec_dpl_L5'], f_spec, xlim, 'L5')
    f.f.colorbar(pc, ax=f.ax['spec_dpl_L5'])

    # grab the current spec and plot them
    spec_L2, spec_L5 = data_spec_current = specfn.read(f_spec_current, type='current')
    pc_L2 = f.ax['spec_I'].imshow(spec_L2['TFR'], aspect='auto', origin='upper',cmap=plt.get_cmap(spec_cmap))
    pc_L5 = f.ax['spec_I_L5'].imshow(spec_L5['TFR'], aspect='auto', origin='upper',cmap=plt.get_cmap(spec_cmap))

    # plot the current-based spec data
    # pci = specfn.pspec_ax(f.ax['spec_I'], f_spec_current, type='current')
    f.f.colorbar(pc_L2, ax=f.ax['spec_I'])
    f.f.colorbar(pc_L5, ax=f.ax['spec_I_L5'])

    # get all spikes
    s = spikefn.spikes_from_file(f_param, f_spk)

    # these work primarily because of how the keys are done
    # in the spike dict s (consequence of spikefn.spikes_from_file())
    s_L2 = spikefn.filter_spike_dict(s, 'L2_')
    s_L5 = spikefn.filter_spike_dict(s, 'L5_')

    # resize xlim based on our 50 ms cutoff thingy
    xlim = (50., xlim[1])

    # plot the spikes
    spikefn.spike_png(f.ax['spk'], s_L2)
    spikefn.spike_png(f.ax['spk_L5'], s_L5)

    f.ax['dpl'].set_xlim(xlim)
    # f.ax['dpl_L5'].set_xlim(xlim)
    # f.ax['spec_dpl'].set_xlim(xlim)
    f.ax['spk'].set_xlim(xlim)
    f.ax['spk_L5'].set_xlim(xlim)

    f.savepng(fname)
    f.close()

    return 0
예제 #12
0
파일: simdat.py 프로젝트: tbardouille/hnn
  def plotsimdat (self):
    # plot the simulation data

    self.gRow = 0
    bottom = 0.0

    only_create_axes = False
    if not os.path.isfile(self.paramf):
      only_create_axes = True
      DrawSpec = False
      xl = (0.0, 1.0)
    else:
      # setup the figure axis for drawing the dipole signal
      dinty = self.getInputs()

      # try loading data. ignore failures
      try:
        updatedat(self.paramf)
        loaded_dat = True
      except ValueError:
        loaded_dat = False
        pass

      xl = (0.0, quickgetprm(self.paramf,'tstop',float))
      if dinty['Ongoing'] or dinty['Evoked'] or dinty['Poisson']:
        xo = self.plotinputhist(xl, dinty)
        if xo:
          self.gRow = xo[1]

      # whether to draw the specgram - should draw if user saved it or have ongoing, poisson, or tonic inputs
      DrawSpec = loaded_dat and \
                'spec' in ddat and \
                (find_param(dfile['outparam'],'save_spec_data') or dinty['Ongoing'] or dinty['Poisson'] or dinty['Tonic'])

    if DrawSpec: # dipole axis takes fewer rows if also drawing specgram
      self.axdipole = self.figure.add_subplot(self.G[self.gRow:5,0]) # dipole
      bottom = 0.08
    else:
      self.axdipole = self.figure.add_subplot(self.G[self.gRow:-1,0]) # dipole

    yl = (-0.001,0.001)
    self.axdipole.set_ylim(yl)
    self.axdipole.set_xlim(xl)

    left = 0.08
    w,h=getscreengeom()
    if w < 2800: left = 0.1
    self.figure.subplots_adjust(left=left,right=0.99,bottom=bottom,top=0.99,hspace=0.1,wspace=0.1) # reduce padding

    if only_create_axes:
      return

    try:
      updatedat(self.paramf)
    except ValueError:
      if 'dpl' not in ddat:
        # failed to load dipole data, nothing more to plot
        return

    ds = None
    xl = (0,ddat['dpl'][-1,0])
    dt = ddat['dpl'][1,0] - ddat['dpl'][0,0]

    # get spectrogram if it exists, then adjust axis limits but only if drawing spectrogram
    if DrawSpec:
      if ddat['spec'] is not None:
        ds = ddat['spec'] # spectrogram
        xl = (ds['time'][0],ds['time'][-1]) # use specgram time limits
      else:
        DrawSpec = False

    sampr = 1e3/dt # dipole sampling rate
    sidx, eidx = int(sampr*xl[0]/1e3), int(sampr*xl[1]/1e3) # use these indices to find dipole min,max

    N_trials = self.getNTrials()
    if debug: print('simdat: N_trials:',N_trials)

    yl = [0,0]
    yl[0] = min(yl[0],np.amin(ddat['dpl'][sidx:eidx,1]))
    yl[1] = max(yl[1],np.amax(ddat['dpl'][sidx:eidx,1]))

    if not self.optMode:
      # skip for optimization
      for lsim in lsimdat: # plot average dipoles from prior simulations
        olddpl = lsim[1]
        if debug: print('olddpl has shape ',olddpl.shape,len(olddpl[:,0]),len(olddpl[:,1]))
        self.axdipole.plot(olddpl[:,0],olddpl[:,1],'--',color='black',linewidth=self.gui.linewidth)

      if N_trials>1 and dconf['drawindivdpl'] and len(ddat['dpltrials']) > 0: # plot dipoles from individual trials
        for dpltrial in ddat['dpltrials']:
          self.axdipole.plot(dpltrial[:,0],dpltrial[:,1],color='gray',linewidth=self.gui.linewidth)
          yl[0] = min(yl[0],dpltrial[sidx:eidx,1].min())
          yl[1] = max(yl[1],dpltrial[sidx:eidx,1].max())

      if conf.dconf['drawavgdpl'] or N_trials <= 1:
        # this is the average dipole (across trials)
        # it's also the ONLY dipole when running a single trial
        self.axdipole.plot(ddat['dpl'][:,0],ddat['dpl'][:,1],'k',linewidth=self.gui.linewidth+1)
        yl[0] = min(yl[0],ddat['dpl'][sidx:eidx,1].min())
        yl[1] = max(yl[1],ddat['dpl'][sidx:eidx,1].max())
    else:
      for idx, opt in enumerate(optdat):
        optdpl = opt[1]
        if idx == len(optdat) - 1:
          # only show the last optimization
          self.axdipole.plot(optdpl[:,0],optdpl[:,1],'k',color='gray',linewidth=self.gui.linewidth+1)
          yl[0] = min(yl[0],optdpl[sidx:eidx,1].min())
          yl[1] = max(yl[1],optdpl[sidx:eidx,1].max())

      if self.hasinitoptdata():
        # show initial dipole in dotted black line
        self.axdipole.plot(initial_ddat['dpl'][:,0],initial_ddat['dpl'][:,1],'--',color='black',linewidth=self.gui.linewidth)
        yl[0] = min(yl[0],initial_ddat['dpl'][sidx:eidx,1].min())
        yl[1] = max(yl[1],initial_ddat['dpl'][sidx:eidx,1].max())

    scalefctr = getscalefctr(self.paramf)
    NEstPyr = int(self.getNPyr() * scalefctr)

    if NEstPyr > 0:
      self.axdipole.set_ylabel(r'Dipole (nAm $\times$ '+str(scalefctr)+')\nFrom Estimated '+str(NEstPyr)+' Cells',fontsize=dconf['fontsize'])
    else:
      self.axdipole.set_ylabel(r'Dipole (nAm $\times$ '+str(scalefctr)+')\n',fontsize=dconf['fontsize'])
    self.axdipole.set_xlim(xl); self.axdipole.set_ylim(yl)

    if DrawSpec: #
      if debug: print('ylim is : ', np.amin(ddat['dpl'][sidx:eidx,1]),np.amax(ddat['dpl'][sidx:eidx,1]))

      p_exp = ExpParams(self.paramf, debug=debug)
      if len(p_exp.expmt_groups) > 0:
        expmt_group = p_exp.expmt_groups[0]
      else:
        expmt_group = None
      p = p_exp.return_pdict(expmt_group, 0)

      gRow = 6
      self.axspec = self.figure.add_subplot(self.G[gRow:10,0]); # specgram
      cax = self.axspec.imshow(ds['TFR'],extent=(ds['time'][0],ds['time'][-1],ds['freq'][-1],ds['freq'][0]),aspect='auto',origin='upper',cmap=plt.get_cmap(p['spec_cmap']))
      self.axspec.set_ylabel('Frequency (Hz)',fontsize=dconf['fontsize'])
      self.axspec.set_xlabel('Time (ms)',fontsize=dconf['fontsize'])
      self.axspec.set_xlim(xl)
      self.axspec.set_ylim(ds['freq'][-1],ds['freq'][0])
      cbaxes = self.figure.add_axes([0.6, 0.49, 0.3, 0.005])
      cb = plt.colorbar(cax, cax = cbaxes, orientation='horizontal') # horizontal to save space
    else:
      self.axdipole.set_xlabel('Time (ms)',fontsize=dconf['fontsize'])