Exemple #1
0
 def loadspk (self,idx):
   global haveinputs,extinputs
   if idx in alldat: return
   alldat[idx] = {}
   if idx == 0:
     try:
       extinputs = spikefn.ExtInputs(spkpath, outparamf)
     except ValueError:
       print("Error: could not load spike timings from %s" % spkpath)
       return
     extinputs.add_delay_times()
     dspk,haveinputs,dhist = getdspk(spkpath)
     alldat[idx]['dspk'] = dspk
     alldat[idx]['haveinputs'] = haveinputs
     alldat[idx]['dhist'] = dhist
     alldat[idx]['extinputs'] = extinputs
   else:
     spkpathtrial = os.path.join(dconf['datdir'],paramf.split('.param')[0].split(os.path.sep)[-1],'spk_'+str(self.index-1)+'.txt') 
     dspktrial,haveinputs,dhisttrial = getdspk(spkpathtrial) # show spikes from first trial
     try:
       extinputs = spikefn.ExtInputs(spkpathtrial, outparamf)
     except ValueError:
       print("Error: could not load spike timings from %s" % spkpath)
       return
     extinputs.add_delay_times()
     alldat[idx]['dspk'] = dspktrial
     alldat[idx]['haveinputs'] = haveinputs
     alldat[idx]['dhist'] = dhisttrial
     alldat[idx]['extinputs'] = extinputs
Exemple #2
0
def pdipole_with_hist(f_dpl, f_spk, dfig, f_param, key_types, plot_dict):
  """ this function has not been converted to use the Dipole() class yet
  """
  # dpl is an obj of Dipole() class
  dpl = Dipole(f_dpl)
  dpl.baseline_renormalize(f_param)
  dpl.convert_fAm_to_nAm()
  # split to find file prefix
  file_prefix = f_dpl.split('/')[-1].split('.')[0]
  # grabbing the p_dict from the f_param
  _, p_dict = paramrw.read(f_param)
  # get xmin and xmax from the plot_dict
  if plot_dict['xmin'] is None:
    xmin = 0.
  else:
    xmin = plot_dict['xmin']
  if plot_dict['xmax'] is None:
    xmax = p_dict['tstop']
  else:
    xmax = plot_dict['xmax']
  # truncate tvec and dpl data using logical indexing
  t_range = dpl.t[(dpl.t >= xmin) & (dpl.t <= xmax)]
  dpl_range = dpl.dpl['agg'][(dpl.t >= xmin) & (dpl.t <= xmax)]
  # Plotting
  f = ac.FigDplWithHist()
  # dipole
  f.ax['dipole'].plot(t_range, dpl_range)
  # set new xlim based on dipole plot
  xlim_new = f.ax['dipole'].get_xlim()
  # Get extinput data and account for delays
  extinputs = spikefn.ExtInputs(f_spk, f_param)
  extinputs.add_delay_times()
  # set number of bins (150 bins per 1000ms)
  bins = ceil(150. * (xlim_new[1] - xlim_new[0]) / 1000.) # bins needs to be an int
  # plot histograms
  hist = {}
  hist['feed_prox'] = extinputs.plot_hist(f.ax['feed_prox'], 'prox', dpl.t, bins, xlim_new, color='red')
  hist['feed_dist'] = extinputs.plot_hist(f.ax['feed_dist'], 'dist', dpl.t, bins, xlim_new, color='green')
  # Invert dist histogram
  f.ax['feed_dist'].invert_yaxis()
  # for now, set the xlim for the other one, force it!
  f.ax['dipole'].set_xlim(xlim_new)
  f.ax['feed_prox'].set_xlim(xlim_new)
  f.ax['feed_dist'].set_xlim(xlim_new)
  # set hist axis properties
  f.set_hist_props(hist)
  # Add legend to histogram
  for key in f.ax.keys():
    if 'feed' in key:
      f.ax[key].legend()
  # force xlim on histograms
  f.ax['feed_prox'].set_xlim((xmin, xmax))
  f.ax['feed_dist'].set_xlim((xmin, xmax))
  title_str = ac.create_title(p_dict, key_types)
  f.f.suptitle(title_str)
  fig_name = os.path.join(dfig, file_prefix+'.png')
  plt.savefig(fig_name)
  f.close()
