示例#1
0
def handle_show(do_show):
    ''' Helper function to handle the slightly complex logic of show -- not for users '''
    backend = pl.get_backend()
    if do_show is None:  # If not supplied, reset to global value
        do_show = cvo.show
    if backend == 'agg':  # Cannot show plots for a non-interactive backend
        do_show = False
    if do_show:  # Now check whether to show, and atually do it
        pl.show()
    return do_show
示例#2
0
def gcf_set_active(manager):
    # Note that this function is called by pyplot
    # - when the user clicks on the canvas (callback needed on canvas object?)
    # - on pyplot.figure(number)
    if pylab.get_backend() == config.get("matplotlib",
                                         {}).get("backend", None):
        number = manager.num
        if number in gui._qapp.panels.get('plot', {}).keys():
            gui.plot.select(manager.num)
        else:
            set_active_backup(manager)
    else:
        set_active_backup(manager)
示例#3
0
文件: gui_utils.py 项目: isaxs/pyFAI
def update_fig(fig=None):
    """
    Update a matplotlib figure with a Qt4 backend

    @param fig: pylab figure
    """
    if fig and "canvas" in dir(fig) and fig.canvas:
        fig.canvas.draw()
        if "Qt4" in pylab.get_backend():
            QtGui.qApp.postEvent(fig.canvas,
                                 QtGui.QResizeEvent(fig.canvas.size(),
                                                    fig.canvas.size()))
            if not main_loop:
                QtCore.QCoreApplication.processEvents()
示例#4
0
def set_default_options():
    '''
    Set the default options for Covasim -- not to be called by the user, use
    ``cv.options.set('defaults')`` instead.
    '''

    # Options acts like a class, but is actually an objdict for simplicity
    optdesc = sc.objdict()  # Help for the options
    options = sc.objdict()  # The options

    optdesc.verbose = 'Set default level of verbosity (i.e. logging detail)'
    options.verbose = float(os.getenv('COVASIM_VERBOSE', 0.1))

    optdesc.show = 'Set whether or not to show figures (i.e. call pl.show() automatically)'
    options.show = int(os.getenv('COVASIM_SHOW', True))

    optdesc.close = 'Set whether or not to close figures (i.e. call pl.close() automatically)'
    options.close = int(os.getenv('COVASIM_CLOSE', False))

    optdesc.backend = 'Set the Matplotlib backend (use "agg" for non-interactive)'
    options.backend = os.getenv('COVASIM_BACKEND', pl.get_backend())

    optdesc.interactive = 'Convenience method to set figure backend, showing, and closing behavior'
    options.interactive = os.getenv('COVASIM_INTERACTIVE', True)

    optdesc.dpi = 'Set the default DPI -- the larger this is, the larger the figures will be'
    options.dpi = int(os.getenv('COVASIM_DPI', pl.rcParams['figure.dpi']))

    optdesc.font_size = 'Set the default font size'
    options.font_size = int(
        os.getenv('COVASIM_FONT_SIZE', pl.rcParams['font.size']))

    optdesc.font_family = 'Set the default font family (e.g., Arial)'
    options.font_family = os.getenv('COVASIM_FONT_FAMILY',
                                    pl.rcParams['font.family'])

    optdesc.precision = 'Set arithmetic precision for Numba -- 32-bit by default for efficiency'
    options.precision = int(os.getenv('COVASIM_PRECISION', 32))

    optdesc.numba_parallel = 'Set Numba multithreading -- none, safe, full; full multithreading is ~20% faster, but results become nondeterministic'
    options.numba_parallel = str(os.getenv('COVASIM_NUMBA_PARALLEL', 'none'))

    optdesc.numba_cache = 'Set Numba caching -- saves on compilation time, but harder to update'
    options.numba_cache = bool(int(os.getenv('COVASIM_NUMBA_CACHE', 1)))

    return options, optdesc
示例#5
0
文件: gui_utils.py 项目: isaxs/pyFAI
def maximize_fig(fig=None):
    """
    Try to set the figure fullscreen
    """
    if fig and "canvas" in dir(fig) and fig.canvas:
        if "Qt4" in pylab.get_backend():
            fig.canvas.setWindowState(QtCore.Qt.WindowMaximized)
        else:
            mng = pylab.get_current_fig_manager()
            # attempt to maximize the figure ... lost hopes.
            win_shape = (1920, 1080)
            event = Event(*win_shape)
            try:
                mng.resize(event)
            except TypeError:
                 mng.resize(*win_shape)
    update_fig(fig)
示例#6
0
def savefig(fname,figsize,fig=None,**kwargs):
  """ 
    force saving figure with a given size, useful when using tiling wm;
    if fname is a list, it saves multiple files, for example [todel.pdf,todel.png]
  """
  if isinstance(fname,str): fname = (fname,)
  if fig is None: fig = plt.gcf()
  old_bkg = plt.get_backend()
  old_inter = plt.isinteractive()
  try:
    plt.switch_backend("cairo")
    old_height = fig.get_figheight()
    old_width  = fig.get_figwidth()
    fig.set_figwidth ( figsize[0] )
    fig.set_figheight( figsize[1] )
    [  fig.savefig(f,**kwargs) for f in fname ]
    plt.switch_backend(old_bkg)
  finally:
    plt.switch_backend(old_bkg)
    plt.interactive(old_inter)
示例#7
0
    def _plotValues(self,
                    values,            #dict  TimeSeries values
                    plot_label,        #str   Plot-Label
                    fig_num,           #int   Figure-number for classify plots
                                       #      1: average,
                                       #      2: single trial,
                                       #      3: average accumulating
                    store_dir = None,  #str   Directory to store the plots
                    counter=0):        #int   Plotcounter for all trials
        
        if self.class_difference:
            #we have to compute the difference
            list_of_classes = values.keys()
            num_of_classes = len(list_of_classes)
            if num_of_classes != 2: 
                warnings.warn("TimeSeriesPlot:: Difference plots only possible for two classes  Plotting ignored!")
                return
            data1 = values[list_of_classes[0]].view(numpy.ndarray)
            data2 = values[list_of_classes[1]].view(numpy.ndarray)

            #construct new TimeSeries with differences
            data = TimeSeries(data1 - data2, 
                              channel_names=values[list_of_classes[0]].channel_names, 
                              sampling_frequency=values[list_of_classes[0]].sampling_frequency)
            #overwrite old incoming values
            values=dict(difference=data)

        sampling_frequency = values[values.keys()[0]].sampling_frequency
        list_of_classes = values.keys()
        num_of_classes = len(list_of_classes)
             
        #computing time points to show
        num_tpoints = values.values()[0].shape[0]
        all_tpoints = numpy.arange(0,
                                   num_tpoints * (1000/sampling_frequency),
                                   1000 / sampling_frequency) + self.timeshift    

        pylab.subplots_adjust(left  = 0.05,  # the left side of the subplots of the figure
                      right = 0.95,    # the right side of the subplots of the figure
                      bottom = 0.05,   # the bottom of the subplots of the figure
                      top = 0.95,      # the top of the subplots of the figure
                      wspace = 0.15,   # the amount of width reserved for blank space between subplots
                      hspace = 0.1,   # the amount of height reserved for white space between subplots                          
                      )

        f=pylab.figure(fig_num, figsize = (18,13))
        #assure that figure is displayed with an interactive backend
        if pylab.get_backend() in pylab.matplotlib.backends.interactive_bk:
                f.show()
        #plot all channels separately in one figure
        if self.separate_channels:
            self._plot_all_channels_separated(all_tpoints, values)
        else:
            for index, class_label in enumerate(list_of_classes):
           
                data = values[class_label].view(numpy.ndarray)
                
                axis = pylab.subplot(1, num_of_classes, index + 1)
                pylab.gca().clear()
                
                #plot just 1 channel
                if self.channel_names != None and len(self.channel_names)==1:
                    assert (self.channel_names[0] in values[class_label].channel_names),\
                            "TimeSeriesPlot::Channel requested for plotting is not available in data"
                    channel_index = values[class_label].channel_names.index(self.channel_names[0])                     
                    # Update minimal and maximal value
                    self.min_value = min(self.min_value, 
                                         min(data[:, channel_index].flatten()))
                    self.max_value = max(self.max_value, 
                                         max(data[:, channel_index].flatten()))
                    
                    title = pylab.title(str(self.channel_names) + ' ' + class_label)
                    pylab.plot(all_tpoints, data[:, channel_index])
    
                #plot all channels as matrix    
                else:
                    self._plot_all_channels(data, all_tpoints, values[class_label].channel_names)
                    title = pylab.title(class_label)
                
                title.set_fontsize(24)
                pylab.draw()
                          
        
        # Draw or store the figure
        if store_dir is None:
            pylab.draw()
        else:
            current_split=self.current_split
            if current_split != 0 and not\
            plot_label.endswith('_split_' + str(current_split)): #more than one split and first call
                plot_label = plot_label + '_split_' + str(current_split)
                
            f_name=str(store_dir) + str(os.sep) + str(plot_label)
            pylab.savefig(f_name + ".png")         
示例#8
0
       def dayPlot(self, period, data, locn, per_labels=None, x_labels=None):
           plt.figure(period)
           plt.suptitle(self.hdrs[period] + locn, fontsize=16)
           maxy = 0
           maxw = 0
           if len(data[0]) > 9:
               p_y = 3
               p_x = 4
               xl = 8
               yl = [0, 4, 8]
               yl2 = [3, 7, 11]
           elif len(data[0]) > 6:
               p_y = 3
               p_x = 3
               xl = 6
               yl = [0, 3]
               yl2 = [2, 5]
           elif len(data[0]) > 4:
               p_y = 2
               p_x = 3
               xl = 3
               yl = [0, 3]
               yl2 = [2, 5]
           elif len(data[0]) > 2:
               p_y = 2
               p_x = 2
               xl = 2
               yl = [0, 2]
               yl2 = [1, 3]
           else:
               p_y = 1
               p_x = 2
               xl = 0
               yl = [0, 1]
               yl2 = [0, 1]
           wi = -1
           ra = -1
           te = -1
           i = -1
           for key, value in iter(sorted(self.ly.iteritems())):
               i += 1
               if key == 'wind':
                   wi = i
               elif key == 'temp':
                   te = i
               elif key == 'rain':
                   ra = i
           for p in range(len(data[0])):
               for i in range(len(ly)):
                   maxy = max(maxy, max(data[i][p]))
                   if i == wi or i == te or i == ra:
                       maxw = max(maxw, max(data[i][p]))
           for p in range(len(data[0])):
               px = plt.subplot(p_y, p_x, p + 1)
               i = -1
               if self.two_axes:
                   px2 = px.twinx()
               for key, value in iter(sorted(self.ly.iteritems())):
                   i += 1
                   lw = 2.0
                   if self.two_axes and key in self.ylabel2[0]:
                       px2.plot(x24, data[i][p], linewidth=lw, label=key, color=self.colours[key])
                   else:
                       px.plot(x24, data[i][p], linewidth=lw, label=key, color=self.colours[key])
                   plt.title(per_labels[p])
               plt.xlim([1, 24])
               plt.xticks(range(4, 25, 4))
      #         px.set_xticklabels(labels])
 #              plt.xticks(range(0, 25, 4))
               px.set_xticklabels(x_labels[1:])
               px.set_ylim([0, maxy])
               if self.two_axes:
                   px2.set_ylim(0, maxw)
                   if p in yl2:
                       px2.set_ylabel(self.ylabel2[2])
               if p >= xl:
                   px.set_xlabel('Hour of the Day')
               if p in yl:
                   px.set_ylabel(self.ylabel[1])
           if self.two_axes:
               lines = []
               for key in self.ly:
                   lines.append(mlines.Line2D([], [], color=self.colours[key], label=key))
               px.legend(handles=lines, loc='best')
           else:
               px.legend(loc='best')
           if self.maximise:
               mng = plt.get_current_fig_manager()
               if sys.platform == 'win32' or sys.platform == 'cygwin':
                   if plt.get_backend() == 'TkAgg':
                       mng.window.state('zoomed')
                   elif plt.get_backend() == 'Qt4Agg':
                       mng.window.showMaximized()
               else:
                   mng.resize(*mng.window.maxsize())
           if self.plots['block']:
               plt.show(block=True)
           else:
               plt.draw()
