コード例 #1
0
class Plot():
    """This class is used to generate the figures for the plots."""
    def __init__(self):
        """ Description of init """

        # Create the option parser for the command line options
        usage = (
            'usage: %prog [options]\n\n'
            'All options are strings. Boolean options are true when they \n'
            'contains a certain specific keywords, which is written in \n'
            'the option description in parantheses.')
        parser = OptionParser(usage=usage)

        # Add the options to the option parser
        parser.add_option('-a',
                          '--type',
                          help='Type string from '
                          'graphsettings.xml')
        parser.add_option('-b', '--idlist', help='List of id\'s to plot')
        parser.add_option('-c',
                          '--from_d',
                          help='From timestamp, format: '
                          'YYYY-MM-DD HH:MM')
        parser.add_option('-d',
                          '--to_d',
                          help='To timestamp, format: '
                          'YYYY-MM-DD HH:MM')
        parser.add_option('-e', '--xmin', help='X-min for zoom')
        parser.add_option('-f', '--xmax', help='X-max for zoom')
        parser.add_option('-g', '--ymin', help='Y-min for zoom')
        parser.add_option('-i', '--ymax', help='Y-max for zoom')
        parser.add_option('-j',
                          '--offset',
                          help='List of offsets for the '
                          'graphs (for plots that goes on a log scale and has '
                          'negative values)')
        parser.add_option(
            '-k',
            '--as_function_of_t',
            help='Plot the graphs as '
            'a function of temperature (boolean \'checked\'=True)')
        parser.add_option('-l',
                          '--logscale',
                          help='Use a log for the right '
                          'axis (boolean \'checked\'=True)')
        parser.add_option('-m',
                          '--shift_temp_unit',
                          help='Change between K '
                          'and C when values are plotted as a function of '
                          'temperature (boolean \'checked\'=True)')
        parser.add_option('-n',
                          '--flip_x',
                          help='Exchange min and max for the '
                          'x-axis (boolean \'checked\'=True)')
        parser.add_option('-o',
                          '--shift_be_ke',
                          help='Shift between binding '
                          'energy and kinetic energy for XPS plots (boolean '
                          '\'checked\'=True)')
        # -p is availabel from previous options
        parser.add_option(
            '-q',
            '--image_format',
            help='Image format for the '
            'figure exports, given as the figure extension. Can '
            'be svg, eps, ps, pdf and default. Default means use '
            'the one in graphsettings.xml or internal deaault.')
        parser.add_option('-r',
                          '--small_plot',
                          help='Produce a small plot '
                          '(boolean \'checked\'=1)')

        # Parse the options
        (options, args) = parser.parse_args()

        ### Process options - all options are given as string, and they need to
        ### be converted into other data types
        # Convert idlist
        self.idlist = [
            int(element) for element in options.idlist.split(',')[1:]
        ]
        # Turn the offset 'key:value,' pair string into a dictionary
        self.offsets = dict([[int(offset.split(':')[0]),
                              offset.split(':')[1]]
                             for offset in options.offset.split(',')[1:]])
        # Gather from and to in a fictionary
        self.from_to = {'from': options.from_d, 'to': options.to_d}
        # Turn several options into booleans
        self.as_function_of_t = True if options.as_function_of_t ==\
            'checked' else False
        self.shift_temp_unit = True if options.shift_temp_unit ==\
            'checked' else False
        self.logscale = True if options.logscale == 'checked' else False
        self.flip_x = True if options.flip_x == 'checked' else False
        self.shift_be_ke = True if options.shift_be_ke == 'checked' else False
        self.small_plot = True if options.small_plot == '1' else False

        ### Create database backend object
        self.db = dataBaseBackend(typed=options.type,
                                  from_to=self.from_to,
                                  id_list=self.idlist,
                                  offsets=self.offsets,
                                  as_function_of_t=self.as_function_of_t,
                                  shift_temp_unit=self.shift_temp_unit,
                                  shift_be_ke=self.shift_be_ke)

        ### Ask self.db for a measurement count
        measurement_count = self.db.get_data_count()

        # Set the image format to standard, overwite with gs value and again
        # options value if i exits
        if options.image_format:
            if options.image_format == 'default':
                if self.db.global_settings.has_key('image_format'):
                    self.image_format = self.db.global_settings['image_format']
                else:
                    self.image_format = 'png'
            else:
                self.image_format = options.image_format
        else:
            self.image_format = 'png'

        # Create a hash from the measurement_count, options and
        #self.db.global_settings
        hash = hashlib.md5()
        hash.update(
            str(options) + str(self.db.global_settings) +
            str(measurement_count))
        # self.namehash is unique for this plot and will form the filename
        self.namehash = ('/var/www/cinfdata/figures/' + hash.hexdigest() +
                         '.' + self.image_format)

        # For use in other methods
        self.options = options

        # object to give first good color, and then random colors
        self.c = Color()

        self.left_color = 'black'
        self.right_color = 'black'

    def main(self):
        if os.path.exists(self.namehash) and False:
            print self.namehash
        else:
            # Call a bunch of functions
            self._init_plot()
            self._plot()
            if self.left_color != 'black':
                if self.right_color != 'black':
                    self.c.color_axis(self.ax1, self.ax2, self.left_color,
                                      self.right_color)
                else:
                    self.c.color_axis(self.ax1, None, self.left_color, None)
            self._legend()
            self._zoom_and_flip()
            self._transform_and_label_axis()
            if not self.small_plot:
                self._title()
            self._grids()
            self._save()

    def _init_plot(self):
        ### Apply settings
        # Small plots
        if self.small_plot:
            # Apply default settings
            plt.rcParams.update({
                'figure.figsize': [4.5, 3.0],
                'ytick.labelsize': 'x-small',
                'xtick.labelsize': 'x-small',
                'legend.fontsize': 'x-small'
            })
            # Overwrite with values from graphsettings
            plt.rcParams.update(self.db.global_settings['rcparams_small'])
        else:
            plt.rcParams.update({
                'figure.figsize': [9.0, 6.0],
                'axes.titlesize': '24',
                'legend.fontsize': 'small'
            })
            plt.rcParams.update(self.db.global_settings['rcparams_regular'])

        self.fig = plt.figure(1)

        self.ax1 = self.fig.add_subplot(111)
        self.ax2 = None

        # Decide on the y axis type
        self.gs = self.db.global_settings
        if self.logscale:
            self.ax1.set_yscale('log')
        elif self.gs['default_yscale'] == 'log':
            self.ax1.set_yscale('log')

    def _plot(self):
        # Make plot
        data_in_plot = False
        for data in self.db.get_data():
            if len(data['data']) > 0:
                data_in_plot = data_in_plot or True
                # Speciel case for barplots
                if self.db.global_settings.has_key('default_style') and\
                        self.db.global_settings['default_style'] == 'barplot':
                    self.ax1.bar(data['data'][:, 0],
                                 data['data'][:, 1],
                                 color=self.c.get_color())
                # Normal graph styles
                else:
                    # If the graph go on the right side of the plot
                    if data['info']['on_the_right']:
                        # Initialise secondary plot if it isn't already
                        if not self.ax2:
                            self._init_second_y_axis()
                        # If info has a color (i.e. it is given in gs ordering)
                        if data['info'].has_key('color'):
                            # Set the color for the graph and axis
                            color = data['info']['color']
                            self.right_color = data['info']['color']
                        else:
                            # Else get a new color from self.c
                            color = self.c.get_color()

                        # Make the actual plot
                        self.ax2.plot(data['data'][:, 0],
                                      data['data'][:, 1],
                                      color=color,
                                      label=self._legend_item(data) + '(R)')
                    # If the graph does not go on the right side of the plot
                    else:
                        # If info has a color (i.e. it is given in gs ordering)
                        if data['info'].has_key('color'):
                            # Set the color for the graph and axis
                            color = data['info']['color']
                            self.left_color = data['info']['color']
                        else:
                            # Else get a new color from self.c
                            color = self.c.get_color()

                        # Make the actual plot
                        self.ax1.plot(data['data'][:, 0],
                                      data['data'][:, 1],
                                      color=color,
                                      label=self._legend_item(data))

        # If no data has been been put on the graph at all, explain why there
        # is none
        if not data_in_plot:
            y = 0.00032 if self.logscale or self.gs[
                'default_yscale'] == 'log' else 0.5
            self.ax1.text(0.5,
                          y,
                          'No data',
                          horizontalalignment='center',
                          verticalalignment='center',
                          color='red',
                          size=60)

    def _legend(self):
        if self.db.global_settings['default_xscale'] != 'dat':
            ax1_legends = self.ax1.get_legend_handles_labels()
            if self.ax2:
                ax2_legends = self.ax2.get_legend_handles_labels()
                for color, text in zip(ax2_legends[0], ax2_legends[1]):
                    ax1_legends[0].append(color)
                    ax1_legends[1].append(text)

            # loc for locations, 0 means 'best'. Why that isn't deafult I
            # have no idea
            self.ax1.legend(ax1_legends[0], ax1_legends[1], loc=0)

    def _zoom_and_flip(self):
        # Now we are done with the plotting, change axis if necessary
        # Get current axis limits
        self.axis = self.ax1.axis()
        if self.options.xmin != self.options.xmax:
            self.axis = (float(self.options.xmin), float(self.options.xmax)) +\
                self.axis[2:4]
        if self.options.ymin != self.options.ymax:
            self.axis = self.axis[0:2] + (float(
                self.options.ymin), float(self.options.ymax))
        if self.flip_x:
            self.axis = (self.axis[1], self.axis[0]) + self.axis[2:4]
        self.ax1.axis(self.axis)

    def _transform_and_label_axis(self):
        """ Transform X-AXIS axis and label it """

        # If it is a date plot
        if self.db.global_settings['default_xscale'] == 'dat':
            # Turn the x-axis into timemarks
            # IMPLEMENT add something to TimeMarks initialisation to take care
            # or morning_pressure
            markformat = '%H:%M' if self.small_plot else '%b-%d %H:%M'
            timemarks = TimeMarks(self.axis[0],
                                  self.axis[1],
                                  markformat=markformat)
            (old_tick_labels, new_tick_labels) = timemarks.get_time_marks()
            self.ax1.set_xticks(old_tick_labels)
            self.bbox_xlabels = self.ax1.\
                set_xticklabels(new_tick_labels, rotation=25,
                                horizontalalignment='right')
            # Make a little extra room for the rotated x marks
            #self.fig.subplots_adjust(bottom=0.12)
        elif self.options.type == 'masstime':
            gs_temp_unit = self.gs['temperature_unit']
            other_temp_unit = 'C' if gs_temp_unit == 'K' else 'K'
            cur_temp_unit = other_temp_unit if self.shift_temp_unit else\
                gs_temp_unit
            if self.as_function_of_t and not self.small_plot:
                self.ax1.set_xlabel(self.gs['t_xlabel'] + cur_temp_unit)
            elif not self.small_plot:
                self.ax1.set_xlabel(self.gs['xlabel'])
        elif self.options.type == 'xps':
            if self.shift_be_ke and not self.small_plot:
                self.ax1.set_xlabel(self.gs['alt_xlabel'])
            elif not self.small_plot:
                self.ax1.set_xlabel(self.gs['xlabel'])
        elif not self.small_plot:
            self.ax1.set_xlabel(self.gs['xlabel'])

        # Label Y-axis
        if not self.small_plot:
            self.ax1.set_ylabel(self.gs['ylabel'], color=self.left_color)
            if self.ax2:
                self.ax2.set_ylabel(self.gs['right_ylabel'],
                                    color=self.right_color)

    def _title(self):
        """ TITLE """
        # Set the title and raise it a bit
        if self.as_function_of_t:
            self.bbox_title = self.ax1.set_title(self.gs['t_title'], y=1.03)
        else:
            self.bbox_title = self.ax1.set_title(self.gs['title'], y=1.03)

    def _grids(self):
        # GRIDS
        self.ax1.grid(b=True, which='major')
        #plt.xscale('linear')
        #plt.xticks(range(0,100,10))
        #plt.x_minor_ticks(range(0,100,10))
        #plt.grid(b='on', which='minor')
        #plt.grid(b='on', which='major')

    def _save(self):
        ## Filesave
        # Save
        self.fig.savefig(self.namehash, bbox_inches='tight', pad_inches=0.03)

        # This is the magical line that plot.php opens
        # For the script to work this has to be the only print statement
        print self.namehash

    ### Here start the small helper functions that are called from the main flow

    def _init_second_y_axis(self):
        self.ax2 = self.ax1.twinx()
        if self.db.global_settings['right_yscale'] == 'log':
            self.ax2.set_yscale('log')

    def _legend_item(self, data):
        if self.db.global_settings['default_xscale'] == 'dat':
            return ''
        elif data['gs'].has_key('legend_field_name') and\
                data['info'][data['gs']['legend_field_name']]:
            return data['info']['mass_label'] + '-' + str(data['info']['id'])
        else:
            return str(data['info']['id'])