Exemple #3
0
    def plotinputhist(self, xl, dinty):
        """ plot input histograms
        xl = x axis limits
        dinty = dict of input types used, determines how many/which axes created/displayed
    """
        xlim_new = (ddat['dpl'][0, 0], ddat['dpl'][-1, 0])
        # print('xlim_new:',xlim_new)
        # set number of bins (150 bins per 1000ms)
        bins = ceil(150. * (xlim_new[1] - xlim_new[0]) /
                    1000.)  # bins needs to be an int
        if debug: print('bins:', bins)
        extinputs = None

        try:
            if debug:
                print('dfilespk:', dfile['spk'], 'dfileoutparam',
                      dfile['outparam'])
            extinputs = spikefn.ExtInputs(dfile['spk'], dfile['outparam'])
            extinputs.add_delay_times()
            dinput = extinputs.inputs
            if len(dinput['dist']) <= 0 and len(dinput['prox']) <= 0 and \
               len(dinput['evdist']) <= 0 and len(dinput['evprox']) <= 0 and \
               len(dinput['pois']) <= 0:
                if debug: print('all hists 0!')
                return False
        except:
            print('plotinputhist ERR: problem with extinputs')
        self.hist = hist = {
            x: None
            for x in [
                'feed_dist', 'feed_prox', 'feed_evdist', 'feed_evprox',
                'feed_pois'
            ]
        }

        hasPois = len(dinput['pois']) > 0 and dinty[
            'Poisson']  # this ensures synaptic weight > 0

        gRow = 0
        axdist = axprox = axpois = None  # axis objects

        # check poisson inputs, create subplot
        if hasPois:
            self.axpois = axpois = self.figure.add_subplot(self.G[gRow, 0])
            self.lax.append(axpois)
            gRow += 1

        # check distal inputs, create subplot
        if (len(dinput['dist']) > 0 and dinty['OngoingDist']) or \
           (len(dinput['evdist']) > 0 and dinty['EvokedDist']):
            self.axdist = axdist = self.figure.add_subplot(self.G[gRow, 0])
            gRow += 1
            self.lax.append(axdist)

        # check proximal inputs, create subplot
        if (len(dinput['prox']) > 0 and dinty['OngoingProx']) or \
           (len(dinput['evprox']) > 0 and dinty['EvokedProx']):
            self.axprox = axprox = self.figure.add_subplot(self.G[gRow, 0])
            gRow += 1
            self.lax.append(axprox)

        if extinputs is not None:  # only valid param.txt file after sim was run
            if debug:
                print(len(dinput['dist']), len(dinput['prox']),
                      len(dinput['evdist']), len(dinput['evprox']),
                      len(dinput['pois']))

            if hasPois:
                hist['feed_pois'] = extinputs.plot_hist(axpois,
                                                        'pois',
                                                        ddat['dpl'][:, 0],
                                                        bins,
                                                        xlim_new,
                                                        color='k',
                                                        hty='step',
                                                        lw=self.gui.linewidth +
                                                        1)

            if len(dinput['dist']) > 0 and dinty[
                    'OngoingDist']:  # dinty condition ensures synaptic weight > 0
                hist['feed_dist'] = extinputs.plot_hist(axdist,
                                                        'dist',
                                                        ddat['dpl'][:, 0],
                                                        bins,
                                                        xlim_new,
                                                        color='g',
                                                        lw=self.gui.linewidth +
                                                        1)

            if len(dinput['prox']) > 0 and dinty[
                    'OngoingProx']:  # dinty condition ensures synaptic weight > 0
                hist['feed_prox'] = extinputs.plot_hist(axprox,
                                                        'prox',
                                                        ddat['dpl'][:, 0],
                                                        bins,
                                                        xlim_new,
                                                        color='r',
                                                        lw=self.gui.linewidth +
                                                        1)

            if len(dinput['evdist']) > 0 and dinty[
                    'EvokedDist']:  # dinty condition ensures synaptic weight > 0
                hist['feed_evdist'] = extinputs.plot_hist(
                    axdist,
                    'evdist',
                    ddat['dpl'][:, 0],
                    bins,
                    xlim_new,
                    color='g',
                    hty='step',
                    lw=self.gui.linewidth + 1)

            if len(dinput['evprox']) > 0 and dinty[
                    'EvokedProx']:  # dinty condition ensures synaptic weight > 0
                hist['feed_evprox'] = extinputs.plot_hist(
                    axprox,
                    'evprox',
                    ddat['dpl'][:, 0],
                    bins,
                    xlim_new,
                    color='r',
                    hty='step',
                    lw=self.gui.linewidth + 1)

            if hist['feed_dist'] is None and hist['feed_prox'] is None and \
               hist['feed_evdist'] is None and hist['feed_evprox'] is None and \
               hist['feed_pois'] is None:
                self.invertedhistax = False
                if debug: print('all hists None!')
                return False
            else:
                if not self.invertedhistax and axdist:  # only need to invert axis 1X
                    axdist.invert_yaxis()
                    self.invertedhistax = True
                for ax in [axpois, axdist, axprox]:
                    if ax:
                        ax.set_xlim(xlim_new)
                        ax.legend()
                return True, gRow