示例#9
0
   def showGraphs(self, ly, x, locn):
       def dayPlot(self, period, data, locn, per_labels=None, x_labels=None):
           plt.figure(period)
           plt.suptitle(self.hdrs[period] + locn, fontsize=16)
           maxy = 0
           maxw = 0
           if len(data[0]) > 9:
               p_y = 3
               p_x = 4
               xl = 8
               yl = [0, 4, 8]
               yl2 = [3, 7, 11]
           elif len(data[0]) > 6:
               p_y = 3
               p_x = 3
               xl = 6
               yl = [0, 3]
               yl2 = [2, 5]
           elif len(data[0]) > 4:
               p_y = 2
               p_x = 3
               xl = 3
               yl = [0, 3]
               yl2 = [2, 5]
           elif len(data[0]) > 2:
               p_y = 2
               p_x = 2
               xl = 2
               yl = [0, 2]
               yl2 = [1, 3]
           else:
               p_y = 1
               p_x = 2
               xl = 0
               yl = [0, 1]
               yl2 = [0, 1]
           wi = -1
           ra = -1
           te = -1
           i = -1
           for key, value in iter(sorted(self.ly.iteritems())):
               i += 1
               if key == 'wind':
                   wi = i
               elif key == 'temp':
                   te = i
               elif key == 'rain':
                   ra = i
           for p in range(len(data[0])):
               for i in range(len(ly)):
                   maxy = max(maxy, max(data[i][p]))
                   if i == wi or i == te or i == ra:
                       maxw = max(maxw, max(data[i][p]))
           for p in range(len(data[0])):
               px = plt.subplot(p_y, p_x, p + 1)
               i = -1
               if self.two_axes:
                   px2 = px.twinx()
               for key, value in iter(sorted(self.ly.iteritems())):
                   i += 1
                   lw = 2.0
                   if self.two_axes and key in self.ylabel2[0]:
                       px2.plot(x24, data[i][p], linewidth=lw, label=key, color=self.colours[key])
                   else:
                       px.plot(x24, data[i][p], linewidth=lw, label=key, color=self.colours[key])
                   plt.title(per_labels[p])
               plt.xlim([1, 24])
               plt.xticks(range(4, 25, 4))
      #         px.set_xticklabels(labels])
 #              plt.xticks(range(0, 25, 4))
               px.set_xticklabels(x_labels[1:])
               px.set_ylim([0, maxy])
               if self.two_axes:
                   px2.set_ylim(0, maxw)
                   if p in yl2:
                       px2.set_ylabel(self.ylabel2[2])
               if p >= xl:
                   px.set_xlabel('Hour of the Day')
               if p in yl:
                   px.set_ylabel(self.ylabel[1])
           if self.two_axes:
               lines = []
               for key in self.ly:
                   lines.append(mlines.Line2D([], [], color=self.colours[key], label=key))
               px.legend(handles=lines, loc='best')
           else:
               px.legend(loc='best')
           if self.maximise:
               mng = plt.get_current_fig_manager()
               if sys.platform == 'win32' or sys.platform == 'cygwin':
                   if plt.get_backend() == 'TkAgg':
                       mng.window.state('zoomed')
                   elif plt.get_backend() == 'Qt4Agg':
                       mng.window.showMaximized()
               else:
                   mng.resize(*mng.window.maxsize())
           if self.plots['block']:
               plt.show(block=True)
           else:
               plt.draw()
       papersizes = {'a0': '33.1,46.8', 'a1': '23.4,33.1', 'a2': '16.5,23.4',
                   'a3': '11.7,16.5', 'a4': '8.3,11.7', 'a5': '5.8,8.3',
                   'a6': '4.1,5.8', 'a7': '2.9,4.1', 'a8': '2,2.9',
                   'a9': '1.5,2', 'a10': '1,1.5', 'b0': '39.4,55.7',
                   'b1': '27.8,39.4', 'b2': '19.7,27.8', 'b3': '13.9,19.7',
                   'b4': '9.8,13.9', 'b5': '6.9,9.8', 'b6': '4.9,6.9',
                   'b7': '3.5,4.9', 'b8': '2.4,3.5', 'b9': '1.7,2.4',
                   'b10': '1.2,1.7', 'foolscap': '8.0,13.0', 'ledger': '8.5,14.0',
                   'legal': '8.5,14.09', 'letter': '8.5,11.0'}
       landscape = False
       papersize = ''
       config = ConfigParser.RawConfigParser()
       if len(sys.argv) > 1:
           config_file = sys.argv[1]
       else:
           config_file = 'SIREN.ini'
       config.read(config_file)
       self.maximise = False
       seasons = []
       periods = []
       parents = []
       try:
           parents = getParents(config.items('Parents'))
       except:
           pass
       try:
           self.scenarios = config.get('Files', 'scenarios')
           for key, value in parents:
               self.scenarios = self.scenarios.replace(key, value)
           self.scenarios = self.scenarios.replace('$USER$', getUser())
           self.scenarios = self.scenarios.replace('$YEAR$', str(self.base_year))
           i = self.scenarios.rfind('/')
           self.scenarios = self.scenarios[:i + 1]
       except:
           self.scenarios = ''
       try:
           items = config.items('Power')
           for item, values in items:
               if item[:6] == 'season':
                   if item == 'season':
                       continue
                   i = int(item[6:]) - 1
                   if i >= len(seasons):
                       seasons.append([])
                   seasons[i] = values.split(',')
                   for j in range(1, len(seasons[i])):
                       seasons[i][j] = int(seasons[i][j]) - 1
               elif item[:6] == 'period':
                   if item == 'period':
                       continue
                   i = int(item[6:]) - 1
                   if i >= len(periods):
                       periods.append([])
                   periods[i] = values.split(',')
                   for j in range(1, len(periods[i])):
                       periods[i][j] = int(periods[i][j]) - 1
               elif item == 'maximise':
                   if values.lower() in ['true', 'on', 'yes']:
                       self.maximise = True
               elif item == 'save_format':
                   plt.rcParams['savefig.format'] = values
               elif item == 'figsize':
                   try:
                       papersize = papersizes[values]
                   except:
                       papersize = values
               elif item == 'orientation':
                   if values.lower()[0] == 'l':
                       landscape = True
       except:
           pass
       if papersize != '':
           if landscape:
               bit = papersize.split(',')
               plt.rcParams['figure.figsize'] = bit[1] + ',' + bit[0]
           else:
               plt.rcParams['figure.figsize'] = papersize
       if len(seasons) == 0:
           seasons = [['Summer', 11, 0, 1], ['Autumn', 2, 3, 4], ['Winter', 5, 6, 7], ['Spring', 8, 9, 10]]
       if len(periods) == 0:
           periods = [['Winter', 4, 5, 6, 7, 8, 9], ['Summer', 10, 11, 0, 1, 2, 3]]
       for i in range(len(periods)):
           for j in range(len(seasons)):
               if periods[i][0] == seasons[j][0]:
                   periods[i][0] += '2'
                   break
       mth_labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
       ssn_labels = []
       for i in range(len(seasons)):
           ssn_labels.append('%s (%s-%s)' % (seasons[i][0], mth_labels[seasons[i][1]],
                              mth_labels[seasons[i][-1]]))
     #   ssn_labels = ['Summer (Dec, Jan-Feb)', 'Autumn (Mar-May)', 'Winter (Jun-Aug)', 'Spring(Sep-Nov)']
       smp_labels = []
       for i in range(len(periods)):
           smp_labels.append('%s (%s-%s)' % (periods[i][0], mth_labels[periods[i][1]],
                              mth_labels[periods[i][-1]]))
    #    smp_labels = ['Winter (May-Oct)', 'Summer (Nov-Apr)']
       labels = ['0:00', '4:00', '8:00', '12:00', '16:00', '20:00', '24:00']
       mth_xlabels = ['0:', '4:', '8:', '12:', '16:', '20:', '24:']
       m = 0
       d = 1
       day_labels = []
       while m < len(the_days):
           day_labels.append('%s %s' % (str(d), mth_labels[m]))
           d += 7
           if d > the_days[m]:
               d = d - the_days[m]
               m += 1
       lbl_font = FontProperties()
       lbl_font.set_size('small')
       x24 = []
       l24 = []
       m24 = []
       q24 = []
       s24 = []
       t12 = []
       for i in range(24):
           x24.append(i + 1)
       for i in range(len(self.ly)):
           if self.plots['total']:
               l24.append([])
               for j in range(24):
                   l24[i].append(0.)
           if self.plots['month']:
               m24.append([])
               for m in range(12):
                   m24[i].append([])
                   for j in range(24):
                       m24[i][m].append(0.)
           if self.plots['season']:
               q24.append([])
               for q in range(len(seasons)):
                   q24[i].append([])
                   for j in range(24):
                       q24[i][q].append(0.)
           if self.plots['period']:
               s24.append([])
               for s in range(len(periods)):
                   s24[i].append([])
                   for j in range(24):
                       s24[i][s].append(0.)
           if self.plots['monthly'] or self.plots['mthavg']:
               t12.append([])
               for m in range(14):
                   t12[i].append(0.)
       the_qtrs = []
       for i in range(len(seasons)):
           d = 0
           for j in range(1, len(seasons[i])):
               d += the_days[seasons[i][j]]
           the_qtrs.append(d)
       the_ssns = []
       for i in range(len(periods)):
           d = 0
           for j in range(1, len(periods[i])):
               d += the_days[periods[i][j]]
           the_ssns.append(d)
       the_hours = [0]
       i = 0
       for m in range(len(the_days)):
           i = i + the_days[m] * 24
           the_hours.append(i)
       d = -1
       for i in range(0, len(x), 24):
           m = 11
           d += 1
           while i < the_hours[m] and m > 0:
               m -= 1
           for k in range(24):
               j = -1
               for key, value in iter(sorted(self.ly.iteritems())):
                   if len(value) == 0:
                       continue
                   j += 1
                   if self.plots['total']:
                       l24[j][k] += value[i + k]
                   if self.plots['month']:
                       m24[j][m][k] = m24[j][m][k] + value[i + k]
                   if self.plots['season']:
                       for q in range(len(seasons)):
                           if m in seasons[q]:
                               break
                       q24[j][q][k] = q24[j][q][k] + value[i + k]
                   if self.plots['period']:
                       for s in range(len(periods)):
                           if m in periods[s]:
                               break
                       s24[j][s][k] = s24[j][s][k] + value[i + k]
                   if self.plots['monthly'] or self.plots['mthavg']:
                       t12[j][m + 1] = t12[j][m + 1] + value[i + k]
       for i in range(len(ly)):
           for k in range(24):
               if self.plots['total']:
                   l24[i][k] = l24[i][k] / 365
               if self.plots['month']:
                   for m in range(12):
                       m24[i][m][k] = m24[i][m][k] / the_days[m]
               if self.plots['season']:
                   for q in range(len(seasons)):
                       q24[i][q][k] = q24[i][q][k] / the_qtrs[q]
               if self.plots['period']:
                   for s in range(len(periods)):
                       s24[i][s][k] = s24[i][s][k] / the_ssns[s]
       if self.plots['hour']:
           if self.plots['save_plot']:
               vals = ['hour']
               data = []
               data.append(x)
           fig = plt.figure('hour')
           plt.grid(True)
           hx = fig.add_subplot(111)
           plt.title(self.hdrs['hour'] + ' - ' + locn)
           maxy = 0
           if self.two_axes:
               hx2 = hx.twinx()
           for key, value in iter(sorted(self.ly.iteritems())):
               lw = 2.0
               if self.two_axes and key in self.ylabel2[0]:
                   hx2.plot(x, value, linewidth=lw, label=key, color=self.colours[key])
               else:
                   hx.plot(x, value, linewidth=lw, label=key, color=self.colours[key])
                   maxy = max(maxy, max(value))
               if self.plots['save_plot']:
                   vals.append(key)
                   data.append(value)
           if self.plots['save_plot']:
               titl = 'hour'
               dialog = displaytable.Table(map(list, zip(*data)), title=titl, fields=vals, save_folder=self.scenarios)
               dialog.exec_()
               del dialog, data, vals
           hx.set_ylim([0, maxy])
           plt.xlim([0, len(x)])
           plt.xticks(range(12, len(x), 168))
           hx.set_xticklabels(day_labels, rotation='vertical')
           hx.set_xlabel('Month of the year')
           hx.set_ylabel(self.ylabel[0])
           hx.legend(loc='best')
           if self.two_axes:
               ylim = hx2.get_ylim()
               hx2.set_ylim(0, ylim[1])
               lines = []
               for key in self.ly:
                   lines.append(mlines.Line2D([], [], color=self.colours[key], label=key))
               hx.legend(handles=lines, loc='best')
               hx2.set_ylabel(self.ylabel2[1])
           if self.maximise:
               mng = plt.get_current_fig_manager()
               if sys.platform == 'win32' or sys.platform == 'cygwin':
                   if plt.get_backend() == 'TkAgg':
                       mng.window.state('zoomed')
                   elif plt.get_backend() == 'Qt4Agg':
                       mng.window.showMaximized()
               else:
                   mng.resize(*mng.window.maxsize())
           if self.plots['block']:
               plt.show(block=True)
           else:
               plt.draw()
       if self.plots['total']:
           if self.plots['save_plot']:
               vals = ['hour of the day']
               decpts = [0]
               data = []
               data.append(x24)
           figt = plt.figure('total')
           plt.grid(True)
           tx = figt.add_subplot(111)
           plt.title(self.hdrs['total'] + ' - ' + locn)
           maxy = 0
           i = -1
           lw = 2.0
           if self.two_axes:
               tx2 = tx.twinx()
           for key, value in iter(sorted(self.ly.iteritems())):
               i += 1
               if self.two_axes and key in self.ylabel2[0]:
                   tx2.plot(x24, l24[i], linewidth=lw, label=key, color=self.colours[key])
               else:
                   tx.plot(x24, l24[i], linewidth=lw, label=key, color=self.colours[key])
                   maxy = max(maxy, max(l24[i]))
               if self.plots['save_plot']:
                   vals.append(key)
                   data.append(l24[i])
                   if key == 'wind':
                       decpts.append(2)
                   else:
                       decpts.append(1)
           if self.plots['save_plot']:
               titl = 'total'
               dialog = displaytable.Table(map(list, zip(*data)), title=titl, fields=vals, save_folder=self.scenarios, decpts=decpts)
               dialog.exec_()
               del dialog, data, vals
           tx.set_ylim([0, maxy])
           plt.xlim([1, 24])
           plt.xticks(range(4, 25, 4))
           tx.set_xticklabels(labels[1:])
           tx.set_xlabel('Hour of the Day')
           tx.set_ylabel(self.ylabel[0])
           tx.legend(loc='best')
           if self.two_axes:
               ylim = tx2.get_ylim()
               tx2.set_ylim(0, ylim[1])
               lines = []
               for key in self.ly:
                   lines.append(mlines.Line2D([], [], color=self.colours[key], label=key))
               tx.legend(handles=lines, loc='best')
               tx2.set_ylabel(self.ylabel2[1])
           if self.maximise:
               mng = plt.get_current_fig_manager()
               if sys.platform == 'win32' or sys.platform == 'cygwin':
                   if plt.get_backend() == 'TkAgg':
                       mng.window.state('zoomed')
                   elif plt.get_backend() == 'Qt4Agg':
                       mng.window.showMaximized()
               else:
                   mng.resize(*mng.window.maxsize())
           if self.plots['block']:
               plt.show(block=True)
           else:
               plt.draw()
       if self.plots['month']:
           dayPlot(self, 'month', m24, locn, mth_labels, mth_xlabels)
       if self.plots['season']:
           dayPlot(self, 'season', q24, locn, ssn_labels, labels)
       if self.plots['period']:
           dayPlot(self, 'period', s24, locn, smp_labels, labels)
       if 'pdf' in self.plots.keys():
           if self.plots['pdf'] and self.plots['wind']:
               j = int(ceil(max(self.ly['wind'])))
               figp = plt.figure('pdf')
               plt.grid(True)
               px = figp.add_subplot(111)
               plt.title(self.hdrs['pdf'] + ' - ' + locn)
               px.hist(self.ly['wind'], j)
               px.set_ylabel('Number of occurences')
               px.set_xlabel('Wind Speed (m/s)')
           if self.plots['block']:
               plt.show(block=True)
           else:
               plt.draw()
       if self.plots['monthly']:
           if self.plots['save_plot']:
               vals = ['monthly']
               data = []
               data.append(x24[:12])
           figt = plt.figure('monthly')
           plt.grid(True)
           tx = figt.add_subplot(111)
           plt.title(self.hdrs['monthly'] + ' - ' + locn)
           maxy = 0
           i = -1
           if self.two_axes:
               tx2 = tx.twinx()
           for key, value in iter(sorted(self.ly.iteritems())):
               i += 1
               lw = 2.0
               if self.two_axes and key in self.ylabel2[0]:
                   tx2.step(x24[:14], t12[i], linewidth=lw, label=key, color=self.colours[key])
               else:
                   tx.step(x24[:14], t12[i], linewidth=lw, label=key, color=self.colours[key])
                   maxy = max(maxy, max(t12[i]) + 1)
               if self.plots['save_plot']:
                   vals.append(key)
                   data.append(t12[i][1:-1])
           if self.plots['save_plot']:
               titl = 'monthly'
               dialog = displaytable.Table(map(list, zip(*data)), title=titl, fields=vals, save_folder=self.scenarios)
               dialog.exec_()
               del dialog, data, vals
           tx.set_ylim([0, maxy])
           tick_spot = []
           for i in range(12):
               tick_spot.append(i + 1.5)
           tx.set_xticks(tick_spot)
           tx.set_xticklabels(mth_labels)
           plt.xlim([1, 13.0])
           tx.set_xlabel('Month')
           tx.set_ylabel(self.ylabel[0])
           tx.legend(loc='best')
           if self.two_axes:
               ylim = tx2.get_ylim()
               tx2.set_ylim(0, ylim[1])
               lines = []
               for key in self.ly:
                   lines.append(mlines.Line2D([], [], color=self.colours[key], label=key))
               tx.legend(handles=lines, loc='best')
               tx2.set_ylabel(self.ylabel2[1])
           if self.maximise:
               mng = plt.get_current_fig_manager()
               if sys.platform == 'win32' or sys.platform == 'cygwin':
                   if plt.get_backend() == 'TkAgg':
                       mng.window.state('zoomed')
                   elif plt.get_backend() == 'Qt4Agg':
                       mng.window.showMaximized()
               else:
                   mng.resize(*mng.window.maxsize())
           if self.plots['block']:
               plt.show(block=True)
           else:
               plt.draw()
       if self.plots['mthavg']:
           if self.plots['save_plot']:
               vals = ['monthly_average']
               data = []
               data.append(x24[:12])
               decpts = [0]
           figt = plt.figure('monthly_average')
           plt.grid(True)
           tx = figt.add_subplot(111)
           plt.title(self.hdrs['mthavg'] + ' - ' + locn)
           maxy = 0
           if self.two_axes:
               tx2 = tx.twinx()
           m12 = []
           for i in range(len(t12)):
               m12.append([])
               for m in range(1, 13):
                   m12[-1].append(t12[i][m] / the_days[m - 1] / 24.)
           i = -1
           lw = 2.0
           for key, value in iter(sorted(self.ly.iteritems())):
               i += 1
               if self.two_axes and key in self.ylabel2[0]:
                   tx2.plot(x24[:12], m12[i], linewidth=lw, label=key, color=self.colours[key])
               else:
                   tx.plot(x24[:12], m12[i], linewidth=lw, label=key, color=self.colours[key])
                   maxy = max(maxy, max(m12[i]) + 1)
               if self.plots['save_plot']:
                   vals.append(key)
                   data.append(m12[i])
                   if key == 'wind':
                       decpts.append(2)
                   else:
                       decpts.append(1)
           if self.plots['save_plot']:
               titl = 'mthavg'
               dialog = displaytable.Table(map(list, zip(*data)), title=titl, fields=vals, save_folder=self.scenarios, decpts=decpts)
               dialog.exec_()
               del dialog, data, vals
           tx.set_ylim([0, maxy])
           plt.xlim([1, 12])
           plt.xticks(range(1, 13, 1))
           tx.set_xticklabels(mth_labels)
           tx.set_xlabel('Month')
           tx.set_ylabel(self.ylabel[0])
           tx.legend(loc='best')
           if self.two_axes:
               ylim = tx2.get_ylim()
               tx2.set_ylim(0, ylim[1])
               lines = []
               for key in self.ly:
                   lines.append(mlines.Line2D([], [], color=self.colours[key], label=key))
               tx.legend(handles=lines, loc='best')
               tx2.set_ylabel(self.ylabel2[1])
           if self.maximise:
               mng = plt.get_current_fig_manager()
               if sys.platform == 'win32' or sys.platform == 'cygwin':
                   if plt.get_backend() == 'TkAgg':
                       mng.window.state('zoomed')
                   elif plt.get_backend() == 'Qt4Agg':
                       mng.window.showMaximized()
               else:
                   mng.resize(*mng.window.maxsize())
           if self.plots['block']:
               plt.show(block=True)
           else:
               plt.draw()
       if not self.plots['block']:
           plt.show()
    def _plotValues(
        self,
        values,  #dict  TimeSeries values
        plot_label,  #str   Plot-Label
        fig_num,  #int   Figure-number for classify plots
        #      1: average,
        #      2: single trial,
        #      3: average accumulating
        store_dir=None,  #str   Directory to store the plots
        counter=0):  #int   Plotcounter for all trials
        #compute sampling_frequency and classes to plot
        sampling_frequency = values[values.keys()[0]].sampling_frequency
        list_of_classes = values.keys()
        num_of_classes = len(list_of_classes)
        #autoscale color bar or use user scaling
        if self.limits:
            levels = self._compute_levels()
        else:
            levels = None
            #compute maximum and minimum for colorbar scaling if not existing
            vmax = float(max(
                numpy.array(v).max() for v in values.itervalues()))
            vmin = float(min(
                numpy.array(v).min() for v in values.itervalues()))
            levels = self._compute_levels(limits=[vmin, vmax])
            #normalizer=matplotlib.colors.Normalize(vmin=vmin, vmax=vmax)

        #computing time points to show
        num_tpoints = values.values()[0].shape[0]
        all_tpoints = numpy.arange(0, num_tpoints *
                                   (1000 / sampling_frequency),
                                   1000 / sampling_frequency) + self.timeshift

        if self.time_stamps == [-1]:
            tpoints = all_tpoints
        else:  #check if desired time points are existing and confirm
            if not self.time_checked:
                for t in self.time_stamps:
                    if not t in all_tpoints:
                        warnings.warn("Electrode_Coordination_Plot:: At least" \
                                      " one desired time stamp not available!" \
                                      " Legal time stamps are " \
                                      + str(all_tpoints) + ". Switching to " \
                                      "next legal time point. Please check " \
                                      "for consistency!")

                        if t < 0:
                            new_t = self.timeshift
                        else:
                            new_t = range(0, t + 1,
                                          int(1000 / sampling_frequency))[-1]

                            #if we obtain an empty list reset to timeshift
                            if new_t == []:
                                new_t = self.timeshift
                            else:
                                new_t = new_t + self.timeshift

                        #finally check for too high or low values
                        if new_t < self.timeshift:
                            new_t = self.timeshift
                        elif new_t > all_tpoints[-1]:
                            new_t = all_tpoints[-1]

                        self.time_stamps[self.time_stamps.index(t)] = new_t
                self.time_checked = True  #has to be performed only once

            tpoints = numpy.array(self.time_stamps)

        num_of_tpoints = len(tpoints)

        # selecting formatting and clearing figure
        default_size = [8., 6.]
        if self.single_plot:
            num_of_rows = num_of_tpoints
            if num_of_rows > 4:
                default_size[0] = default_size[0] / (int(
                    (num_of_rows + 3) / 4))
                default_size[1] = default_size[1] / (int(
                    (num_of_rows + 3) / 4))
        else:
            num_of_rows = 1

        f = pylab.figure(fig_num,
                         figsize=[
                             default_size[0] * num_of_classes,
                             default_size[1] * num_of_rows
                         ])
        if pylab.get_backend() in pylab.matplotlib.backends.interactive_bk:
            f.show()

        if counter % 20 == 19:  #clear every 20th trial
            pylab.figure(fig_num).clear()

        # Iterate  over the time window
        for time_index in range(num_of_tpoints):

            pylab.subplots_adjust(left=0.025,
                                  right=0.8)  #shift a bit to the left

            if self.single_plot:
                pl_offset = time_index
            else:
                pl_offset = 0

            for index, class_label in enumerate(list_of_classes):
                current_plot_num = (num_of_classes * pl_offset) + index + 1
                pylab.subplot(num_of_rows, num_of_classes, current_plot_num)
                pylab.gca().clear()

                # Get the values for the respective class
                data = values[class_label].view(numpy.ndarray)

                ec = self.get_metadata("electrode_coordinates")
                if ec is None:
                    ec = StreamDataset.ec

                # observe channels
                channel_names = [
                    channel for channel in values[class_label].channel_names
                    if channel in ec.keys()
                ]
                fcn = [
                    channel for channel in values[class_label].channel_names
                    if not channel in ec.keys()
                ]
                if not fcn == []:
                    self._log("Unsupported channels ignored:%s ." % str(fcn),
                              level=logging.CRITICAL)
                if channel_names == []:
                    self._log("No channel for plotting left.",
                              level=logging.CRITICAL)
                    return

                ec_2d = StreamDataset.project2d(ec)

                # Define x and y coordinates of electrodes in the order of the channels
                # of data
                x = numpy.array([ec_2d[key][0] for key in channel_names])
                y = numpy.array([ec_2d[key][1] for key in channel_names])

                #                x = numpy.array([self.electrode_coordinates[key][0] * numpy.cos(self.electrode_coordinates[key][1]/180*numpy.pi)
                #                                        for key in channel_names])
                #                y = numpy.array([self.electrode_coordinates[key][0] * numpy.sin(self.electrode_coordinates[key][1]/180*numpy.pi)
                #                                        for key in channel_names])

                # The values of the electrodes at this point of time
                pos = list(all_tpoints).index(tpoints[time_index])

                z = data[pos, :]

                if self.smooth_corners:
                    x, y, z = self._smooth_corners(x, y, z, data,
                                                   channel_names, pos)

                #griddata returns a masked array
                #you can get the data via zi[~zi.mask]
                zi = griddata(x, y, z, self.xi, self.yi)

                #clip values
                if self.clip and self.limits:
                    zi = numpy.clip(zi, self.limits[0],
                                    self.limits[1])  #minimum and maximum

                # contour the gridded data,
                # plotting dots at the nonuniform data points.

                cs = pylab.contourf(self.xi,
                                    self.yi,
                                    zi,
                                    15,
                                    cmap=pylab.cm.jet,
                                    levels=levels)
                if self.contourlines:
                    pylab.contour(self.xi,
                                  self.yi,
                                  zi,
                                  15,
                                  linewidths=0.5,
                                  colors='k',
                                  levels=levels)

                if self.figlabels:
                    # plot data points.
                    if not self.smooth_corners:
                        pylab.scatter(x, y, c='b', s=5, marker='o')
                    else:
                        # dont plot invented electrode positions
                        pylab.scatter(x[:-4], y[:-4], c='b', s=5, marker='o')
                    # Add channel labels
                    for label, position in ec_2d.iteritems():
                        if label in channel_names:
                            pylab.text(position[0], position[1], label)

                if self.add_info:
                    if counter:
                        if len(list_of_classes) > 1:
                            if index == 0:
                                pylab.text(-120,
                                           -98,
                                           'Trial No. ' + str(counter),
                                           fontsize=12)
                        else:
                            pylab.text(-120,
                                       -98,
                                       'Trial No. ' + str(counter),
                                       fontsize=12)

                if self.nose_ears:
                    #nose
                    ytips = [87.00, 87.00, 97]
                    xtips = [-10.00, 10.00, 0]
                    pylab.fill(xtips, ytips, facecolor='k', edgecolor='none')

                    #left
                    xtips = [-108.0, -113.0, -113.0, -108.0]
                    ytips = [-10.0, -10.0, 10.0, 10.0]
                    pylab.fill(xtips, ytips, facecolor='k', edgecolor='none')

                    #right
                    xtips = [108.0, 114.0, 113.0, 108.0]
                    ytips = [-10.0, -10.0, 10.0, 10.0]
                    pylab.fill(xtips, ytips, facecolor='k', edgecolor='none')

                pylab.xlim(-125, 125)
                pylab.ylim(-100, 100)
                if not self.single_plot or time_index == 0:  #if single_plot=True do only for the first row
                    if self.figtitle:
                        pylab.title(self.figtitle, fontsize=20)
                    else:
                        pylab.title(class_label, fontsize=20)
                pylab.setp(pylab.gca(), xticks=[], yticks=[])
                pylab.draw()

            caxis = pylab.axes([.85, .1, .04, .75])
            cb = pylab.colorbar(mappable=cs, cax=caxis)
            # TODO: The label read 'Amplitude ($\mu$V)'
            #       Removed the unit. Or can we really still assume
            #       a (correct) \muV scale after all preprocessing?
            cb.ax.set_ylabel(r'Amplitude', fontsize=16)

            # Position of the time axes
            ax = pylab.axes([.79, .94, .18, .04])
            pylab.gca().clear()

            pylab.bar(tpoints[time_index],
                      1.0,
                      width=1000.0 / sampling_frequency)
            pylab.xlim(tpoints[0], tpoints[-1])
            pylab.xlabel("time (ms)", fontsize=12)
            pylab.setp(
                ax,
                yticks=[],
                xticks=[all_tpoints[0], tpoints[time_index], all_tpoints[-1]])

            # Draw or store the figure
            if store_dir is None:
                pylab.draw()
                #pylab.show()
            elif self.single_plot and not current_plot_num == (
                    num_of_rows *
                    num_of_classes):  #save only if everything is plotted
                pylab.draw()
                #pylab.show()
            else:
                current_split = self.current_split
                if current_split != 0 and not\
                plot_label.endswith('_split_' + str(current_split)): #more than one split and first call
                    plot_label = plot_label + '_split_' + str(current_split)

                f_name = str(store_dir) + str(
                    os.sep) + str(plot_label) + "_" + str(
                        int(tpoints[time_index]))
                pylab.savefig(f_name + ".png")

        if self.store_data:
            import pickle
            f_name = str(store_dir) + str(os.sep) + str(plot_label)
            pickle.dump(values, open(f_name + ".pickle", 'w'))