コード例 #2
0
class Plot():
    """This class is used to generate the figures for the plots."""
    
    def __init__(self, options, ggs):
        """ Description of init """
        
        self.o = options
        self.ggs = ggs
        
        # Set the image format to standard, overwite with ggs value and again
        # options value if it exits
        if self.o['image_format'] == '':
            self.image_format = self.ggs['image_format']
        else:
            self.image_format = self.o['image_format']

        # Default values for matplotlib plots (names correspond to ggs names)
        mpl_settings = {'width': 900,
                        'height': 600,
                        'title_size': '24',
                        'xtick_labelsize': '12',
                        'ytick_labelsize': '12',
                        'legend_fontsize': '10',
                        'label_fontsize': '16',
                        'linewidth': 1.0,
                        'grid': False}
        
        # Owerwrite defaults with gs values and convert to appropriate types
        for key, value in mpl_settings.items():
            try:
                mpl_settings[key] = type(value)(self.ggs['matplotlib_settings'][key])
            except KeyError:
                pass
        
        # Write some settings to pyplot
        rc_temp = {'figure.figsize': [float(mpl_settings['width'])/100,
                                      float(mpl_settings['height'])/100],
                   'axes.titlesize': mpl_settings['title_size'],
                   'xtick.labelsize': mpl_settings['xtick_labelsize'],
                   'ytick.labelsize': mpl_settings['ytick_labelsize'],
                   'legend.fontsize': mpl_settings['legend_fontsize'],
                   'axes.labelsize': mpl_settings['label_fontsize'],
                   'lines.linewidth': mpl_settings['linewidth'],
                   'axes.grid': mpl_settings['grid']
                   }
        plt.rcParams.update(rc_temp)
                                                        
        # Plotting options
        self.maxticks=15
        self.tz = GMT1()
        self.right_yaxis = len(self.o['right_plotlist']) > 0
        self.measurement_count = None
 
        # object to give first good color, and then random colors
        self.c = Color()

    def new_plot(self, data, plot_info, measurement_count):
        """ Form a new plot with the given data and info """
        self.measurement_count = sum(measurement_count)
        self._init_plot()
        self._plot(data)
        self._zoom_and_flip()
        self._title_and_labels(plot_info)
        self._save(plot_info)

    def _init_plot(self):
        """ Initialize plot """
        self.fig = plt.figure(1)

        self.ax1 = self.fig.add_subplot(111)
        if self.right_yaxis:
            self.ax2 = self.ax1.twinx()

        if self.o['left_logscale']:
            self.ax1.set_yscale('log')
        if self.right_yaxis and self.o['right_logscale']:
            self.ax2.set_yscale('log')

    def _plot(self, data):
        """ Determine the type of the plot and make the appropriate plot by use
        of the functions:
          _plot_dateplot
          _plot_xyplot
        """
        if self.ggs['default_xscale'] == 'dat':
            self._plot_dateplot(data)
        else:
            self._plot_xyplot(data)

    def _plot_dateplot(self, data):
        """ Make the date plot """
        # Rotate datemarks on xaxis
        self.ax1.set_xticklabels([], rotation=25, horizontalalignment='right')
        # Left axis
        for dat in data['left']:
            # Form legend
            if dat['lgs'].has_key('legend'):
                legend = dat['lgs']['legend']
            else:
                legend = None
            # Plot
            if len(dat['data']) > 0:
                self.ax1.plot_date(mdates.epoch2num(dat['data'][:,0]),
                                   dat['data'][:,1],
                                   label=legend,
                                   xdate=True,
                                   color=self.c.get_color(),
                                   tz=self.tz,
                                   fmt='-')
        # Right axis
        for dat in data['right']:
            # Form legend
            if dat['lgs'].has_key('legend'):
                legend = dat['lgs']['legend']
            else:
                legend = None
            # Plot
            if len(dat['data']) > 0:
                self.ax2.plot_date(mdates.epoch2num(dat['data'][:,0]),
                                   dat['data'][:,1],
                                   label=legend,
                                   xdate=True,
                                   color=self.c.get_color(),
                                   tz=self.tz,
                                   fmt='-')
        # No data
        if self.measurement_count == 0:
            y = 0.00032 if self.o['left_logscale'] is True else 0.5
            self.ax1.text(0.5, y, 'No data', horizontalalignment='center',
                          verticalalignment='center', color='red', size=60)

    def _plot_xyplot(self, data):
        # Left axis
        for dat in data['left']:
            # Form legend
            if dat['lgs'].has_key('legend'):
                legend = dat['lgs']['legend']
            else:
                legend = None
            # Plot
            if len(dat['data']) > 0:
                self.ax1.plot(dat['data'][:,0],
                              dat['data'][:,1],
                              '-',
                              label=legend,
                              color=self.c.get_color(),
                              )
        # Right axis
        for dat in data['right']:
            # Form legend
            if dat['lgs'].has_key('legend'):
                legend = dat['lgs']['legend']
            else:
                legend = None
            # Plot
            if len(dat['data']) > 0:
                self.ax2.plot(dat['data'][:,0],
                              dat['data'][:,1],
                              '-',
                              label=legend,
                              color=self.c.get_color()
                              )
        # No data
        if self.measurement_count == 0:
            y = 0.00032 if self.o['left_logscale'] is True else 0.5
            self.ax1.text(0.5, y, 'No data', horizontalalignment='center',
                          verticalalignment='center', color='red', size=60)

    def _zoom_and_flip(self):
        """ Apply the y zooms.
        NOTE: self.ax1.axis() return a list of bounds [xmin,xmax,ymin,ymax] and
        we reuse x and replace y)
        """
        # Left axis 
        if self.o['left_yscale_bounding'] is not None:
            self.ax1.axis(self.ax1.axis()[0:2] + self.o['left_yscale_bounding'])
        # Right axis
        if self.right_yaxis and self.o['right_yscale_bounding'] is not None:
            self.ax2.axis(self.ax2.axis()[0:2] + self.o['right_yscale_bounding'])

        if self.o['flip_x']:
            self.ax1.axis((self.ax1.axis()[1], self.ax1.axis()[0]) + self.ax1.axis()[2:4])

    def _title_and_labels(self, plot_info):
        """ Put title and labels on the plot """
        # xlabel
        if plot_info.has_key('xlabel'):
            label = plot_info['xlabel']
            if plot_info['xlabel_addition'] != '':
                label += '\n' + plot_info['xlabel_addition']
            self.ax1.set_xlabel(label)
        if self.o['xlabel'] != '':  # Manual override
            self.ax1.set_xlabel(r'{0}'.format(self.o['xlabel']))
        # Left ylabel
        if plot_info.has_key('left_ylabel'):
            label = plot_info['left_ylabel']
            if plot_info['y_left_label_addition'] != '':
                label += '\n' + plot_info['y_left_label_addition']
            self.ax1.set_ylabel(label, multialignment='center')
        if self.o['left_ylabel'] != '':  # Manual override
            self.ax1.set_ylabel(self.o['left_ylabel'], multialignment='center')
        # Right ylabel
        if self.right_yaxis and plot_info.has_key('right_ylabel'):
            label = plot_info['right_ylabel']
            if plot_info['y_right_label_addition'] != '':
                label += '\n' + plot_info['y_right_label_addition']
            self.ax2.set_ylabel(label, multialignment='center', rotation=270)
            if self.o['right_ylabel'] != '':  # Manual override
                self.ax2.set_ylabel(self.o['right_ylabel'],
                                    multialignment='center', rotation=270)
        # Title
        if plot_info.has_key('title'):
            self.ax1.set_title(plot_info['title'], y=1.03)
        if self.o['title'] != '':
            # experiment with 'r{0}'.form .. at some time
            self.ax1.set_title('{0}'.format(self.o['title']), y=1.03)
        # Legends
        if self.measurement_count > 0:
            ax1_legends = self.ax1.get_legend_handles_labels()
            if self.right_yaxis:
                ax2_legends = self.ax2.get_legend_handles_labels()
                for color, text in zip(ax2_legends[0], ax2_legends[1]):
                    ax1_legends[0].append(color)
                    ax1_legends[1].append(text)
                    
            # loc for locations, 0 means 'best'. Why that isn't deafult I
            # have no idea
            self.ax1.legend(ax1_legends[0], ax1_legends[1], loc=0)

    def _save(self, plot_info):
        """ Save the figure """
        # The tight method only works if there is a title (it caps of parts of
        # the axis numbers, therefore this hack, this may also become a problem
        # for the other edges of the figure if there are no labels)
        tight = ''
        if plot_info.has_key('title'):
            tight = 'tight'
        # For some wierd reason we cannot write directly to sys.stdout when it
        # is a pdf file, so therefore we use a the StringIO object workaround
        if self.o['image_format'] == 'pdf':
            import StringIO
            out = StringIO.StringIO()
            self.fig.savefig(out, bbox_inches=tight, pad_inches=0.03,
                             format=self.o['image_format'])
            sys.stdout.write(out.getvalue())
        else:
            self.fig.savefig(sys.stdout, bbox_inches=tight, pad_inches=0.03,
                             format=self.o['image_format'])
