Beispiel #1
0
  def plotextdat (self, recalcErr=True):
    # plot 'external' data (e.g. from experiment/other simulation)
    try:
      #self.plotsimdat()
      if recalcErr: calcerr(ddat) # recalculate/save the error?
      lerr, errtot = ddat['lerr'], ddat['errtot']

      hassimdata = self.hassimdata() # has the simulation been run yet?

      if not hasattr(self,'axdipole'): self.setupaxdipole() # do we need an axis for drawing?
      elif self.axdipole is None: self.setupaxdipole()

      ax = self.axdipole
      yl = ax.get_ylim()

      cmap=plt.get_cmap('nipy_spectral')
      csm = plt.cm.ScalarMappable(cmap=cmap);
      csm.set_clim((0,100))

      self.clearlextdatobj() # clear annotation objects

      ddx = 0
      for fn,dat in ddat['dextdata'].items():
        shp = dat.shape
        clr = csm.to_rgba(self.getnextcolor())
        c = min(shp[1],1)
        self.lextdatobj.append(ax.plot(dat[:,0],dat[:,c],color=clr,linewidth=self.gui.linewidth+1))
        yl = ((min(yl[0],min(dat[:,c]))),(max(yl[1],max(dat[:,c]))))
        fx = int(shp[0] * float(c) / shp[1])
        if lerr:
          tx,ty=dat[fx,0],dat[fx,c]
          txt='RMSE:' + str(round(lerr[ddx],2))
          self.lextdatobj.append(ax.annotate(txt,xy=(dat[0,0],dat[0,c]),xytext=(tx,ty),color=clr,fontweight='bold'))
        self.lpatch.append(mpatches.Patch(color=clr, label=fn.split(os.path.sep)[-1].split('.txt')[0]))
        ddx+=1

      ax.set_ylim(yl)

      if self.lextdatobj and self.lpatch:
        self.lextdatobj.append(ax.legend(handles=self.lpatch))

      if errtot:
        tx,ty=0,0
        txt='Avg. RMSE:' + str(round(errtot,2))
        self.annot_avg = ax.annotate(txt,xy=(0,0),xytext=(0.005,0.005),textcoords='axes fraction',fontweight='bold')

      if not hassimdata: # need axis labels
        left = 0.08
        w,h=getscreengeom()
        if w < 2800: left = 0.1
        ax.set_xlabel('Time (ms)',fontsize=dconf['fontsize'])
        ax.set_ylabel('Dipole (nAm)',fontsize=dconf['fontsize'])
        myxl = ax.get_xlim()
        if myxl[0] < 0.0: ax.set_xlim((0.0,myxl[1]+myxl[0]))
        self.figure.subplots_adjust(left=left,right=0.99,bottom=0.0,top=0.99,hspace=0.1,wspace=0.1) # reduce padding

    except:
      print('simdat ERR: could not plotextdat')
      return False
    return True
Beispiel #2
0
  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'])
Beispiel #3
0
  def plotsimdat (self):
    # plot the simulation data

    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])]

      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]))
        ax.plot(olddpl[:,0],olddpl[:,1],'--',color='black',linewidth=self.gui.linewidth)
        yl[0] = min(yl[0],olddpl[sidx:eidx,1].min())
        yl[1] = max(yl[1],olddpl[sidx:eidx,1].max())

      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,(yl[1]-yl[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+1)

      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)

      bottom = 0.0
      left = 0.08
      w,h=getscreengeom()
      if w < 2800: left = 0.1

      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)
        bottom = 0.08
      else:
        ax.set_xlabel('Time (ms)',fontsize=dconf['fontsize'])
    except:
      print('ERR: in plotsimdat')
    self.figure.subplots_adjust(left=left,right=0.99,bottom=bottom,top=0.99,hspace=0.1,wspace=0.1) # reduce padding