示例#11
0
def LogoOverlay(sites, overlayfile, overlay, nperline, sitewidth, rmargin, logoheight, barheight, barspacing):
    """Makes overlay for *LogoPlot*.

    This function creates colored bars overlay bars showing up to two
    properties.
    The trick of this function is to create the bars the right
    size so they align when they overlay the logo plot. 

    CALLING VARIABLES:

    * *sites* : same as the variable of this name used by *LogoPlot*.

    * *overlayfile* is a string giving the name of created PDF file containing
      the overlay. It must end in the extension ``.pdf``.

    * *overlay* : same as the variable of this name used by *LogoPlot*.

    * *nperline* : same as the variable of this name used by *LogoPlot*.

    * *sitewidth* is the width of each site in points.

    * *rmargin* is the right margin in points.

    * *logoheight* is the total height of each logo row in points.

    * *barheight* is the total height of each bar in points.

    * *barspacing* is the vertical spacing between bars in points.

    * *cmap* is a ``pylab`` *LinearSegmentedColorMap* used for the bar coloring.
    """
    if not pylab.get_backend().lower() == 'pdf':
        raise ValueError("You cannot use this function without first setting the matplotlib / pylab backend to 'pdf'. Do this with: matplotlib.use('pdf')")
    if os.path.splitext(overlayfile)[1] != '.pdf':
        raise ValueError("overlayfile must end in .pdf: %s" % overlayfile)
    (cmap, mapping_d, mapper) = KyteDoolittleColorMapping()
    pts_per_inch = 72.0 # to convert between points and inches
    # some general properties of the plot
    matplotlib.rc('text', usetex=True)
    matplotlib.rc('xtick', labelsize=9)
    matplotlib.rc('xtick', direction='out')
    matplotlib.rc('ytick', direction='out')
    matplotlib.rc('axes', linewidth=0.5)
    matplotlib.rc('ytick.major', size=3)
    matplotlib.rc('xtick.major', size=2.5)
    # define sizes (still in points)
    colorbar_bmargin = 20 # margin below color bars in points
    colorbar_tmargin = 15 # margin above color bars in points
    nlines = int(math.ceil(len(sites) / float(nperline)))
    lmargin = 25 # left margin in points
    barwidth = nperline * sitewidth
    figwidth = lmargin + rmargin + barwidth
    figheight = nlines * (logoheight + len(overlay) * (barheight + barspacing)) + barheight + colorbar_bmargin + colorbar_tmargin
    # set up the figure and axes
    fig = pylab.figure(figsize=(figwidth / pts_per_inch, figheight / pts_per_inch))
    # determine property types
    prop_types = {}
    for (prop_d, shortname, longname) in overlay:
        if all([isinstance(prop, str) for prop in prop_d.itervalues()]):
            proptype = 'discrete'
            propcategories = list(set(prop_d.values()))
            propcategories.sort()
            (vmin, vmax) = (0, len(propcategories) - 1)
        elif all ([isinstance(prop, (int, float)) for prop in prop_d.itervalues()]):
            proptype = 'continuous'
            propcategories = None
            (vmin, vmax) = (min(prop_d.values()), max(prop_d.values()))
            # If vmin is slightly greater than zero, set it to zero. This helps for RSA properties.
            if vmin >= 0 and vmin / float(vmax - vmin) < 0.05:
                vmin = 0.0
                # And if vmax is just a bit less than one, set it to that...
                if 0.9 <= vmax <= 1.0:
                    vmax = 1.0
        else:
            raise ValueError("Property %s is neither continuous or discrete. Values are:\n%s" % (shortname, str(prop_d.items())))
        prop_types[shortname] = (proptype, vmin, vmax, propcategories)
    assert len(prop_types) == len(overlay), "Not as many property types as overlays. Did you give the same name (shortname) to multiple properties in the overlay?"
    # loop over each line of the multi-lined plot
    prop_image = {}
    for iline in range(nlines):
        isites = sites[iline * nperline : min(len(sites), (iline + 1) * nperline)]
        xlength = len(isites) * sitewidth
        logo_ax = pylab.axes([lmargin / figwidth, ((nlines - iline - 1) * (logoheight + len(overlay) * (barspacing + barheight))) / figheight, xlength / figwidth, logoheight / figheight], frameon=False)
        logo_ax.yaxis.set_ticks_position('none')
        logo_ax.xaxis.set_ticks_position('none')
        pylab.yticks([])
        pylab.xlim(0.5, len(isites) + 0.5)
        pylab.xticks([])
        for (iprop, (prop_d, shortname, longname)) in enumerate(overlay):
            (proptype, vmin, vmax, propcategories) = prop_types[shortname]
            prop_ax = pylab.axes([lmargin / figwidth, ((nlines - iline - 1) * (logoheight + len(overlay) * (barspacing + barheight)) + logoheight + iprop * (barspacing + barheight)) / figheight, xlength / figwidth, barheight / figheight], frameon=True)
            prop_ax.xaxis.set_ticks_position('none')
            prop_ax.yaxis.set_ticks_position('left')
            pylab.xticks([])
            pylab.yticks([0], [shortname], size=8)
            pylab.xlim((0, len(isites)))
            pylab.ylim(-0.5, 0.5)
            propdata = pylab.zeros(shape=(1, len(isites)))
            propdata[ : ] = pylab.nan # set to nan for all entries
            for (isite, site) in enumerate(isites):
                if site in prop_d:
                    if proptype == 'continuous':
                        propdata[(0, isite)] = prop_d[site]
                    elif proptype == 'discrete':
                        propdata[(0, isite)] = propcategories.index(prop_d[site])
                    else:
                        raise ValueError('neither continuous nor discrete')
            prop_image[shortname] = pylab.imshow(propdata, interpolation='nearest', aspect='auto', extent=[0, len(isites), 0.5, -0.5], cmap=cmap, vmin=vmin, vmax=vmax)
            pylab.yticks([0], [shortname], size=8)
    # set up colorbar axes, then color bars
    if len(overlay) == 1:
        colorbarwidth = 0.4
        colorbarspacingwidth = 1.0 - colorbarwidth
    else:
        colorbarspacingfrac = 0.5 # space between color bars is this fraction of bar width
        colorbarwidth = 1.0 / (len(overlay) * (1.0 + colorbarspacingfrac)) # width of color bars in fraction of figure width
        colorbarspacingwidth = colorbarwidth * colorbarspacingfrac # width of color bar spacing in fraction of figure width
    propnames = {}
    for (icolorbar, (prop_d, shortname, longname)) in enumerate(overlay):
        (proptype, vmin, vmax, propcategories) = prop_types[shortname]
        if shortname == longname or not longname:
            propame = shortname
        else:
            propname = "%s (%s)" % (longname, shortname)