コード例 #3
0
ファイル: plot.py プロジェクト: CINF/cinfdata_before_rewrite
class Plot():
    """This class is used to generate the figures for the plots."""
    
    def __init__(self):
        """ Description of init """

        # Create the option parser for the command line options
        usage = ('usage: %prog [options]\n\n'
                 'All options are strings. Boolean options are true when they \n'
                 'contains a certain specific keywords, which is written in \n'
                 'the option description in parantheses.')
        parser = OptionParser(usage=usage)

        # Add the options to the option parser
        parser.add_option('-a', '--type', help='Type string from '
                          'graphsettings.xml')
        parser.add_option('-b', '--idlist', help='List of id\'s to plot')
        parser.add_option('-c', '--from_d', help='From timestamp, format: '
                          'YYYY-MM-DD HH:MM')
        parser.add_option('-d', '--to_d', help='To timestamp, format: '
                          'YYYY-MM-DD HH:MM')
        parser.add_option('-e', '--xmin', help='X-min for zoom')
        parser.add_option('-f', '--xmax', help='X-max for zoom')
        parser.add_option('-g', '--ymin', help='Y-min for zoom')
        parser.add_option('-i', '--ymax', help='Y-max for zoom')
        parser.add_option('-j', '--offset', help='List of offsets for the '
                          'graphs (for plots that goes on a log scale and has '
                          'negative values)')
        parser.add_option('-k', '--as_function_of_t', help='Plot the graphs as '
                          'a function of temperature (boolean \'checked\'=True)')
        parser.add_option('-l', '--logscale', help='Use a log for the right '
                          'axis (boolean \'checked\'=True)')
        parser.add_option('-m', '--shift_temp_unit', help='Change between K '
                          'and C when values are plotted as a function of '
                          'temperature (boolean \'checked\'=True)')
        parser.add_option('-n', '--flip_x', help='Exchange min and max for the '
                          'x-axis (boolean \'checked\'=True)')
        parser.add_option('-o', '--shift_be_ke', help='Shift between binding '
                          'energy and kinetic energy for XPS plots (boolean '
                          '\'checked\'=True)')
        # -p is availabel from previous options
        parser.add_option('-q', '--image_format', help='Image format for the '
                          'figure exports, given as the figure extension. Can '
                          'be svg, eps, ps, pdf and default. Default means use '
                          'the one in graphsettings.xml or internal deaault.')
        parser.add_option('-r', '--small_plot', help='Produce a small plot '
                          '(boolean \'checked\'=1)')

        # Parse the options
        (options, args) = parser.parse_args()

        ### Process options - all options are given as string, and they need to
        ### be converted into other data types
        # Convert idlist
        self.idlist = [int(element) for element in options.idlist.split(',')[1:]]
        # Turn the offset 'key:value,' pair string into a dictionary
        self.offsets =  dict([[int(offset.split(':')[0]), offset.split(':')[1]]
                              for offset in options.offset.split(',')[1:]])
        # Gather from and to in a fictionary
        self.from_to = {'from':options.from_d, 'to':options.to_d}
        # Turn several options into booleans
        self.as_function_of_t = True if options.as_function_of_t ==\
            'checked' else False
        self.shift_temp_unit = True if options.shift_temp_unit ==\
            'checked' else False
        self.logscale = True if options.logscale == 'checked' else False
        self.flip_x = True if options.flip_x == 'checked' else False
        self.shift_be_ke = True if options.shift_be_ke == 'checked' else False
        self.small_plot = True if options.small_plot == '1' else False
                
        ### Create database backend object
        self.db = dataBaseBackend(typed=options.type, from_to=self.from_to,
                                  id_list=self.idlist, offsets=self.offsets,
                                  as_function_of_t=self.as_function_of_t,
                                  shift_temp_unit=self.shift_temp_unit,
                                  shift_be_ke=self.shift_be_ke)

        ### Ask self.db for a measurement count
        measurement_count = self.db.get_data_count()

        # Set the image format to standard, overwite with gs value and again
        # options value if i exits
        if options.image_format:
            if options.image_format == 'default':
                if self.db.global_settings.has_key('image_format'):
                    self.image_format = self.db.global_settings['image_format']
                else:
                    self.image_format = 'png'
            else:
                self.image_format = options.image_format
        else:
            self.image_format = 'png'
        
        # Create a hash from the measurement_count, options and
        #self.db.global_settings
        hash = hashlib.md5()
        hash.update(str(options) + str(self.db.global_settings) +
                    str(measurement_count))
        # self.namehash is unique for this plot and will form the filename
        self.namehash = ('/var/www/cinfdata/figures/' + hash.hexdigest() + '.' +
                         self.image_format)
        
        # For use in other methods
        self.options = options
 
        # object to give first good color, and then random colors
        self.c = Color()

        self.left_color = 'black'
        self.right_color = 'black'


    def main(self):
        if os.path.exists(self.namehash) and False:
            print self.namehash
        else:
            # Call a bunch of functions
            self._init_plot()
            self._plot()
            if self.left_color != 'black':
                if self.right_color != 'black':
                    self.c.color_axis(self.ax1, self.ax2, self.left_color, self.right_color)
                else:
                    self.c.color_axis(self.ax1, None, self.left_color, None)
            self._legend()
            self._zoom_and_flip()
            self._transform_and_label_axis()
            if not self.small_plot:
                self._title()
            self._grids()
            self._save()

    def _init_plot(self):
        ### Apply settings        
        # Small plots
        if self.small_plot:
            # Apply default settings 
            plt.rcParams.update({'figure.figsize':[4.5, 3.0],
                                 'ytick.labelsize':'x-small',
                                 'xtick.labelsize':'x-small',
                                 'legend.fontsize':'x-small'})
            # Overwrite with values from graphsettings
            plt.rcParams.update(self.db.global_settings['rcparams_small'])
        else:
            plt.rcParams.update({'figure.figsize':[9.0, 6.0],
                                 'axes.titlesize':'24',
                                 'legend.fontsize':'small'})
            plt.rcParams.update(self.db.global_settings['rcparams_regular'])

        self.fig = plt.figure(1)

        self.ax1 = self.fig.add_subplot(111)
        self.ax2 = None

        # Decide on the y axis type
        self.gs = self.db.global_settings
        if self.logscale:
            self.ax1.set_yscale('log')
        elif self.gs['default_yscale'] == 'log':
            self.ax1.set_yscale('log')
    
    def _plot(self):
        # Make plot
        data_in_plot = False
        for data in self.db.get_data():
            if len(data['data']) > 0:
                data_in_plot = data_in_plot or True
                # Speciel case for barplots
                if self.db.global_settings.has_key('default_style') and\
                        self.db.global_settings['default_style'] == 'barplot':
                    self.ax1.bar(data['data'][:,0], data['data'][:,1],
                                 color=self.c.get_color())
                # Normal graph styles
                else:
                    # If the graph go on the right side of the plot
                    if data['info']['on_the_right']:
                        # Initialise secondary plot if it isn't already
                        if not self.ax2:
                            self._init_second_y_axis()
                        # If info has a color (i.e. it is given in gs ordering)
                        if data['info'].has_key('color'):
                            # Set the color for the graph and axis
                            color = data['info']['color']
                            if 'overview' in self.options.type:
                                self.right_color = data['info']['color']
                        else:
                            # Else get a new color from self.c
                            color = self.c.get_color()
                        
                        # Make the actual plot
                        self.ax2.plot(data['data'][:,0], data['data'][:,1],
                                      color=color,
                                      label=self._legend_item(data)+'(R)')
                    # If the graph does not go on the right side of the plot
                    else:
                        # If info has a color (i.e. it is given in gs ordering)
                        if data['info'].has_key('color'):
                            # Set the color for the graph and axis
                            color = data['info']['color']
                            if 'overview' in self.options.type:
                                self.left_color = data['info']['color']
                        else:
                            # Else get a new color from self.c
                            color = self.c.get_color()
                        
                        # Make the actual plot
                        self.ax1.plot(data['data'][:,0], data['data'][:,1],
                                      color=color,
                                      label=self._legend_item(data))
        
        # If no data has been been put on the graph at all, explain why there
        # is none
        if not data_in_plot:
            y = 0.00032 if self.logscale or self.gs['default_yscale'] == 'log' else 0.5
            self.ax1.text(0.5, y, 'No data', horizontalalignment='center',
                          verticalalignment='center', color='red', size=60)

    def _legend(self):
        if self.db.global_settings['default_xscale'] != 'dat':
            ax1_legends = self.ax1.get_legend_handles_labels()
            if self.ax2:
                ax2_legends = self.ax2.get_legend_handles_labels()
                for color, text in zip(ax2_legends[0], ax2_legends[1]):
                    ax1_legends[0].append(color)
                    ax1_legends[1].append(text)
                    
            # loc for locations, 0 means 'best'. Why that isn't deafult I
            # have no idea
            self.ax1.legend(ax1_legends[0], ax1_legends[1], loc=0)

    def _zoom_and_flip(self):
        # Now we are done with the plotting, change axis if necessary
        # Get current axis limits
        self.axis = self.ax1.axis()
        if self.options.xmin != self.options.xmax:
            self.axis = (float(self.options.xmin), float(self.options.xmax)) +\
                self.axis[2:4]
        if self.options.ymin != self.options.ymax:
            self.axis = self.axis[0:2] + (float(self.options.ymin),
                                          float(self.options.ymax))
        if self.flip_x:
            self.axis = (self.axis[1], self.axis[0]) + self.axis[2:4]
        self.ax1.axis(self.axis)
        
    def _transform_and_label_axis(self):
        """ Transform X-AXIS axis and label it """
        
        # If it is a date plot
        if self.db.global_settings['default_xscale'] == 'dat':
            # Turn the x-axis into timemarks
            # IMPLEMENT add something to TimeMarks initialisation to take care
            # or morning_pressure
            markformat = '%H:%M' if self.small_plot else '%b-%d %H:%M'
            timemarks = TimeMarks(self.axis[0], self.axis[1],
                                  markformat=markformat)
            (old_tick_labels, new_tick_labels) = timemarks.get_time_marks()
            self.ax1.set_xticks(old_tick_labels)
            self.bbox_xlabels = self.ax1.\
                set_xticklabels(new_tick_labels, rotation=25,
                                horizontalalignment='right')
            # Make a little extra room for the rotated x marks
            #self.fig.subplots_adjust(bottom=0.12)
        elif self.options.type == 'masstime':
            gs_temp_unit = self.gs['temperature_unit']
            other_temp_unit = 'C' if gs_temp_unit == 'K' else 'K'
            cur_temp_unit = other_temp_unit if self.shift_temp_unit else\
                gs_temp_unit
            if self.as_function_of_t and not self.small_plot:
                self.ax1.set_xlabel(self.gs['t_xlabel'] + cur_temp_unit)
            elif not self.small_plot:
                self.ax1.set_xlabel(self.gs['xlabel'])
        elif self.options.type == 'xps':
            if self.shift_be_ke and not self.small_plot:
                self.ax1.set_xlabel(self.gs['alt_xlabel'])
            elif not self.small_plot:
                self.ax1.set_xlabel(self.gs['xlabel'])
        elif not self.small_plot:
            self.ax1.set_xlabel(self.gs['xlabel'])
        
        # Label Y-axis
        if not self.small_plot:
            self.ax1.set_ylabel(self.gs['ylabel'], color=self.left_color)
            if self.ax2:
                self.ax2.set_ylabel(self.gs['right_ylabel'], color=self.right_color)

    def _title(self):
        """ TITLE """
        # Set the title and raise it a bit
        if self.as_function_of_t:
            self.bbox_title = self.ax1.set_title(
                self.gs['t_title'], y=1.03)
        else:
            self.bbox_title = self.ax1.set_title(
                self.gs['title'], y=1.03)
            
    def _grids(self):
        # GRIDS
        self.ax1.grid(b=True, which = 'major')
        #plt.xscale('linear')
        #plt.xticks(range(0,100,10))
        #plt.x_minor_ticks(range(0,100,10))
        #plt.grid(b='on', which='minor')
        #plt.grid(b='on', which='major')

    def _save(self):
        ## Filesave
        # Save
        self.fig.savefig(self.namehash, bbox_inches='tight', pad_inches=0.03)

        # This is the magical line that plot.php opens
        # For the script to work this has to be the only print statement
        print self.namehash

    ### Here start the small helper functions that are called from the main flow

    def _init_second_y_axis(self):
        self.ax2 = self.ax1.twinx()
        if self.db.global_settings['right_yscale'] == 'log':
            self.ax2.set_yscale('log')

    def _legend_item(self, data):
        if self.db.global_settings['default_xscale'] == 'dat':
            return ''
        elif data['gs'].has_key('legend_field_name') and\
                data['info'][data['gs']['legend_field_name']]:
            return data['info']['mass_label'] + '-' + str(data['info']['id'])
        else:
            return str(data['info']['id'])