Exemple #4
0
ntrial = 1; tstop = -1; outparamf = spkpath = paramf = ''; EvokedInputs = OngoingInputs = PoissonInputs = False; 

for i in range(len(sys.argv)):
  if sys.argv[i].endswith('.txt'):
    spkpath = sys.argv[i]
  elif sys.argv[i].endswith('.param'):
    paramf = sys.argv[i]
    tstop = paramrw.quickgetprm(paramf,'tstop',float)
    ntrial = paramrw.quickgetprm(paramf,'N_trials',int)
    EvokedInputs = paramrw.usingEvokedInputs(paramf)
    OngoingInputs = paramrw.usingOngoingInputs(paramf)
    PoissonInputs = paramrw.usingPoissonInputs(paramf)
    outparamf = os.path.join(dconf['datdir'],paramf.split('.param')[0].split(os.path.sep)[-1],'param.txt')

try:
  extinputs = spikefn.ExtInputs(spkpath, outparamf)
except ValueError:
  print("Error: could not load spike timings from %s" % spkpath)

extinputs.add_delay_times()

alldat = {}

ncell = len(net.cells)

binsz = 5.0
smoothsz = 0 # no smoothing

bDrawHist = True # whether to draw histograms (spike counts per time)

# adjust input gids for display purposes
Exemple #5
0
def pspec_with_hist(f_spec,
                    f_dpl,
                    f_spk,
                    dfig,
                    f_param,
                    key_types,
                    xlim=None,
                    ylim=None):
    # Generate file prefix
    # print('f_spec:',f_spec)
    fprefix = f_spec.split('/')[-1].split('.')[0]
    # Create the fig name
    fig_name = os.path.join(dfig, fprefix + '.png')
    # print('fig_name:',fig_name)
    # load param dict
    _, p_dict = paramrw.read(f_param)
    f = ac.FigSpecWithHist()
    # load spec data
    spec = specfn.Spec(f_spec)
    # Plot TFR data and add colorbar
    pc = spec.plot_TFR(f.ax['spec'], 'agg', xlim, ylim)
    f.f.colorbar(pc, ax=f.ax['spec'])
    # set xlim based on TFR plot
    xlim_new = f.ax['spec'].get_xlim()
    # grab the dipole data
    dpl = dipolefn.Dipole(f_dpl)
    dpl.baseline_renormalize(f_param)
    dpl.convert_fAm_to_nAm()
    # plot routine
    dpl.plot(f.ax['dipole'], xlim_new, 'agg')
    # data_dipole = np.loadtxt(open(f_dpl, 'r'))
    # t_dpl = data_dipole[xmin_ind:xmax_ind+1, 0]
    # dp_total = data_dipole[xmin_ind:xmax_ind+1, 1]
    # f.ax['dipole'].plot(t_dpl, dp_total)
    # x = (xmin, xmax)
    # # 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)
    # Get extinput data and account for delays
    extinputs = spikefn.ExtInputs(f_spk, f_param)
    extinputs.add_delay_times()
    extinputs.get_envelope(dpl.t, feed='dist')
    # set number of bins (150 bins per 1000ms)
    bins = ceil(150. * (xlim_new[1] - xlim_new[0]) /
                1000.)  # bins should be int
    # plot histograms
    hist = {}
    hist['feed_prox'] = extinputs.plot_hist(f.ax['feed_prox'],
                                            'prox',
                                            dpl.t,
                                            bins=bins,
                                            xlim=xlim_new,
                                            color='red')
    hist['feed_dist'] = extinputs.plot_hist(f.ax['feed_dist'],
                                            'dist',
                                            dpl.t,
                                            bins=bins,
                                            xlim=xlim_new,
                                            color='green')
    f.ax['feed_dist'].invert_yaxis()
    # for now, set the xlim for the other one, force it!
    f.ax['dipole'].set_xlim(xlim_new)
    f.ax['spec'].set_xlim(xlim_new)
    f.ax['feed_prox'].set_xlim(xlim_new)
    f.ax['feed_dist'].set_xlim(xlim_new)
    # set hist axis props
    f.set_hist_props(hist)
    # axis labels
    f.ax['spec'].set_xlabel('Time (ms)')
    f.ax['spec'].set_ylabel('Frequency (Hz)')
    # Add legend to histogram
    for key in f.ax.keys():
        if 'feed' in key:
            f.ax[key].legend()
    # create title
    title_str = ac.create_title(p_dict, key_types)
    f.f.suptitle(title_str)
    f.savepng(fig_name)
    f.close()