#        colorbar_ax = pylab.axes([colorbarspacingwidth * 0.5 + icolorbar * (colorbarwidth + colorbarspacingwidth), 1.0 - (colorbar_tmargin + barheight) / figwidth, colorbarwidth, barheight / figwidth], frameon=True)
        colorbar_ax = pylab.axes([colorbarspacingwidth * 0.5 + icolorbar * (colorbarwidth + colorbarspacingwidth), 1.0 - (colorbar_tmargin + barheight) / figheight, colorbarwidth, barheight / figheight], frameon=True)
        colorbar_ax.xaxis.set_ticks_position('bottom')
        colorbar_ax.yaxis.set_ticks_position('none')
        pylab.xticks([])
        pylab.yticks([])
        pylab.title(propname, size=9)
        if proptype == 'continuous':
            cb = pylab.colorbar(prop_image[shortname], cax=colorbar_ax, orientation='horizontal')
            # if range is close to zero to one, manually set tics to 0, 0.5, 1. This helps for RSA
            if -0.1 <= vmin <= 0 and 1.0 <= vmax <= 1.15:
                cb.set_ticks([0, 0.5, 1])
                cb.set_ticklabels(['0', '0.5', '1'])
        elif proptype == 'discrete':
            cb = pylab.colorbar(prop_image[shortname], cax=colorbar_ax, orientation='horizontal', boundaries=[i for i in range(len(propcategories) + 1)], values=[i for i in range(len(propcategories))])
            cb.set_ticks([i + 0.5 for i in range(len(propcategories))])
            cb.set_ticklabels(propcategories)
        else:
            raise ValueError("Invalid proptype")
    # save the plot
    pylab.savefig(overlayfile, transparent=True)
示例#12
0
import os as _os
import sys as _sys
import matplotlib as _mpl
import pylab

# Try to run the qt magic first
try:
    if not pylab.get_backend()[0:2] == 'Qt':
        get_ipython().run_line_magic('matplotlib', 'qt')
except:
    pass

import traceback as _traceback
_sys.excepthook = _traceback.print_exception
_p = _traceback.print_last

# ignore warnings by default
import warnings as _warnings
_warnings.simplefilter("ignore")
_qtapp = None

# Import databox first
from . import _data as data
from . import _functions as fun
from . import _thread as thread
from . import _settings
settings = _settings.settings()
fun._settings = settings
data._settings = settings