コード例 #4
0
class Plot():
    """This class is used to generate the figures for the plots."""
    
    def __init__(self, options, ggs):
        """ Description of init """
        
        self.o = options
        self.ggs = ggs
        
        # Set the image format to standard, overwite with ggs value and again
        # options value if it exits
        if self.o['image_format'] == '':
            self.image_format = self.ggs['image_format']
        else:
            self.image_format = self.o['image_format']

        # Default values for matplotlib plots (names correspond to ggs names)
        mpl_settings = {'width': 900,
                        'height': 600,
                        'title_size': '24',
                        'xtick_labelsize': '12',
                        'ytick_labelsize': '12',
                        'legend_fontsize': '10',
                        'label_fontsize': '16',
                        'linewidth': 1.0,
                        'grid': False}
        
        # Owerwrite defaults with gs values and convert to appropriate types
        for key, value in mpl_settings.items():
            try:
                mpl_settings[key] = type(value)(self.ggs['matplotlib_settings'][key])
            except KeyError:
                pass
        
        # Write some settings to pyplot
        rc_temp = {'figure.figsize': [float(mpl_settings['width'])/100,
                                      float(mpl_settings['height'])/100],
                   'axes.titlesize': mpl_settings['title_size'],
                   'xtick.labelsize': mpl_settings['xtick_labelsize'],
                   'ytick.labelsize': mpl_settings['ytick_labelsize'],
                   'legend.fontsize': mpl_settings['legend_fontsize'],
                   'axes.labelsize': mpl_settings['label_fontsize'],
                   'lines.linewidth': mpl_settings['linewidth'],
                   'axes.grid': mpl_settings['grid']
                   }
        plt.rcParams.update(rc_temp)
                                                        
        # Plotting options
        self.maxticks=15
        self.tz = timezone('Europe/Copenhagen')
        self.right_yaxis = None
        self.measurement_count = None
 
        # Colors object, will be filled in at new_plot
        self.c = None

    def new_plot(self, data, plot_info, measurement_count):
        """ Form a new plot with the given data and info """
        self.c = Color(data, self.ggs)

        self.measurement_count = sum(measurement_count)
        self._init_plot(data)
        # _plot returns True or False to indicate whether the plot is good
        if self._plot(data):
            self._zoom_and_flip(data)
            self._title_and_labels(plot_info)
        self._save(plot_info)

    def _init_plot(self, data):
        """ Initialize plot """
        self.fig = plt.figure(1)
        self.ax1 = self.fig.add_subplot(111)

        # We only activate the right y-axis, if there there points to put on it
        self.right_yaxis = sum([len(dat['data']) for dat in data['right']]) > 0

        if self.right_yaxis:
            self.ax2 = self.ax1.twinx()

        if self.o['left_logscale']:
            self.ax1.set_yscale('log')
        if self.right_yaxis and self.o['right_logscale']:
            self.ax2.set_yscale('log')

    def _plot(self, data):
        """ Determine the type of the plot and make the appropriate plot by use
        of the functions:
          _plot_dateplot
          _plot_xyplot
        """
        if self.ggs['default_xscale'] == 'dat':
            return self._plot_dateplot(data)
        else:
            return self._plot_xyplot(data)

    def _plot_dateplot(self, data):
        """ Make the date plot """
        # Rotate datemarks on xaxis
        self.ax1.set_xticklabels([], rotation=25, horizontalalignment='right')

        # Test for un-workable plot configurations
        error_msg = None
        # Test if there is data on the left axis
        if sum([len(dat['data']) for dat in data['left']]) == 0:
            error_msg = 'There must\nbe data on\nthe left y-axis'
        # Test if there is any data at all
        if self.measurement_count == 0:
            error_msg = 'No data'
        # No data
        if error_msg:
            y = 0.00032 if self.o['left_logscale'] is True else 0.5
            self.ax1.text(0.5, y, error_msg, horizontalalignment='center',
                          verticalalignment='center', color='red', size=60)
            return False

        # Left axis
        for dat in data['left']:
            # Form legend
            if dat['lgs'].has_key('legend'):
                legend = dat['lgs']['legend']
            else:
                legend = None
            # Plot
            if len(dat['data']) > 0:
                self.ax1.plot_date(mdates.epoch2num(dat['data'][:,0]),
                                   dat['data'][:,1],
                                   label=legend,
                                   xdate=True,
                                   color=self.c.get_color(),
                                   tz=self.tz,
                                   fmt='-')
        # Right axis
        if self.right_yaxis:
            for dat in data['right']:
                # Form legend
                if dat['lgs'].has_key('legend'):
                    legend = dat['lgs']['legend']
                else:
                    legend = None
                # Plot
                if len(dat['data']) > 0:
                    self.ax2.plot_date(mdates.epoch2num(dat['data'][:,0]),
                                       dat['data'][:,1],
                                       label=legend,
                                       xdate=True,
                                       color=self.c.get_color(),
                                       tz=self.tz,
                                       fmt='-')

        # Set xtick formatter (only if we have points)
        if self.measurement_count > 0:
            xlim = self.ax1.set_xlim()
            diff = max(xlim) - min(xlim)  # in days
            format_out = '%H:%M:%S'  # Default
            # Diff limit to date format translation, will pick the format
            # format of the largest limit the diff is larger than. Limits
            # are in minutes.
            formats = [
                [1.0,              '%a %H:%M'],  # Larger than 1 day
                [7.0,              '%Y-%m-%d'],  # Larger than 7 day
                [7*30.,              '%Y-%m'],  # Larger than 3 months
                ]
            for limit, format in formats:
                if diff > limit:
                    format_out = format
            fm = mdates.DateFormatter(format_out, tz=self.tz)
            self.ax1.xaxis.set_major_formatter(fm)

        # Indicate that the plot is good
        return True

    def _plot_xyplot(self, data):
        # Left axis
        for dat in data['left']:
            # Form legend
            if dat['lgs'].has_key('legend'):
                legend = dat['lgs']['legend']
            else:
                legend = None
            # Plot
            if len(dat['data']) > 0:
                self.ax1.plot(dat['data'][:,0],
                              dat['data'][:,1],
                              '-',
                              label=legend,
                              color=self.c.get_color(dat['lgs']['id']),
                              )
        # Right axis
        for dat in data['right']:
            # Form legend
            if dat['lgs'].has_key('legend'):
                legend = dat['lgs']['legend']
            else:
                legend = None
            # Plot
            if len(dat['data']) > 0:
                self.ax2.plot(dat['data'][:,0],
                              dat['data'][:,1],
                              '-',
                              label=legend,
                              color=self.c.get_color(dat['lgs']['id'])
                              )
        # No data
        if self.measurement_count == 0:
            y = 0.00032 if self.o['left_logscale'] is True else 0.5
            self.ax1.text(0.5, y, 'No data', horizontalalignment='center',
                          verticalalignment='center', color='red', size=60)

        # Indicate that the plot is good
        return True

    def _zoom_and_flip(self, data):
        """ Apply the y zooms.
        NOTE: self.ax1.axis() return a list of bounds [xmin,xmax,ymin,ymax] and
        we reuse x and replace y)
        """
        left_yscale_inferred = self.o['left_yscale_bounding']
        right_yscale_inferred = self.o['right_yscale_bounding']

        # X-axis zoom and infer y-axis zoom implications
        if self.o['xscale_bounding'] is not None and\
                self.o['xscale_bounding'][1] > self.o['xscale_bounding'][0]:
            # Set the x axis scaling, unsure if we should do it for ax2 as well
            self.ax1.set_xlim(self.o['xscale_bounding'])
            # With no specific left y-axis zoom, infer it from x-axis zoom
            if left_yscale_inferred is None:
                left_yscale_inferred = self._infer_y_on_x_zoom(
                    data['left'], self.o['left_logscale'])
            # With no specific right y-axis zoom, infer it from x-axis zoom
            if right_yscale_inferred is None and self.right_yaxis:
                right_yscale_inferred = self._infer_y_on_x_zoom(
                    data['right'])

        # Left axis 
        if left_yscale_inferred is not None:
            self.ax1.set_ylim(left_yscale_inferred)
        # Right axis
        if self.right_yaxis and right_yscale_inferred is not None:
            self.ax2.set_ylim(right_yscale_inferred)

        if self.o['flip_x']:
            self.ax1.set_xlim((self.ax1.set_xlim()[1],self.ax1.set_xlim()[0]))

    def _infer_y_on_x_zoom(self, list_of_data_sets, log=None):
        """Infer the implied Y axis zoom with an X axis zoom, for one y axis"""
        yscale_inferred = None
        min_candidates = []
        max_candidates = []
        for dat in list_of_data_sets:
            # Make mask that gets index for points where x is within bounds
            mask = (dat['data'][:, 0] > self.o['xscale_bounding'][0]) &\
                (dat['data'][:, 0] < self.o['xscale_bounding'][1])
            # Gets all the y values from that mask
            reduced = dat['data'][mask, 1]
            # Add min/max candidates
            if len(reduced) > 0:
                min_candidates.append(np.min(reduced))
                max_candidates.append(np.max(reduced))
        # If there are min/max candidates, set the inferred left y bounding
        if len(min_candidates) > 0 and len(max_candidates) > 0:
            min_, max_ = np.min(min_candidates), np.max(max_candidates)
            height = max_ - min_
            yscale_inferred = (min_ - height*0.05, max_ + height*0.05)
        return yscale_inferred

    def _title_and_labels(self, plot_info):
        """ Put title and labels on the plot """
        # xlabel
        if plot_info.has_key('xlabel'):
            label = plot_info['xlabel']
            if plot_info['xlabel_addition'] != '':
                label += '\n' + plot_info['xlabel_addition']
            self.ax1.set_xlabel(label)
        if self.o['xlabel'] != '':  # Manual override
            self.ax1.set_xlabel(r'{0}'.format(self.o['xlabel']))
        # Left ylabel
        if plot_info.has_key('left_ylabel'):
            label = plot_info['left_ylabel']
            if plot_info['y_left_label_addition'] != '':
                label += '\n' + plot_info['y_left_label_addition']
            self.ax1.set_ylabel(label, multialignment='center')
        if self.o['left_ylabel'] != '':  # Manual override
            self.ax1.set_ylabel(self.o['left_ylabel'], multialignment='center')
        # Right ylabel
        if self.right_yaxis and plot_info.has_key('right_ylabel'):
            label = plot_info['right_ylabel']
            if plot_info['y_right_label_addition'] != '':
                label += '\n' + plot_info['y_right_label_addition']
            self.ax2.set_ylabel(label, multialignment='center', rotation=270)
            if self.o['right_ylabel'] != '':  # Manual override
                self.ax2.set_ylabel(self.o['right_ylabel'],
                                    multialignment='center', rotation=270)
        # Title
        if plot_info.has_key('title'):
            self.ax1.set_title(plot_info['title'], y=1.03)
        if self.o['title'] != '':
            # experiment with 'r{0}'.form .. at some time
            self.ax1.set_title('{0}'.format(self.o['title']), y=1.03)

        # Legends
        if self.measurement_count > 0:
            ax1_legends = self.ax1.get_legend_handles_labels()
            if self.right_yaxis:
                ax2_legends = self.ax2.get_legend_handles_labels()
                for color, text in zip(ax2_legends[0], ax2_legends[1]):
                    ax1_legends[0].append(color)
                    ax1_legends[1].append(text)
                    
            # loc for locations, 0 means 'best'. Why that isn't deafult I
            # have no idea
            legends = self.ax1.legend(ax1_legends[0], ax1_legends[1], loc=0)

            # Make legend lines thicker
            for legend_handle in legends.legendHandles:
                legend_handle.set_linewidth(6)

    def _save(self, plot_info):
        """ Save the figure """
        # The tight method only works if there is a title (it caps of parts of
        # the axis numbers, therefore this hack, this may also become a problem
        # for the other edges of the figure if there are no labels)
        tight = ''
        if plot_info.has_key('title'):
            tight = 'tight'
        # For some wierd reason we cannot write directly to sys.stdout when it
        # is a pdf file, so therefore we use a the StringIO object workaround
        if self.o['image_format'] == 'pdf':
            import StringIO
            out = StringIO.StringIO()
            self.fig.savefig(out, bbox_inches=tight, pad_inches=0.03,
                             format=self.o['image_format'])
            sys.stdout.write(out.getvalue())
        else:
            self.fig.savefig(sys.stdout, bbox_inches=tight, pad_inches=0.03,
                             format=self.o['image_format'])