Exemple #6
0
  def plotinputhist (self, xl, dinty):
    """ plot input histograms
        xl = x axis limits
        dinty = dict of input types used, determines how many/which axes created/displayed
    """

    extinputs = None
    plot_distribs = False

    sim_tstop = quickgetprm(self.paramf,'tstop',float)
    sim_dt = quickgetprm(self.paramf,'dt',float)
    num_step = ceil(sim_tstop / sim_dt) + 1
    times = np.linspace(0, sim_tstop, num_step)

    try:
      extinputs = spikefn.ExtInputs(dfile['spk'], dfile['outparam'])
      extinputs.add_delay_times()
      dinput = extinputs.inputs
    except ValueError:
      dinput = self.getInputDistrib()
      plot_distribs = True

    if len(dinput['dist']) <= 0 and len(dinput['prox']) <= 0 and \
        len(dinput['evdist']) <= 0 and len(dinput['evprox']) <= 0 and \
        len(dinput['pois']) <= 0:
      if debug: print('all hists 0!')
      return False

    self.hist=hist={x:None for x in ['feed_dist','feed_prox','feed_evdist','feed_evprox','feed_pois']}

    hasPois = len(dinput['pois']) > 0 and dinty['Poisson'] # this ensures synaptic weight > 0

    gRow = 0
    self.axdist = self.axprox = self.axpois = None # axis objects

    # check poisson inputs, create subplot
    if hasPois:
      self.axpois = self.figure.add_subplot(self.G[gRow,0])
      gRow += 1

    # check distal inputs, create subplot
    if (len(dinput['dist']) > 0 and dinty['OngoingDist']) or \
       (len(dinput['evdist']) > 0 and dinty['EvokedDist']):
      self.axdist = self.figure.add_subplot(self.G[gRow,0])
      gRow+=1

    # check proximal inputs, create subplot
    if (len(dinput['prox']) > 0 and dinty['OngoingProx']) or \
       (len(dinput['evprox']) > 0 and dinty['EvokedProx']):
      self.axprox = self.figure.add_subplot(self.G[gRow,0])
      gRow+=1


    # check input types provided in simulation
    if extinputs is not None and self.hassimdata(): # only valid param.txt file after sim was run
      if debug:
        print(len(dinput['dist']),len(dinput['prox']),len(dinput['evdist']),len(dinput['evprox']),len(dinput['pois']))

      if hasPois: # any Poisson inputs?
        extinputs.plot_hist(self.axpois,'pois',times,'auto',xl,color='k',hty='step',lw=self.gui.linewidth+1)

      if len(dinput['dist']) > 0 and dinty['OngoingDist']: # dinty condition ensures synaptic weight > 0
        extinputs.plot_hist(self.axdist,'dist',times,'auto',xl,color='g',lw=self.gui.linewidth+1)

      if len(dinput['prox']) > 0 and dinty['OngoingProx']: # dinty condition ensures synaptic weight > 0
        extinputs.plot_hist(self.axprox,'prox',times,'auto',xl,color='r',lw=self.gui.linewidth+1)

      if len(dinput['evdist']) > 0 and dinty['EvokedDist']: # dinty condition ensures synaptic weight > 0
        extinputs.plot_hist(self.axdist,'evdist',times,'auto',xl,color='g',hty='step',lw=self.gui.linewidth+1)

      if len(dinput['evprox']) > 0 and dinty['EvokedProx']: # dinty condition ensures synaptic weight > 0
        extinputs.plot_hist(self.axprox,'evprox',times,'auto',xl,color='r',hty='step',lw=self.gui.linewidth+1)
    elif plot_distribs:
      if len(dinput['evprox']) > 0 and dinty['EvokedProx']: # dinty condition ensures synaptic weight > 0
        prox_tot = np.zeros(len(dinput['evprox'][0][0]))
        for prox in dinput['evprox']:
          prox_tot += prox[1]
        plot = self.axprox.plot(dinput['evprox'][0][0],prox_tot,color='r',lw=self.gui.linewidth,label='evprox distribution')
        self.axprox.set_xlim(dinput['evprox'][0][0][0],dinput['evprox'][0][0][-1])
      if len(dinput['evdist']) > 0 and dinty['EvokedDist']: # dinty condition ensures synaptic weight > 0
        dist_tot = np.zeros(len(dinput['evdist'][0][0]))
        for dist in dinput['evdist']:
          dist_tot += dist[1]
        plot = self.axdist.plot(dinput['evdist'][0][0],dist_tot,color='g',lw=self.gui.linewidth,label='evdist distribution')
        self.axprox.set_xlim(dinput['evdist'][0][0][0],dinput['evdist'][0][0][-1])

    ymax = 0
    for ax in [self.axpois, self.axdist, self.axprox]:
      if not ax is None:
        if ax.get_ylim()[1] > ymax:
          ymax = ax.get_ylim()[1]

    if ymax == 0:
      if debug: print('all hists None!')
      return False
    else:
      for ax in [self.axpois, self.axdist, self.axprox]:
        if not ax is None:
          ax.set_ylim(0,ymax)
      if self.axdist:
        self.axdist.invert_yaxis()
      for ax in [self.axpois,self.axdist,self.axprox]:
        if ax:
          ax.set_xlim(xl)
          ax.legend(loc=1)  # legend in upper right
      return True,gRow