# Get the version
示例#13
0
       def dayPlot(self, period, data, locn, per_labels=None, x_labels=None):
           plt.figure(period)
           plt.suptitle(self.hdrs[period] + locn, fontsize=16)
           maxy = 0
           maxw = 0
           if len(data[0]) > 9:
               p_y = 3
               p_x = 4
               xl = 8
               yl = [0, 4, 8]
               yl2 = [3, 7, 11]
           elif len(data[0]) > 6:
               p_y = 3
               p_x = 3
               xl = 6
               yl = [0, 3]
               yl2 = [2, 5]
           elif len(data[0]) > 4:
               p_y = 2
               p_x = 3
               xl = 3
               yl = [0, 3]
               yl2 = [2, 5]
           elif len(data[0]) > 2:
               p_y = 2
               p_x = 2
               xl = 2
               yl = [0, 2]
               yl2 = [1, 3]
           else:
               p_y = 1
               p_x = 2
               xl = 0
               yl = [0, 1]
               yl2 = [0, 1]
           wi = -1
           ra = -1
           te = -1
           i = -1
           for key, value in iter(sorted(self.ly.items())):
               i += 1
               if key == 'wind':
                   wi = i
               elif key == 'temp':
                   te = i
               elif key == 'rain':
                   ra = i
           for p in range(len(data[0])):
               for i in range(len(ly)):
                   maxy = max(maxy, max(data[i][p]))
                   if i == wi or i == te or i == ra:
                       maxw = max(maxw, max(data[i][p]))
           for p in range(len(data[0])):
               px = plt.subplot(p_y, p_x, p + 1)
               i = -1
               if self.two_axes:
                   px2 = px.twinx()
               for key, value in iter(sorted(self.ly.items())):
                   i += 1
                   lw = 2.0
                   if self.two_axes and key in self.ylabel2[0]:
                       px2.plot(x24, data[i][p], linewidth=lw, label=key, color=self.colours[key])
                   else:
                       px.plot(x24, data[i][p], linewidth=lw, label=key, color=self.colours[key])
                   plt.title(per_labels[p])
               plt.xlim([1, 24])
               plt.xticks(list(range(4, 25, 4)))
      #         px.set_xticklabels(labels])
 #              plt.xticks(range(0, 25, 4))
          #     plt.grid(axis='x')
               px.set_xticklabels(x_labels[1:])
               px.set_ylim([0, maxy])
               if self.two_axes:
                   px2.set_ylim(0, maxw)
                   if p in yl2:
                       px2.set_ylabel(self.ylabel2[2])
               if p >= xl:
                   px.set_xlabel('Hour of the Day')
               if p in yl:
                   px.set_ylabel(self.ylabel[1])
           if self.two_axes:
               lines = []
               for key in self.ly:
                   lines.append(mlines.Line2D([], [], color=self.colours[key], label=key))
               px.legend(handles=lines, loc='best')
           else:
               px.legend(loc='best')
           if self.maximise:
               mng = plt.get_current_fig_manager()
               if sys.platform == 'win32' or sys.platform == 'cygwin':
                   if plt.get_backend() == 'TkAgg':
                       mng.window.state('zoomed')
                   elif plt.get_backend() == 'Qt4Agg':
                       mng.window.showMaximized()
               else:
                   mng.resize(*mng.window.maxsize())
           if self.plots['block']:
               plt.show(block=True)
           else:
               plt.draw()
示例#14
0

import system as sys
import network3N as netw
import traces as tra
import info as nf
import torus as tor
import pylab as pl

pos_info = '+0+600'
pos_tra = '+300+600'
pos_net = '+300+0'
pos_sys = '+0+0'
pos_torus = '+800+0'

info = nf.info(position=pos_info)
net = netw.network(g_inh=0.015, info=info, position=pos_net)
system = sys.system(info=info, position=pos_sys, network=net)
traces = tra.traces(system, net, info=info, position=pos_tra)
torus = tor.torus(system, net, traces, info=info, position=pos_torus)

net.system = system
system.traces = traces

if pl.get_backend() == 'TkAgg':
	system.fig.tight_layout()
	traces.fig.tight_layout()
	torus.fig.tight_layout()

pl.show()
示例#15
0
    def _plotValues(
        self,
        values,  #dict  TimeSeries values
        plot_label,  #str   Plot-Label
        fig_num,  #int   Figure-number for classify plots
        #      1: average,
        #      2: single trial,
        #      3: average accumulating
        store_dir=None,  #str   Directory to store the plots
        counter=0):  #int   Plotcounter for all trialsdef plot_values

        sampling_frequency = values[values.keys()[0]].sampling_frequency
        list_of_classes = values.keys()
        num_of_classes = len(list_of_classes)

        #computing time points to show
        #num_tpoints = values.values()[0].shape[0]

        pylab.subplots_adjust(
            left=0.05,  # the left side of the subplots of the figure
            right=0.95,  # the right side of the subplots of the figure
            bottom=0.05,  # the bottom of the subplots of the figure
            top=0.95,  # the top of the subplots of the figure
            wspace=
            0.15,  # the amount of width reserved for blank space between subplots
            hspace=
            0.1,  # the amount of height reserved for white space between subplots                          
        )

        #plot all channels separately in one figure
        #plot just 1 channel
        if self.channel_names != None and len(self.channel_names) == 1:

            f = pylab.figure(fig_num, figsize=(18, 13))

            #assure that figure is displayed with an interactive backend
            if pylab.get_backend() in pylab.matplotlib.backends.interactive_bk:
                f.show()

            for index, class_label in enumerate(list_of_classes):

                assert (self.channel_names[0] in values[class_label].channel_names),\
                    "SpectrumPlot::Channel requested for plotting is not available in data"

                channel_index = values[class_label].channel_names.index(
                    self.channel_names[0])

                #operations like splicing only on view of object
                data = values[class_label].view(numpy.ndarray)

                pylab.subplot(1, num_of_classes, index + 1)
                title = pylab.title(
                    str(self.channel_names) + ' ' + class_label)

                self._plot_spectrum(data[:, channel_index], sampling_frequency)

            # Draw or store the figure
            if store_dir is None:
                pylab.draw()
            else:
                current_split = self.current_split
                if current_split != 0 and not\
                plot_label.endswith('_split_' + str(current_split)): #more than one split and first call
                    plot_label = plot_label + '_split_' + str(current_split)

                f_name = str(store_dir) + str(os.sep) + str(plot_label)

                pylab.savefig(f_name + ".png")

        #plot more than one channel in one figure for each label
        else:

            for index, class_label in enumerate(list_of_classes):
                title = pylab.title(class_label)

                if self.channel_names == None:  #this means all channels are plotted
                    self.channel_names = values[class_label].channel_names

                f = pylab.figure(fig_num, figsize=(18, 13))

                #assure that figure is displayed with an interactive backend
                if pylab.get_backend(
                ) in pylab.matplotlib.backends.interactive_bk:
                    f.show()

                number_of_channels = len(self.channel_names)
                # Compute number of rows and cols for subplot-arrangement:
                # use 8 as upper limit for cols and compute rows accordingly
                if number_of_channels <= 8:
                    nr_of_cols = number_of_channels
                else:
                    nr_of_cols = 8
                    nr_of_rows = (number_of_channels - 1) / 8 + 1

                data = values[class_label].view(numpy.ndarray)

                ec = self.getMetadata("electrode_coordinates")
                if ec is None:
                    ec = StreamDataset.ec

                ec_2d = StreamDataset.project2d(ec)

                # plot everything channel-wise
                for channel_index in range(number_of_channels):
                    channel_name = self.channel_names[channel_index]

                    f.add_subplot(nr_of_rows, nr_of_cols, channel_index + 1)

                    pylab.title(channel_name)

                    # actual plotting of the data
                    self._plot_spectrum(data[:, channel_index],
                                        sampling_frequency)

                    if self.physiological_arrangement:
                        x, y = ec_2d[channel_name]
                        w = .05
                        h = .045
                        pylab.gca().set_position([(x + 110) / 220,
                                                  (y + 110) / 220, w, h])

                pylab.draw()

                # Draw or store the figure
                if store_dir is None:
                    pylab.draw()
                else:
                    current_split = self.current_split
                    if current_split != 0 and not\
                    plot_label.endswith('_split_' + str(current_split)): #more than one split and first call
                        plot_label = plot_label + '_split_' + str(
                            current_split)

                    f_name = str(store_dir) + str(
                        os.sep) + str(plot_label) + '_' + class_label

                    pylab.savefig(f_name + ".png")
示例#16
0
    def _plotValues(
        self,
        values,  #dict  TimeSeries values
        plot_label,  #str   Plot-Label
        fig_num,  #int   Figure-number for classify plots
        #      1: average,
        #      2: single trial,
        #      3: average accumulating
        store_dir=None,  #str   Directory to store the plots
        counter=0):  #int   Plotcounter for all trials

        if self.class_difference:
            #we have to compute the difference
            list_of_classes = values.keys()
            num_of_classes = len(list_of_classes)
            if num_of_classes != 2:
                warnings.warn(
                    "TimeSeriesPlot:: Difference plots only possible for two classes  Plotting ignored!"
                )
                return
            data1 = values[list_of_classes[0]].view(numpy.ndarray)
            data2 = values[list_of_classes[1]].view(numpy.ndarray)

            #construct new TimeSeries with differences
            data = TimeSeries(
                data1 - data2,
                channel_names=values[list_of_classes[0]].channel_names,
                sampling_frequency=values[
                    list_of_classes[0]].sampling_frequency)
            #overwrite old incoming values
            values = dict(difference=data)

        sampling_frequency = values[values.keys()[0]].sampling_frequency
        list_of_classes = values.keys()
        num_of_classes = len(list_of_classes)

        #computing time points to show
        num_tpoints = values.values()[0].shape[0]
        all_tpoints = numpy.arange(0, num_tpoints *
                                   (1000 / sampling_frequency),
                                   1000 / sampling_frequency) + self.timeshift

        pylab.subplots_adjust(
            left=0.05,  # the left side of the subplots of the figure
            right=0.95,  # the right side of the subplots of the figure
            bottom=0.05,  # the bottom of the subplots of the figure
            top=0.95,  # the top of the subplots of the figure
            wspace=
            0.15,  # the amount of width reserved for blank space between subplots
            hspace=
            0.1,  # the amount of height reserved for white space between subplots                          
        )

        f = pylab.figure(fig_num, figsize=(18, 13))
        #assure that figure is displayed with an interactive backend
        if pylab.get_backend() in pylab.matplotlib.backends.interactive_bk:
            f.show()
        #plot all channels separately in one figure
        if self.separate_channels:
            self._plot_all_channels_separated(all_tpoints, values)
        else:
            for index, class_label in enumerate(list_of_classes):

                data = values[class_label].view(numpy.ndarray)

                axis = pylab.subplot(1, num_of_classes, index + 1)
                pylab.gca().clear()

                #plot just 1 channel
                if self.channel_names != None and len(self.channel_names) == 1:
                    assert (self.channel_names[0] in values[class_label].channel_names),\
                            "TimeSeriesPlot::Channel requested for plotting is not available in data"
                    channel_index = values[class_label].channel_names.index(
                        self.channel_names[0])
                    # Update minimal and maximal value
                    self.min_value = min(self.min_value,
                                         min(data[:, channel_index].flatten()))
                    self.max_value = max(self.max_value,
                                         max(data[:, channel_index].flatten()))

                    title = pylab.title(
                        str(self.channel_names) + ' ' + class_label)
                    pylab.plot(all_tpoints, data[:, channel_index])

                #plot all channels as matrix
                else:
                    self._plot_all_channels(data, all_tpoints,
                                            values[class_label].channel_names)
                    title = pylab.title(class_label)

                title.set_fontsize(24)
                pylab.draw()

        # Draw or store the figure
        if store_dir is None:
            pylab.draw()
        else:
            current_split = self.current_split
            if current_split != 0 and not\
            plot_label.endswith('_split_' + str(current_split)): #more than one split and first call
                plot_label = plot_label + '_split_' + str(current_split)

            f_name = str(store_dir) + str(os.sep) + str(plot_label)
            pylab.savefig(f_name + ".png")
示例#17
0
import system as sys
import network as netw
import traces as tra
import info as nf
import torus as tor
import pylab as pl

# root = Tkinter.Tk()
# screen_width = root.winfo_screenwidth()
# screen_height = root.winfo_screenheight()

pos_info = "+0+600"
pos_tra = "+300+600"
pos_net = "+300+0"
pos_sys = "+0+0"
pos_torus = "+800+0"

i = nf.info(position=pos_info)
s = sys.system(info=i, position=pos_sys)
n = netw.network(info=i, position=pos_net, g_inh=0.0055)
t = tra.traces(s, n, info=i, position=pos_tra)
T = tor.torus(s, n, t, info=i, position=pos_torus)

n.traces = t

if pl.get_backend() == "TkAgg":
    s.fig.tight_layout()
    t.fig.tight_layout()