Beispiel #4
0
  def plotextdat (self, recalcErr=True):
    if not 'dextdata' in ddat or len(ddat['dextdata']) == 0:
      return

    # plot 'external' data (e.g. from experiment/other simulation)
    hassimdata = self.hassimdata() # has the simulation been run yet?
    if hassimdata:
      if recalcErr:
        calcerr(ddat, ddat['dpl'][-1,0]) # recalculate/save the error?
      lerr, errtot = ddat['lerr'], ddat['errtot']

      if self.optMode:
        initial_err = initial_ddat['errtot']
    else:
      lerr = None
      errtot = None

    if self.axdipole is None:
      self.axdipole = self.figure.add_subplot(self.G[0:-1,0]) # dipole
      yl = (-0.001,0.001)
    else:
      yl = self.axdipole.get_ylim()

    xl = (0.0,1.0)

    cmap=plt.get_cmap('nipy_spectral')
    csm = plt.cm.ScalarMappable(cmap=cmap);
    csm.set_clim((0,100))

    self.clearlextdatobj() # clear annotation objects

    ddx = 0
    for fn,dat in ddat['dextdata'].items():
      shp = dat.shape
      clr = csm.to_rgba(self.getnextcolor())
      c = min(shp[1],1)
      self.lextdatobj.append(self.axdipole.plot(dat[:,0],dat[:,c],color=clr,linewidth=self.gui.linewidth+1))
      xl = ((min(xl[0],min(dat[:,0]))),(max(xl[1],max(dat[:,0]))))
      yl = ((min(yl[0],min(dat[:,c]))),(max(yl[1],max(dat[:,c]))))
      fx = int(shp[0] * float(c) / shp[1])
      if lerr:
        tx,ty=dat[fx,0],dat[fx,c]
        txt='RMSE: %.2f' % round(lerr[ddx],2)
        if not self.optMode:
          self.lextdatobj.append(self.axdipole.annotate(txt,xy=(dat[0,0],dat[0,c]),xytext=(tx,ty),color=clr,fontweight='bold'))
      self.lpatch.append(mpatches.Patch(color=clr, label=fn.split(os.path.sep)[-1].split('.txt')[0]))
      ddx+=1

    self.axdipole.set_xlim(xl)
    self.axdipole.set_ylim(yl)

    if self.lextdatobj and self.lpatch:
      self.lextdatobj.append(self.axdipole.legend(handles=self.lpatch, loc=2))

    if errtot:
      tx,ty=0,0
      if self.optMode:
        clr = 'black'
        txt='RMSE: %.2f' % round(initial_err,2)
        self.annot_avg = self.axdipole.annotate(txt,xy=(0,0),xytext=(0.005,0.005),textcoords='axes fraction',color=clr,fontweight='bold')
        clr = 'gray'
        txt='RMSE: %.2f' % round(errtot,2)
        self.annot_avg = self.axdipole.annotate(txt,xy=(0,0),xytext=(0.86,0.005),textcoords='axes fraction',color=clr,fontweight='bold')
      else:
        clr = 'black'
        txt='Avg. RMSE: %.2f' % round(errtot,2)
        self.annot_avg = self.axdipole.annotate(txt,xy=(0,0),xytext=(0.005,0.005),textcoords='axes fraction',color=clr,fontweight='bold')

    if not hassimdata: # need axis labels
      left = 0.08
      w,h=getscreengeom()
      if w < 2800: left = 0.1
      self.axdipole.set_xlabel('Time (ms)',fontsize=dconf['fontsize'])
      self.axdipole.set_ylabel('Dipole (nAm)',fontsize=dconf['fontsize'])
      myxl = self.axdipole.get_xlim()
      if myxl[0] < 0.0: self.axdipole.set_xlim((0.0,myxl[1]+myxl[0]))
      self.figure.subplots_adjust(left=left,right=0.99,bottom=0.0,top=0.99,hspace=0.1,wspace=0.1) # reduce padding