Exemple #7
0
  def plotinputhist (self, xl, dinty):
    """ plot input histograms
        xl = x axis limits
        dinty = dict of input types used, determines how many/which axes created/displayed
    """

    # set number of bins (150 bins per 1000ms)
    bins = ceil(150. * (xl[1] - xl[0]) / 1000.) # bins needs to be an int
    if debug: print('bins:',bins)
    extinputs = None
    plot_distribs = False

    try:
      extinputs = spikefn.ExtInputs(dfile['spk'], dfile['outparam'])
      extinputs.add_delay_times()
      dinput = extinputs.inputs
    except FileNotFoundError:
      dinput = self.getInputDistrib()
      plot_distribs = True

    if len(dinput['dist']) <= 0 and len(dinput['prox']) <= 0 and \
        len(dinput['evdist']) <= 0 and len(dinput['evprox']) <= 0 and \
        len(dinput['pois']) <= 0:
      if debug: print('all hists 0!')
      return False

    self.hist=hist={x:None for x in ['feed_dist','feed_prox','feed_evdist','feed_evprox','feed_pois']}

    hasPois = len(dinput['pois']) > 0 and dinty['Poisson'] # this ensures synaptic weight > 0

    gRow = 0
    self.axdist = self.axprox = self.axpois = None # axis objects

    # check poisson inputs, create subplot
    if hasPois:
      self.axpois = self.figure.add_subplot(self.G[gRow,0])
      gRow += 1

    # check distal inputs, create subplot
    if (len(dinput['dist']) > 0 and dinty['OngoingDist']) or \
       (len(dinput['evdist']) > 0 and dinty['EvokedDist']):
      self.axdist = self.figure.add_subplot(self.G[gRow,0])
      gRow+=1

    # check proximal inputs, create subplot
    if (len(dinput['prox']) > 0 and dinty['OngoingProx']) or \
       (len(dinput['evprox']) > 0 and dinty['EvokedProx']):
      self.axprox = self.figure.add_subplot(self.G[gRow,0])
      gRow+=1


    # check input types provided in simulation
    if extinputs is not None and self.hassimdata(): # only valid param.txt file after sim was run
      if debug:
        print(len(dinput['dist']),len(dinput['prox']),len(dinput['evdist']),len(dinput['evprox']),len(dinput['pois']))

      if hasPois: # any Poisson inputs?
        hist['feed_pois'] = extinputs.plot_hist(self.axpois,'pois',ddat['dpl'][:,0],bins,xl,color='k',hty='step',lw=self.gui.linewidth+1)

      if len(dinput['dist']) > 0 and dinty['OngoingDist']: # dinty condition ensures synaptic weight > 0
        hist['feed_dist'] = extinputs.plot_hist(self.axdist,'dist',ddat['dpl'][:,0],bins,xl,color='g',lw=self.gui.linewidth+1)

      if len(dinput['prox']) > 0 and dinty['OngoingProx']: # dinty condition ensures synaptic weight > 0
        hist['feed_prox'] = extinputs.plot_hist(self.axprox,'prox',ddat['dpl'][:,0],bins,xl,color='r',lw=self.gui.linewidth+1)

      if len(dinput['evdist']) > 0 and dinty['EvokedDist']: # dinty condition ensures synaptic weight > 0
        hist['feed_evdist'] = extinputs.plot_hist(self.axdist,'evdist',ddat['dpl'][:,0],bins,xl,color='g',hty='step',lw=self.gui.linewidth+1)

      if len(dinput['evprox']) > 0 and dinty['EvokedProx']: # dinty condition ensures synaptic weight > 0
        hist['feed_evprox'] = extinputs.plot_hist(self.axprox,'evprox',ddat['dpl'][:,0],bins,xl,color='r',hty='step',lw=self.gui.linewidth+1)
    elif plot_distribs:
      if len(dinput['evprox']) > 0 and dinty['EvokedProx']: # dinty condition ensures synaptic weight > 0
        for index, prox in enumerate(dinput['evprox']):
          if index == 0:
            plot = self.axprox.plot(prox[0],prox[1],color='r',lw=self.gui.linewidth,label='evprox distribution')
          else:
            plot = self.axprox.plot(prox[0],prox[1],color='r',lw=self.gui.linewidth)
          self.axprox.set_xlim(prox[0][0],prox[0][-1])
          hist['feed_evprox'] = plot
      if len(dinput['evdist']) > 0 and dinty['EvokedDist']: # dinty condition ensures synaptic weight > 0
        for index, dist in enumerate(dinput['evdist']):
          if index == 0:
            plot = self.axdist.plot(dist[0],dist[1],color='g',lw=self.gui.linewidth,label='evdist distribution')
          else:
            plot = self.axdist.plot(dist[0],dist[1],color='g',lw=self.gui.linewidth)
          self.axdist.set_xlim(dist[0][0],dist[0][-1])
          hist['feed_evdist'] = plot

    if hist['feed_dist'] is None and hist['feed_prox'] is None and \
        hist['feed_evdist'] is None and hist['feed_evprox'] is None and \
        hist['feed_pois'] is None:
      if debug: print('all hists None!')
      return False
    else:
      if self.axdist:
        self.axdist.invert_yaxis()
      for ax in [self.axpois,self.axdist,self.axprox]:
        if ax:
          ax.set_xlim(xl)
          ax.legend(loc=1)  # legend in upper right
      return True,gRow
