コード例 #1
0
    def __init__(self, name):
        """ Initialize a texture from a tga file
            
            Note: This is hand-coded. With a more robust renderer, we could
            probably use an image loader 
        """
        self._width: int = 0
        self._height: int = 0
        self._pixels: [Color] = []

        path = "{}{}{}{}".format('Resources', os.path.sep, name, '.tga')

        with open(path, 'rb') as fd:
            try:
                # Read file header
                # TODO worry about sign? (we should be reading uint8)
                # Note: header is of type "bytes"
                header = fd.read(18)
            except Exception as e:
                print("Couldn't load the tga {}: {}".format(path, e))
                traceback.print_exc()
                return

            useColorMap = header[0] != 0
            imageType = int(header[2])
            if useColorMap or imageType in (0, 1, 3):
                raise Exception("{} is not a color tga".format(path))
                return

            IDLength = header[0]
            self._width = int(header[13]) * 256 + int(header[12])
            self._height = int(header[15]) * 256 + int(header[14])
            pixelDepth = header[16]

            lengthImage = int(pixelDepth) * self._width * self._height // 8

            fd.seek(18 + int(IDLength))
            content = fd.read(lengthImage)

            if pixelDepth == 8:
                self._pixels = [
                    Color(
                        float(byt) / 255.0,
                        float(byt) / 255.0,
                        float(byt) / 255.0) for byt in content
                ]
            else:
                pixelBytes = pixelDepth // 8

                for i in range(0, (self._width * self._height)):
                    r = float(content[pixelBytes * i + 2]) / 255.0
                    g = float(content[pixelBytes * i + 1]) / 255.0
                    b = float(content[pixelBytes * i]) / 255.0
                    self._pixels.append(Color(r, g, b))
コード例 #2
0
    def clear(self, color: Color = Color(0.0)):
        """ Clear the frame buffer

            By default, the color is black (0,0,0)
            But other colors can be specified
        """
        for i in range(0, self.width * self.height):
            self._colorBuffer[i] = color
            self._depthBuffer[i] = 1.0
コード例 #3
0
 def new_plot(self, data, plot_info, measurement_count):
     """ Produce all the plot output by calls to the different
     subsection methods
     """
     self.c = Color(data, self.ggs)
     self.measurement_count = sum(measurement_count)
     self._header()
     self._data(data)
     self._options(data, plot_info)
     self._end()
コード例 #4
0
    def __init__(self, w=0, h=0):
        ## "public"
        self.width = int(w)
        self.height = int(h)

        ## "private"
        # array of Color objects
        self._colorBuffer = [Color()] * self.width * self.height
        # array of floats (0.0 - 1.0)
        self._depthBuffer = [1.0] * self.width * self.height
コード例 #5
0
    def __init__(self, options, ggs):
        """ Initialize variables """
        self.o = options
        self.ggs = ggs  # Global graph settings

        self.right_yaxis = len(self.o['right_plotlist']) > 0
        self.out = sys.stdout
        self.tab = '    '
        # object to give first good color, and then random colors
        self.c = Color()
        self.reduction = 1
コード例 #6
0
    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)
コード例 #7
0
    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
 
        # object to give first good color, and then random colors
        self.c = Color()
コード例 #8
0
    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'