pl.show()
示例#18
0
    def _plotValues(self,
                    values,            #dict  TimeSeries values
                    plot_label,        #str   Plot-Label
                    fig_num,           #int   Figure-number for classify plots
                                       #      1: average,
                                       #      2: single trial,
                                       #      3: average accumulating
                    store_dir = None,  #str   Directory to store the plots
                    counter=0):        #int   Plotcounter for all trialsdef plot_values
                   
        sampling_frequency = values[values.keys()[0]].sampling_frequency
        list_of_classes = values.keys()
        num_of_classes = len(list_of_classes)
             
        #computing time points to show
        #num_tpoints = values.values()[0].shape[0]

        pylab.subplots_adjust(left  = 0.05,  # the left side of the subplots of the figure
                      right = 0.95,    # the right side of the subplots of the figure
                      bottom = 0.05,   # the bottom of the subplots of the figure
                      top = 0.95,      # the top of the subplots of the figure
                      wspace = 0.15,   # the amount of width reserved for blank space between subplots
                      hspace = 0.1,   # the amount of height reserved for white space between subplots                          
                      )

        #plot all channels separately in one figure
        #plot just 1 channel
        if self.channel_names != None and len(self.channel_names)==1:
            
            f=pylab.figure(fig_num, figsize = (18,13))

            #assure that figure is displayed with an interactive backend
            if pylab.get_backend() in pylab.matplotlib.backends.interactive_bk:
                f.show()
            
            for index, class_label in enumerate(list_of_classes):
                
                assert (self.channel_names[0] in values[class_label].channel_names),\
                    "SpectrumPlot::Channel requested for plotting is not available in data"
                       
                channel_index = values[class_label].channel_names.index(self.channel_names[0])  
                
                #operations like splicing only on view of object
                data = values[class_label].view(numpy.ndarray)                
                
                pylab.subplot(1, num_of_classes, index + 1)
                title = pylab.title(str(self.channel_names) + ' ' + class_label)
                
                self._plot_spectrum(data[:,channel_index], sampling_frequency)
                
            # Draw or store the figure
            if store_dir is None:
                pylab.draw()
            else:
                current_split=self.current_split
                if current_split != 0 and not\
                plot_label.endswith('_split_' + str(current_split)): #more than one split and first call
                    plot_label = plot_label + '_split_' + str(current_split)
                    
                f_name=str(store_dir) + str(os.sep) + str(plot_label)

                pylab.savefig(f_name + ".png")                                      

        #plot more than one channel in one figure for each label
        else:
            
            for index, class_label in enumerate(list_of_classes): 
                title = pylab.title(class_label)
                
                if self.channel_names==None: #this means all channels are plotted
                    self.channel_names=values[class_label].channel_names
                
                f=pylab.figure(fig_num, figsize = (18,13))
                
                #assure that figure is displayed with an interactive backend
                if pylab.get_backend() in pylab.matplotlib.backends.interactive_bk:
                    f.show()
                
                number_of_channels=len(self.channel_names)
                # Compute number of rows and cols for subplot-arrangement:
                # use 8 as upper limit for cols and compute rows accordingly
                if number_of_channels <= 8: 
                    nr_of_cols = number_of_channels
                else: 
                    nr_of_cols = 8
                    nr_of_rows = (number_of_channels - 1) / 8 + 1
                    
                data = values[class_label].view(numpy.ndarray)
                
                
                ec = self.getMetadata("electrode_coordinates")
                if ec is None:
                    ec = StreamDataset.ec
                
                ec_2d = StreamDataset.project2d(ec)
                
                # plot everything channel-wise
                for channel_index in range(number_of_channels):
                    channel_name  = self.channel_names[channel_index]

                    f.add_subplot(nr_of_rows, nr_of_cols, channel_index + 1)
                    
                    pylab.title(channel_name)
                    
                    # actual plotting of the data
                    self._plot_spectrum(data[:,channel_index], sampling_frequency)
                        
                    if self.physiological_arrangement:
                        x, y = ec_2d[channel_name]
                        w = .05
                        h = .045
                        pylab.gca().set_position([(x + 110) / 220, (y + 110) / 220, w, h])
                        
                pylab.draw()
                
                # Draw or store the figure
                if store_dir is None:
                    pylab.draw()
                else:
                    current_split=self.current_split
                    if current_split != 0 and not\
                    plot_label.endswith('_split_' + str(current_split)): #more than one split and first call
                        plot_label = plot_label + '_split_' + str(current_split)
                        
                    f_name=str(store_dir) + str(os.sep) + str(plot_label) + '_' + class_label
    
                    pylab.savefig(f_name + ".png") 
示例#19
0
- frame_compare     Display frames from two sequences and their difference.
"""

# Copyright (c) 2009-2015, Lev Givon
# All rights reserved.
# Distributed under the terms of the BSD license:
# http://www.opensource.org/licenses/bsd-license

__all__ = ['animate', 'animate2', 'animate_compare', 'frame_compare']

import time
import numpy as np
import pylab as p

# Fix for animation problems with Qt4Agg backend:
if p.get_backend() == 'Qt4Agg':
    from PyQt4.QtGui import QApplication
    animate_fix = QApplication.processEvents
else:

    def animate_fix():
        pass


def animate(data, step=1, delay=0):
    """
    Animate sequence of frames.

    Animate a sequence of `Ny x Nx` bitmap frames stored in a `M x Ny x Nx` data
    array.
示例#20
0
#!/usr/bin/env python

import system as sys
import traces as tra
import info as nf
import pylab as pl

pos_info = '+0+600'
pos_tra = '+300+600'
pos_sys = '+0+0'

i = nf.info(position=pos_info)
s = sys.system(info=i, position=pos_sys)
t = tra.traces(s, info=i, position=pos_tra)

if pl.get_backend() == 'TkAgg':
    s.fig.tight_layout()
    t.fig.tight_layout()

pl.show()
import os
if os.environ['USER'] == 'ucabtok': os.environ['MPLCONFIGDIR']='.'
import matplotlib as mpl
if 'DISPLAY' not in os.environ:
    mpl.use('agg')
import os, yaml, argparse, sys, logging , pyfits, tabletools, cosmology, filaments_tools, plotstools, mathstools, scipy, scipy.stats, time
import numpy as np
import pylab as pl
import tktools as tt
print 'using matplotlib backend' , pl.get_backend()
# import matplotlib as mpl;
# from matplotlib import figure;
pl.rcParams['image.interpolation'] = 'nearest' ; 
import scipy.interpolate as interp
from sklearn.neighbors import BallTree as BallTree
import cPickle as pickle
import filaments_model_1h
import filaments_model_1f
import filaments_model_2hf
import nfw
import shutil