Exemple #8
0
def exec_phaselock(ddata, opts):
    p = {
        't_interval': [50, 1000],
        'f_max': 60.,
    }
    args_check(p, opts)

    # Do this per expmt group
    for expmt_group in ddata.expmt_groups:
        # Get paths to relevant files
        list_dpl = ddata.file_match(expmt_group, 'rawdpl')
        list_spk = ddata.file_match(expmt_group, 'rawspk')
        list_param = ddata.file_match(expmt_group, 'param')

        avg_spec = ddata.file_match(expmt_group, 'avgspec')[0]

        tmp_array_dpl = []
        tmp_array_spk = []

        for f_dpl, f_spk, f_param in zip(list_dpl, list_spk, list_param):
            # load Dpl data, do stuff, and store it
            print f_dpl
            dpl = dipolefn.Dipole(f_dpl)
            dpl.baseline_renormalize(f_param)
            dpl.convert_fAm_to_nAm()
            t, dp = dpl.truncate_ext(p['t_interval'][0], p['t_interval'][1])
            dp = dp['agg']
            tmp_array_dpl.append(dp)

            # Load extinput data, do stuff, and store it
            try:
                extinput = spikefn.ExtInputs(f_spk, f_param)
            except ValueError:
                print("Error: could not load spike timings from %s" % f_spk)
                return

            extinput.add_delay_times()
            extinput.get_envelope(dpl.t, feed='dist', bins=150)
            inputs, t = extinput.truncate_ext('env', p['t_interval'])
            tmp_array_spk.append(inputs)

        # Convert tmp arrays (actually lists) to numpy nd arrays
        array_dpl = np.array(tmp_array_dpl)
        array_spk = np.array(tmp_array_spk)

        # Phase-locking analysis
        phase = specfn.PhaseLock(array_dpl, array_spk, list_param[0], p['f_max'])

        fname_d = os.path.join(ddata.dsim, expmt_group, 'phaselock-%iHz.npz' %p['f_max'])
        np.savez_compressed(fname_d, t=phase.data['t'], f=phase.data['f'], B=phase.data['B'])

        # Plotting
        # Should be moved elsewhere
        avg_dpl = np.mean(array_dpl, axis=0)
        avg_spk = np.mean(array_spk, axis=0)

        f = ac.FigPhase()

        extent_xy = [t[0], t[-1], phase.data['f'][-1], 0]
        pc1 = f.ax['phase'].imshow(phase.data['B'], extent=extent_xy, aspect='auto', origin='upper',cmap=plt.get_cmap('jet'))
        pc1.set_clim([0, 1])
        cb1 = f.f.colorbar(pc1, ax=f.ax['phase'])
        # cb1.set_clim([0, 1])

        spec = specfn.Spec(avg_spec)
        pc2 = spec.plot_TFR(f.ax['spec'], xlim=[t[0], t[-1]])
        pc2.set_clim([0, 3.8e-7])
        cb2 = f.f.colorbar(pc2, ax=f.ax['spec'])
        # cb2.set_clim([0, 3.6e-7])

        f.ax['dipole'].plot(t, avg_dpl)
        f.ax['dipole'].set_xlim([t[0], t[-1]])
        f.ax['dipole'].set_ylim([-0.0015, 0.0015])

        f.ax['input'].plot(t, avg_spk)
        f.ax['input'].set_xlim([t[0], t[-1]])
        f.ax['input'].set_ylim([-1, 5])
        f.ax['input'].invert_yaxis()

        f.ax['phase'].set_xlabel('Time (ms)')
        f.ax['phase'].set_ylabel('Frequency (Hz)')

        fname = os.path.join(ddata.dsim, expmt_group, 'phaselock-%iHz.png' %p['f_max'])
        print fname

        f.savepng(fname)