logger = logging.getLogger("filam..fit") 
logger.setLevel(logging.INFO)  
log_formatter = logging.Formatter("%(asctime)s %(name)s %(levelname)s   %(message)s ","%Y-%m-%d %H:%M:%S")
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(log_formatter)
logger.addHandler(stream_handler)
logger.propagate = False
示例#22
0
   def showGraphs(self, ly, x, locn):
       def dayPlot(self, period, data, locn, per_labels=None, x_labels=None):
           plt.figure(period)
           plt.suptitle(self.hdrs[period] + locn, fontsize=16)
           maxy = 0
           maxw = 0
           if len(data[0]) > 9:
               p_y = 3
               p_x = 4
               xl = 8
               yl = [0, 4, 8]
               yl2 = [3, 7, 11]
           elif len(data[0]) > 6:
               p_y = 3
               p_x = 3
               xl = 6
               yl = [0, 3]
               yl2 = [2, 5]
           elif len(data[0]) > 4:
               p_y = 2
               p_x = 3
               xl = 3
               yl = [0, 3]
               yl2 = [2, 5]
           elif len(data[0]) > 2:
               p_y = 2
               p_x = 2
               xl = 2
               yl = [0, 2]
               yl2 = [1, 3]
           else:
               p_y = 1
               p_x = 2
               xl = 0
               yl = [0, 1]
               yl2 = [0, 1]
           wi = -1
           ra = -1
           te = -1
           i = -1
           for key, value in iter(sorted(self.ly.items())):
               i += 1
               if key == 'wind':
                   wi = i
               elif key == 'temp':
                   te = i
               elif key == 'rain':
                   ra = i
           for p in range(len(data[0])):
               for i in range(len(ly)):
                   maxy = max(maxy, max(data[i][p]))
                   if i == wi or i == te or i == ra:
                       maxw = max(maxw, max(data[i][p]))
           for p in range(len(data[0])):
               px = plt.subplot(p_y, p_x, p + 1)
               i = -1
               if self.two_axes:
                   px2 = px.twinx()
               for key, value in iter(sorted(self.ly.items())):
                   i += 1
                   lw = 2.0
                   if self.two_axes and key in self.ylabel2[0]:
                       px2.plot(x24, data[i][p], linewidth=lw, label=key, color=self.colours[key])
                   else:
                       px.plot(x24, data[i][p], linewidth=lw, label=key, color=self.colours[key])
                   plt.title(per_labels[p])
               plt.xlim([1, 24])
               plt.xticks(list(range(4, 25, 4)))
      #         px.set_xticklabels(labels])
 #              plt.xticks(range(0, 25, 4))
          #     plt.grid(axis='x')
               px.set_xticklabels(x_labels[1:])
               px.set_ylim([0, maxy])
               if self.two_axes:
                   px2.set_ylim(0, maxw)
                   if p in yl2:
                       px2.set_ylabel(self.ylabel2[2])
               if p >= xl:
                   px.set_xlabel('Hour of the Day')
               if p in yl:
                   px.set_ylabel(self.ylabel[1])
           if self.two_axes:
               lines = []
               for key in self.ly:
                   lines.append(mlines.Line2D([], [], color=self.colours[key], label=key))
               px.legend(handles=lines, loc='best')
           else:
               px.legend(loc='best')
           if self.maximise:
               mng = plt.get_current_fig_manager()
               if sys.platform == 'win32' or sys.platform == 'cygwin':
                   if plt.get_backend() == 'TkAgg':
                       mng.window.state('zoomed')
                   elif plt.get_backend() == 'Qt4Agg':
                       mng.window.showMaximized()
               else:
                   mng.resize(*mng.window.maxsize())
           if self.plots['block']:
               plt.show(block=True)
           else:
               plt.draw()
       papersizes = {'a0': '33.1,46.8', 'a1': '23.4,33.1', 'a2': '16.5,23.4',
                   'a3': '11.7,16.5', 'a4': '8.3,11.7', 'a5': '5.8,8.3',
                   'a6': '4.1,5.8', 'a7': '2.9,4.1', 'a8': '2,2.9',
                   'a9': '1.5,2', 'a10': '1,1.5', 'b0': '39.4,55.7',
                   'b1': '27.8,39.4', 'b2': '19.7,27.8', 'b3': '13.9,19.7',
                   'b4': '9.8,13.9', 'b5': '6.9,9.8', 'b6': '4.9,6.9',
                   'b7': '3.5,4.9', 'b8': '2.4,3.5', 'b9': '1.7,2.4',
                   'b10': '1.2,1.7', 'foolscap': '8.0,13.0', 'ledger': '8.5,14.0',
                   'legal': '8.5,14.09', 'letter': '8.5,11.0'}
       landscape = False
       papersize = ''
       config = configparser.RawConfigParser()
       if len(sys.argv) > 1:
           config_file = sys.argv[1]
       else:
           config_file = getModelFile('SIREN.ini')
       config.read(config_file)
       self.maximise = False
       seasons = []
       periods = []
       parents = []
       try:
           parents = getParents(config.items('Parents'))
       except:
           pass
       try:
           self.scenarios = config.get('Files', 'scenarios')
           for key, value in parents:
               self.scenarios = self.scenarios.replace(key, value)
           self.scenarios = self.scenarios.replace('$USER$', getUser())
           self.scenarios = self.scenarios.replace('$YEAR$', str(self.base_year))
           i = self.scenarios.rfind('/')
           self.scenarios = self.scenarios[:i + 1]
       except:
           self.scenarios = ''
       try:
           items = config.items('Power')
           for item, values in items:
               if item[:6] == 'season':
                   if item == 'season':
                       continue
                   i = int(item[6:]) - 1
                   if i >= len(seasons):
                       seasons.append([])
                   seasons[i] = values.split(',')
                   for j in range(1, len(seasons[i])):
                       seasons[i][j] = int(seasons[i][j]) - 1
               elif item[:6] == 'period':
                   if item == 'period':
                       continue
                   i = int(item[6:]) - 1
                   if i >= len(periods):
                       periods.append([])
                   periods[i] = values.split(',')
                   for j in range(1, len(periods[i])):
                       periods[i][j] = int(periods[i][j]) - 1
               elif item == 'maximise':
                   if values.lower() in ['true', 'on', 'yes']:
                       self.maximise = True
               elif item == 'save_format':
                   plt.rcParams['savefig.format'] = values
               elif item == 'figsize':
                   try:
                       papersize = papersizes[values]
                   except:
                       papersize = values
               elif item == 'orientation':
                   if values.lower()[0] == 'l':
                       landscape = True
       except:
           pass
       if papersize != '':
           if landscape:
               bit = papersize.split(',')
               plt.rcParams['figure.figsize'] = bit[1] + ',' + bit[0]
           else:
               plt.rcParams['figure.figsize'] = papersize
       if len(seasons) == 0:
           seasons = [['Summer', 11, 0, 1], ['Autumn', 2, 3, 4], ['Winter', 5, 6, 7], ['Spring', 8, 9, 10]]
       if len(periods) == 0:
           periods = [['Winter', 4, 5, 6, 7, 8, 9], ['Summer', 10, 11, 0, 1, 2, 3]]
       for i in range(len(periods)):
           for j in range(len(seasons)):
               if periods[i][0] == seasons[j][0]:
                   periods[i][0] += '2'
                   break
       mth_labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
       ssn_labels = []
       for i in range(len(seasons)):
           ssn_labels.append('%s (%s-%s)' % (seasons[i][0], mth_labels[seasons[i][1]],
                              mth_labels[seasons[i][-1]]))
     #   ssn_labels = ['Summer (Dec, Jan-Feb)', 'Autumn (Mar-May)', 'Winter (Jun-Aug)', 'Spring(Sep-Nov)']
       smp_labels = []
       for i in range(len(periods)):
           smp_labels.append('%s (%s-%s)' % (periods[i][0], mth_labels[periods[i][1]],
                              mth_labels[periods[i][-1]]))
    #    smp_labels = ['Winter (May-Oct)', 'Summer (Nov-Apr)']
       labels = ['0:00', '4:00', '8:00', '12:00', '16:00', '20:00', '24:00']
       mth_xlabels = ['0:', '4:', '8:', '12:', '16:', '20:', '24:']
       m = 0
       d = 1
       day_labels = []
       while m < len(the_days):
           day_labels.append('%s %s' % (str(d), mth_labels[m]))
           d += 7
           if d > the_days[m]:
               d = d - the_days[m]
               m += 1
       lbl_font = FontProperties()
       lbl_font.set_size('small')
       x24 = []
       l24 = []
       m24 = []
       q24 = []
       s24 = []
       t12 = []
       for i in range(24):
           x24.append(i + 1)
       for i in range(len(self.ly)):
           if self.plots['total']:
               l24.append([])
               for j in range(24):
                   l24[i].append(0.)
           if self.plots['month']:
               m24.append([])
               for m in range(12):
                   m24[i].append([])
                   for j in range(24):
                       m24[i][m].append(0.)
           if self.plots['season']:
               q24.append([])
               for q in range(len(seasons)):
                   q24[i].append([])
                   for j in range(24):
                       q24[i][q].append(0.)
           if self.plots['period']:
               s24.append([])
               for s in range(len(periods)):
                   s24[i].append([])
                   for j in range(24):
                       s24[i][s].append(0.)
           if self.plots['monthly'] or self.plots['mthavg']:
               t12.append([])
               for m in range(14):
                   t12[i].append(0.)
       the_qtrs = []
       for i in range(len(seasons)):
           d = 0
           for j in range(1, len(seasons[i])):
               d += the_days[seasons[i][j]]
           the_qtrs.append(d)
       the_ssns = []
       for i in range(len(periods)):
           d = 0
           for j in range(1, len(periods[i])):
               d += the_days[periods[i][j]]
           the_ssns.append(d)
       the_hours = [0]
       i = 0
       for m in range(len(the_days)):
           i = i + the_days[m] * 24
           the_hours.append(i)
       d = -1
       for i in range(0, len(x), 24):
           m = 11
           d += 1
           while i < the_hours[m] and m > 0:
               m -= 1
           for k in range(24):
               j = -1
               for key, value in iter(sorted(self.ly.items())):
                   if len(value) == 0:
                       continue
                   j += 1
                   if self.plots['total']:
                       l24[j][k] += value[i + k]
                   if self.plots['month']:
                       m24[j][m][k] = m24[j][m][k] + value[i + k]
                   if self.plots['season']:
                       for q in range(len(seasons)):
                           if m in seasons[q]:
                               break
                       q24[j][q][k] = q24[j][q][k] + value[i + k]
                   if self.plots['period']:
                       for s in range(len(periods)):
                           if m in periods[s]:
                               break
                       s24[j][s][k] = s24[j][s][k] + value[i + k]
                   if self.plots['monthly'] or self.plots['mthavg']:
                       t12[j][m + 1] = t12[j][m + 1] + value[i + k]
       for i in range(len(ly)):
           for k in range(24):
               if self.plots['total']:
                   l24[i][k] = l24[i][k] / 365
               if self.plots['month']:
                   for m in range(12):
                       m24[i][m][k] = m24[i][m][k] / the_days[m]
               if self.plots['season']:
                   for q in range(len(seasons)):
                       q24[i][q][k] = q24[i][q][k] / the_qtrs[q]
               if self.plots['period']:
                   for s in range(len(periods)):
                       s24[i][s][k] = s24[i][s][k] / the_ssns[s]
       if self.plots['hour']:
           if self.plots['save_plot']:
               vals = ['hour']
               data = []
               data.append(x)
           fig = plt.figure('hour')
           plt.grid(True)
           hx = fig.add_subplot(111)
           plt.title(self.hdrs['hour'] + ' - ' + locn)
           maxy = 0
           if self.two_axes:
               hx2 = hx.twinx()
           for key, value in iter(sorted(self.ly.items())):
               lw = 2.0
               if self.two_axes and key in self.ylabel2[0]:
                   hx2.plot(x, value, linewidth=lw, label=key, color=self.colours[key])
               else:
                   hx.plot(x, value, linewidth=lw, label=key, color=self.colours[key])
                   maxy = max(maxy, max(value))
               if self.plots['save_plot']:
                   vals.append(key)
                   data.append(value)
           if self.plots['save_plot']:
               titl = 'hour'
               dialog = displaytable.Table(list(map(list, list(zip(*data)))), title=titl, fields=vals, save_folder=self.scenarios)
               dialog.exec_()
               del dialog, data, vals
           hx.set_ylim([0, maxy])
           plt.xlim([0, len(x)])
           plt.xticks(list(range(12, len(x), 168)))
           hx.set_xticklabels(day_labels, rotation='vertical')
           hx.set_xlabel('Month of the year')
           hx.set_ylabel(self.ylabel[0])
           hx.legend(loc='best')
           if self.two_axes:
               ylim = hx2.get_ylim()
               hx2.set_ylim(0, ylim[1])
               lines = []
               for key in self.ly:
                   lines.append(mlines.Line2D([], [], color=self.colours[key], label=key))
               hx.legend(handles=lines, loc='best')
               hx2.set_ylabel(self.ylabel2[1])
           if self.maximise:
               mng = plt.get_current_fig_manager()
               if sys.platform == 'win32' or sys.platform == 'cygwin':
                   if plt.get_backend() == 'TkAgg':
                       mng.window.state('zoomed')
                   elif plt.get_backend() == 'Qt4Agg':
                       mng.window.showMaximized()
               else:
                   mng.resize(*mng.window.maxsize())
           zp = ZoomPanX()
           if self.two_axes:
               f = zp.zoom_pan(hx2, base_scale=1.2) # enable scrollable zoom
           else:
               f = zp.zoom_pan(hx, base_scale=1.2) # enable scrollable zoom
           if self.plots['block']:
               plt.show(block=True)
           else:
               plt.draw()
           del zp
       if self.plots['total']:
           if self.plots['save_plot']:
               vals = ['hour of the day']
               decpts = [0]
               data = []
               data.append(x24)
           figt = plt.figure('total')
           plt.grid(True)
           tx = figt.add_subplot(111)
           plt.title(self.hdrs['total'] + ' - ' + locn)
           maxy = 0
           i = -1
           lw = 2.0
           if self.two_axes:
               tx2 = tx.twinx()
           for key, value in iter(sorted(self.ly.items())):
               i += 1
               if self.two_axes and key in self.ylabel2[0]:
                   tx2.plot(x24, l24[i], linewidth=lw, label=key, color=self.colours[key])
               else:
                   tx.plot(x24, l24[i], linewidth=lw, label=key, color=self.colours[key])
                   maxy = max(maxy, max(l24[i]))
               if self.plots['save_plot']:
                   vals.append(key)
                   data.append(l24[i])
                   if key == 'wind':
                       decpts.append(2)
                   else:
                       decpts.append(1)
           if self.plots['save_plot']:
               titl = 'total'
               dialog = displaytable.Table(list(map(list, list(zip(*data)))), title=titl, fields=vals, save_folder=self.scenarios, decpts=decpts)
               dialog.exec_()
               del dialog, data, vals
           tx.set_ylim([0, maxy])
           plt.xlim([1, 24])
           plt.xticks(list(range(4, 25, 4)))
           tx.set_xticklabels(labels[1:])
           tx.set_xlabel('Hour of the Day')
           tx.set_ylabel(self.ylabel[0])
           tx.legend(loc='best')
           if self.two_axes:
               ylim = tx2.get_ylim()
               tx2.set_ylim(0, ylim[1])
               lines = []
               for key in self.ly:
                   lines.append(mlines.Line2D([], [], color=self.colours[key], label=key))
               tx.legend(handles=lines, loc='best')
               tx2.set_ylabel(self.ylabel2[1])
           if self.maximise:
               mng = plt.get_current_fig_manager()
               if sys.platform == 'win32' or sys.platform == 'cygwin':
                   if plt.get_backend() == 'TkAgg':
                       mng.window.state('zoomed')
                   elif plt.get_backend() == 'Qt4Agg':
                       mng.window.showMaximized()
               else:
                   mng.resize(*mng.window.maxsize())
           if self.plots['block']:
               plt.show(block=True)
           else:
               plt.draw()
       if self.plots['month']:
           dayPlot(self, 'month', m24, locn, mth_labels, mth_xlabels)
       if self.plots['season']:
           dayPlot(self, 'season', q24, locn, ssn_labels, labels)
       if self.plots['period']:
           dayPlot(self, 'period', s24, locn, smp_labels, labels)
       if 'pdf' in list(self.plots.keys()):
           if self.plots['pdf'] and self.plots['wind']:
               j = int(ceil(max(self.ly['wind'])))
               figp = plt.figure('pdf')
               plt.grid(True)
               px = figp.add_subplot(111)
               plt.title(self.hdrs['pdf'] + ' - ' + locn)
               px.hist(self.ly['wind'], j)
               px.set_ylabel('Number of occurences')
               px.set_xlabel('Wind Speed (m/s)')
           if self.plots['block']:
               plt.show(block=True)
           else:
               plt.draw()
       if self.plots['monthly']:
           if self.plots['save_plot']:
               vals = ['monthly']
               data = []
               data.append(x24[:12])
               decpts = [0]
           figt = plt.figure('monthly')
           plt.grid(True)
           tx = figt.add_subplot(111)
           plt.title(self.hdrs['monthly'] + ' - ' + locn)
           maxy = 0
           i = -1
           if self.two_axes:
               tx2 = tx.twinx()
           for key, value in iter(sorted(self.ly.items())):
               i += 1
               lw = 2.0
               if self.two_axes and key in self.ylabel2[0]:
                   tx2.step(x24[:14], t12[i], linewidth=lw, label=key, color=self.colours[key])
               else:
                   tx.step(x24[:14], t12[i], linewidth=lw, label=key, color=self.colours[key])
                   maxy = max(maxy, max(t12[i]) + 1)
               if self.plots['save_plot']:
                   vals.append(key)
                   data.append(t12[i][1:-1])
                   if key == 'wind':
                       decpts.append(2)
                   else:
                       decpts.append(1)
           if self.plots['save_plot']:
               titl = 'monthly'
               dialog = displaytable.Table(list(map(list, list(zip(*data)))), title=titl, fields=vals, save_folder=self.scenarios, decpts=decpts)
               dialog.exec_()
               del dialog, data, vals
           tx.set_ylim([0, maxy])
           tick_spot = []
           for i in range(12):
               tick_spot.append(i + 1.5)
           tx.set_xticks(tick_spot)
           tx.set_xticklabels(mth_labels)
           plt.xlim([1, 13.0])
           tx.set_xlabel('Month')
           tx.set_ylabel(self.ylabel[0])
           tx.legend(loc='best')
           if self.two_axes:
               ylim = tx2.get_ylim()
               tx2.set_ylim(0, ylim[1])
               lines = []
               for key in self.ly:
                   lines.append(mlines.Line2D([], [], color=self.colours[key], label=key))
               tx.legend(handles=lines, loc='best')
               tx2.set_ylabel(self.ylabel2[1])
           if self.maximise:
               mng = plt.get_current_fig_manager()
               if sys.platform == 'win32' or sys.platform == 'cygwin':
                   if plt.get_backend() == 'TkAgg':
                       mng.window.state('zoomed')
                   elif plt.get_backend() == 'Qt4Agg':
                       mng.window.showMaximized()
               else:
                   mng.resize(*mng.window.maxsize())
           if self.plots['block']:
               plt.show(block=True)
           else:
               plt.draw()
       if self.plots['mthavg']:
           if self.plots['save_plot']:
               vals = ['monthly_average']
               data = []
               data.append(x24[:12])
               decpts = [0]
           figt = plt.figure('monthly_average')
           plt.grid(True)
           tx = figt.add_subplot(111)
           plt.title(self.hdrs['mthavg'] + ' - ' + locn)
           maxy = 0
           if self.two_axes:
               tx2 = tx.twinx()
           m12 = []
           for i in range(len(t12)):
               m12.append([])
               for m in range(1, 13):
                   m12[-1].append(t12[i][m] / the_days[m - 1] / 24.)
           i = -1
           lw = 2.0
           for key, value in iter(sorted(self.ly.items())):
               i += 1
               if self.two_axes and key in self.ylabel2[0]:
                   tx2.plot(x24[:12], m12[i], linewidth=lw, label=key, color=self.colours[key])
               else:
                   tx.plot(x24[:12], m12[i], linewidth=lw, label=key, color=self.colours[key])
                   maxy = max(maxy, max(m12[i]) + 1)
               if self.plots['save_plot']:
                   vals.append(key)
                   data.append(m12[i])
                   if key == 'wind':
                       decpts.append(2)
                   else:
                       decpts.append(1)
           if self.plots['save_plot']:
               titl = 'mthavg'
               dialog = displaytable.Table(list(map(list, list(zip(*data)))), title=titl, fields=vals, save_folder=self.scenarios, decpts=decpts)
               dialog.exec_()
               del dialog, data, vals
           tx.set_ylim([0, maxy])
           plt.xlim([1, 12])
           plt.xticks(list(range(1, 13, 1)))
           tx.set_xticklabels(mth_labels)
           tx.set_xlabel('Month')
           tx.set_ylabel(self.ylabel[0])
           tx.legend(loc='best')
           if self.two_axes:
               ylim = tx2.get_ylim()
               tx2.set_ylim(0, ylim[1])
               lines = []
               for key in self.ly:
                   lines.append(mlines.Line2D([], [], color=self.colours[key], label=key))
               tx.legend(handles=lines, loc='best')
               tx2.set_ylabel(self.ylabel2[1])
           if self.maximise:
               mng = plt.get_current_fig_manager()
               if sys.platform == 'win32' or sys.platform == 'cygwin':
                   if plt.get_backend() == 'TkAgg':
                       mng.window.state('zoomed')
                   elif plt.get_backend() == 'Qt4Agg':
                       mng.window.showMaximized()
               else:
                   mng.resize(*mng.window.maxsize())
           if self.plots['block']:
               plt.show(block=True)
           else:
               plt.draw()
       if not self.plots['block']:
           plt.show()
示例#23
0
    def get_orig_options():
        '''
        Set the default options for Covasim -- not to be called by the user, use
        ``cv.options.set('defaults')`` instead.
        '''

        # Options acts like a class, but is actually an objdict for simplicity
        optdesc = sc.objdict()  # Help for the options
        options = sc.objdict()  # The options

        optdesc.verbose = 'Set default level of verbosity (i.e. logging detail): e.g., 0.1 is an update every 10 simulated days'
        options.verbose = float(os.getenv('COVASIM_VERBOSE', 0.1))

        optdesc.style = 'Set the default plotting style -- options are "covasim" and "simple" plus those in pl.style.available; see also options.rc'
        options.style = os.getenv('COVASIM_STYLE', 'covasim')

        optdesc.dpi = 'Set the default DPI -- the larger this is, the larger the figures will be'
        options.dpi = int(os.getenv('COVASIM_DPI', pl.rcParams['figure.dpi']))

        optdesc.font = 'Set the default font family (e.g., sans-serif or Arial)'
        options.font = os.getenv('COVASIM_FONT', pl.rcParams['font.family'])

        optdesc.fontsize = 'Set the default font size'
        options.fontsize = int(
            os.getenv('COVASIM_FONT_SIZE', pl.rcParams['font.size']))

        optdesc.interactive = 'Convenience method to set figure backend, showing, and closing behavior'
        options.interactive = os.getenv('COVASIM_INTERACTIVE', True)

        optdesc.jupyter = 'Convenience method to set common settings for Jupyter notebooks: set to "retina" or "widget" (default) to set backend'
        options.jupyter = os.getenv('COVASIM_JUPYTER', False)

        optdesc.show = 'Set whether or not to show figures (i.e. call pl.show() automatically)'
        options.show = int(os.getenv('COVASIM_SHOW', True))

        optdesc.close = 'Set whether or not to close figures (i.e. call pl.close() automatically)'
        options.close = int(os.getenv('COVASIM_CLOSE', False))

        optdesc.returnfig = 'Set whether or not to return figures from plotting functions'
        options.returnfig = int(os.getenv('COVASIM_RETURNFIG', True))

        optdesc.backend = 'Set the Matplotlib backend (use "agg" for non-interactive)'
        options.backend = os.getenv('COVASIM_BACKEND', pl.get_backend())

        optdesc.rc = 'Matplotlib rc (run control) style parameters used during plotting -- usually set automatically by "style" option'
        options.rc = sc.dcp(rc_covasim)

        optdesc.warnings = 'How warnings are handled: options are "warn" (default), "print", and "error"'
        options.warnings = str(os.getenv('COVASIM_WARNINGS', 'warn'))

        optdesc.sep = 'Set thousands seperator for text output'
        options.sep = str(os.getenv('COVASIM_SEP', ','))

        optdesc.precision = 'Set arithmetic precision for Numba -- 32-bit by default for efficiency'
        options.precision = int(os.getenv('COVASIM_PRECISION', 32))

        optdesc.numba_parallel = 'Set Numba multithreading -- none, safe, full; full multithreading is ~20% faster, but results become nondeterministic'
        options.numba_parallel = str(
            os.getenv('COVASIM_NUMBA_PARALLEL', 'none'))

        optdesc.numba_cache = 'Set Numba caching -- saves on compilation time; disabling is not recommended'
        options.numba_cache = bool(int(os.getenv('COVASIM_NUMBA_CACHE', 1)))

        return optdesc, options
    def _plotValues(self,
                    values,            #dict  TimeSeries values
                    plot_label,        #str   Plot-Label
                    fig_num,           #int   Figure-number for classify plots
                                       #      1: average,
                                       #      2: single trial,
                                       #      3: average accumulating
                    store_dir = None,  #str   Directory to store the plots
                    counter=0):        #int   Plotcounter for all trials
        #compute sampling_frequency and classes to plot
        sampling_frequency = values[values.keys()[0]].sampling_frequency
        list_of_classes = values.keys()
        num_of_classes = len(list_of_classes)
        #autoscale color bar or use user scaling
        if self.limits:
            levels = self._compute_levels()
        else:
            levels = None
            #compute maximum and minimum for colorbar scaling if not existing
            vmax = float(max(numpy.array(v).max() for v in values.itervalues()))
            vmin = float(min(numpy.array(v).min() for v in values.itervalues()))
            levels = self._compute_levels(limits=[vmin, vmax])
            #normalizer=matplotlib.colors.Normalize(vmin=vmin, vmax=vmax)
        
        #computing time points to show
        num_tpoints = values.values()[0].shape[0]
        all_tpoints = numpy.arange(0,
                                   num_tpoints * (1000/sampling_frequency),
                                   1000 / sampling_frequency
                                   ) + self.timeshift
        
        if self.time_stamps == [-1]:
            tpoints = all_tpoints
        else: #check if desired time points are existing and confirm
            if not self.time_checked:
                for t in self.time_stamps:
                    if not t in all_tpoints:
                        warnings.warn("Electrode_Coordination_Plot:: At least" \
                                      " one desired time stamp not available!" \
                                      " Legal time stamps are " \
                                      + str(all_tpoints) + ". Switching to " \
                                      "next legal time point. Please check " \
                                      "for consistency!")
                        
                        if t < 0:
                            new_t = self.timeshift
                        else:
                            new_t = range(0, t+1, int(1000/sampling_frequency))[-1]
                        
                            #if we obtain an empty list reset to timeshift
                            if new_t == []:
                                new_t = self.timeshift
                            else:
                                new_t = new_t+self.timeshift
                        
                        #finally check for too high or low values
                        if new_t < self.timeshift:
                            new_t = self.timeshift
                        elif new_t > all_tpoints[-1]:
                            new_t = all_tpoints[-1]
                
                        self.time_stamps[self.time_stamps.index(t)] = new_t
                self.time_checked = True #has to be performed only once
                
            tpoints = numpy.array(self.time_stamps)
        
        num_of_tpoints = len(tpoints)
        
        # selecting formatting and clearing figure
        default_size = [8., 6.]
        if self.single_plot:
            num_of_rows = num_of_tpoints
            if num_of_rows > 4:
                default_size[0] = default_size[0]/(int((num_of_rows+3)/4))
                default_size[1] = default_size[1]/(int((num_of_rows+3)/4))
        else:
            num_of_rows = 1

        f=pylab.figure(fig_num, figsize=[default_size[0]*num_of_classes, default_size[1]*num_of_rows])
        if pylab.get_backend() in pylab.matplotlib.backends.interactive_bk:
            f.show()

        if counter%20 == 19: #clear every 20th trial
            pylab.figure(fig_num).clear()
        
        # Iterate  over the time window
        for time_index in range(num_of_tpoints):
            
            pylab.subplots_adjust(left=0.025, right=0.8) #shift a bit to the left
            
            if self.single_plot:
                pl_offset=time_index
            else:
                pl_offset=0

            for index, class_label in enumerate(list_of_classes):
                current_plot_num=(num_of_classes*pl_offset)+index+1
                pylab.subplot(num_of_rows, num_of_classes, current_plot_num)
                pylab.gca().clear()
        
                # Get the values for the respective class
                data = values[class_label].view(numpy.ndarray)

                ec = self.getMetadata("electrode_coordinates")
                if ec is None:
                    ec = StreamDataset.ec
                    
                # observe channels
                channel_names = [channel for channel in values[class_label].channel_names if channel in ec.keys()]
                fcn = [channel for channel in values[class_label].channel_names if not channel in ec.keys()]
                if not fcn == []:
                    self._log("Unsupported channels ignored:%s ."%str(fcn),
                                level=logging.CRITICAL)
                if channel_names == []:
                    self._log("No channel for plotting left.",
                              level=logging.CRITICAL)
                    return

                ec_2d = StreamDataset.project2d(ec)
                
                # Define x and y coordinates of electrodes in the order of the channels
                # of data
                x = numpy.array([ec_2d[key][0] for key in channel_names])
                y = numpy.array([ec_2d[key][1] for key in channel_names])
            
#                x = numpy.array([self.electrode_coordinates[key][0] * numpy.cos(self.electrode_coordinates[key][1]/180*numpy.pi)
#                                        for key in channel_names])
#                y = numpy.array([self.electrode_coordinates[key][0] * numpy.sin(self.electrode_coordinates[key][1]/180*numpy.pi) 
#                                        for key in channel_names])
                
                # The values of the electrodes at this point of time 
                pos=list(all_tpoints).index(tpoints[time_index])
                
                z = data[pos, :]
        
                if self.smooth_corners:
                    x,y,z = self._smooth_corners(x,y,z, data, pos)
                
                #griddata returns a masked array
                #you can get the data via zi[~zi.mask]            
                zi = griddata(x, y, z, self.xi, self.yi)
                
                #clip values
                if self.clip and self.limits:
                    zi=numpy.clip(zi, self.limits[0], self.limits[1]) #minimum and maximum
                    
                # contour the gridded data,
                # plotting dots at the nonuniform data points.
                
                cs=pylab.contourf(self.xi, self.yi, zi, 15, cmap=pylab.cm.jet, levels=levels)
                if self.contourlines:
                    pylab.contour(self.xi, self.yi, zi, 15, linewidths=0.5, colors='k', levels=levels)
                
                if self.figlabels:
                    # plot data points.
                    if not self.smooth_corners:
                        pylab.scatter(x, y, c='b', s=5, marker='o')
                    else:
                        # dont plot invented electrode positions
                        pylab.scatter(x[:-4], y[:-4], c='b', s=5, marker='o')
                    # Add channel labels
                    for label, position in ec_2d.iteritems():
                        if label in channel_names:
                            pylab.text(position[0], position[1], label)
                        
                if self.add_info:
                    if counter:
                        if len(list_of_classes) > 1:
                            if index == 0:
                                pylab.text(-120, -98, 'Trial No. ' + str(counter), fontsize=12)
                        else:
                            pylab.text(-120, -98, 'Trial No. ' + str(counter), fontsize=12)
                
                if self.nose_ears:
                    #nose
                    ytips=[87.00,87.00, 97]
                    xtips=[-10.00,10.00, 0]
                    pylab.fill(xtips,ytips, facecolor='k', edgecolor='none')
                    
                    #left
                    xtips=[-108.0,-113.0,-113.0,-108.0]
                    ytips=[-10.0,-10.0,10.0,10.0]
                    pylab.fill(xtips,ytips, facecolor='k', edgecolor='none')

                    #right
                    xtips=[108.0,114.0,113.0,108.0]
                    ytips=[-10.0,-10.0,10.0,10.0]
                    pylab.fill(xtips,ytips, facecolor='k', edgecolor='none')
                
                pylab.xlim(-125, 125)
                pylab.ylim(-100, 100)
                if not self.single_plot or time_index==0: #if single_plot=True do only for the first row
                    pylab.title(class_label, fontsize=20)
                pylab.setp(pylab.gca(), xticks=[], yticks=[])
                pylab.draw()
            
            caxis = pylab.axes([.85, .1, .04, .75])
            cb = pylab.colorbar(mappable=cs, cax=caxis)
            # TODO: The label read 'Amplitude ($\mu$V)'
            #       Removed the unit. Or can we really still assume 
            #       a (correct) \muV scale after all preprocessing?
            cb.ax.set_ylabel(r'Amplitude', fontsize=16)
    
            # Position of the time axes
            ax = pylab.axes([.79, .94, .18, .04])
            pylab.gca().clear()
            
            pylab.bar(tpoints[time_index], 1.0,  width=1000.0/sampling_frequency)
            pylab.xlim(tpoints[0], tpoints[-1])
            pylab.xlabel("time (ms)", fontsize=12)
            pylab.setp(ax, yticks=[],xticks=[all_tpoints[0], tpoints[time_index], all_tpoints[-1]])
            
            # Draw or store the figure
            if store_dir is None:
                pylab.draw()
                #pylab.show()
            elif self.single_plot and not current_plot_num==(num_of_rows*num_of_classes): #save only if everything is plotted
                pylab.draw()
                #pylab.show()
            else:
                current_split=self.current_split
                if current_split != 0 and not\
                plot_label.endswith('_split_' + str(current_split)): #more than one split and first call
                    plot_label = plot_label + '_split_' + str(current_split)
                    
                f_name=str(store_dir) + str(os.sep) + str(plot_label) + "_" + str(int(tpoints[time_index]))
                pylab.savefig(f_name + ".png")
            
        if self.store_data:
            import pickle
            f_name=str(store_dir) + str(os.sep) + str(plot_label)
            pickle.dump(values, open(f_name + ".pickle",'w'))
示例#25
0
- frame_compare     Display frames from two sequences and their difference.
"""

# Copyright (c) 2009-2015, Lev Givon
# All rights reserved.
# Distributed under the terms of the BSD license:
# http://www.opensource.org/licenses/bsd-license

__all__ = ['animate', 'animate2', 'animate_compare', 'frame_compare']

import time
import numpy as np
import pylab as p

# Fix for animation problems with Qt4Agg backend:
if p.get_backend() == 'Qt4Agg':
    from PyQt4.QtGui import QApplication
    animate_fix = QApplication.processEvents
else:
    def animate_fix():
        pass

def animate(data, step=1, delay=0):
    """
    Animate sequence of frames.

    Animate a sequence of `Ny x Nx` bitmap frames stored in a `M x Ny x Nx` data
    array.

    Parameters
    ----------