Beispiel #1
0
def mmi_ramp(raster_layer):
    """Generate an mmi ramp using standardised range of 1-12

    A standarised range is used so that two shakemaps of different
    intensities can be properly compared visually with colours stretched
    accross the same range.

    The colours used are the 'standard' colours commonly shown for the
    mercalli scale e.g. on wikipedia and other sources.

    :param raster_layer: A raster layer that will have an mmi style applied.
    :type raster_layer: QgsRasterLayer
    """

    items = []
    for class_max in range(1, 13):
        colour = QtGui.QColor(mmi_colour(class_max))
        label = '%i' % class_max
        ramp_item = QgsColorRampShader.ColorRampItem(class_max, colour, label)
        items.append(ramp_item)

    raster_shader = QgsRasterShader()
    ramp_shader = QgsColorRampShader()
    ramp_shader.setColorRampType(QgsColorRampShader.INTERPOLATED)
    ramp_shader.setColorRampItemList(items)
    raster_shader.setRasterShaderFunction(ramp_shader)
    band = 1
    renderer = QgsSingleBandPseudoColorRenderer(
        raster_layer.dataProvider(),
        band,
        raster_shader)
    raster_layer.setRenderer(renderer)
Beispiel #2
0
def createRasterShader(fields, mode = "rgb", scale = "float"):
    shader = QgsRasterShader()
    colRamp = QgsColorRampShader()
    colRamp.setColorRampType(QgsColorRampShader.INTERPOLATED)
    
    ramp = []
    col = QColor()
    
    for line in fields:
        val = float(line[0])
        txt = unicode(line[1])
       
        if mode == "rgb" or mode == "rnd":
            if scale != "float":
                color = [float(x)/255.0 for x in line[2:6]]
            col.setRgbF(*color)
            
        elif mode == "hsv":
            if scale != "float":
                color = [float(x)/float(y) for x,y in zip(line[2:6], [360, 100, 100, 255])]
            col.setHsvF(*color)
            
        elif mode == "hex":
            col.setNamedColor(str(line[2]))

        ramp.append(QgsColorRampShader.ColorRampItem(val, col, txt))
    
    colRamp.setColorRampItemList(ramp)
    shader.setRasterShaderFunction(colRamp)
    
    return(shader)
    def testNan(self):
        shader = QgsColorRampShader()

        item1 = QgsColorRampShader.ColorRampItem(1, QColor(0, 0, 0))
        item2 = QgsColorRampShader.ColorRampItem(2, QColor(255, 255, 255))
        shader.setColorRampItemList([item1, item2])
        self.assertFalse(shader.shade(float('NaN'))[0])
        self.assertFalse(shader.shade(float("inf"))[0])
 def aggregate_layers(self, layers, d):
     aggregation = self.frequency.itemData(self.frequency.currentIndex())
     month = str(d.month)
     month = month if len(month) == 2 else '0' + month
     day = str(d.day)
     day = day if len(day) == 2 else '0' + day
     filtered_layers = filter(lambda x: '.tif' in x, layers)
     datasets = []
     file_name = None
     for l in filtered_layers:
         datasets.append(Dataset(l))
     sum = datasets[0]
     for i in range(1,len(datasets)-1):
         sum += datasets[i]
     if aggregation == 'SUM':
         Env.overwrite = True
         avg = sum
         file_name = self.download_folder.text() + '/' + str(d.year) + '_' + month + '_' + day + '_SUM.tif'
         avg.save(file_name)
     elif aggregation == 'AVG':
         Env.overwrite = True
         avg = sum
         avg /= len(datasets)
         file_name = self.download_folder.text() + '/' + str(d.year) + '_' + month + '_' + day + '_AVG.tif'
         avg.save(file_name)
     if self.add_to_canvas.isChecked() is True:
         self.bar.pushMessage(None, str(file_name), level=QgsMessageBar.INFO)
         title = None
         if aggregation == 'SUM':
             title = self.tr('TRMM Aggregate (Sum): ') + str(d.year) + '-' + str(month) + '-' + str(day)
         elif aggregation == 'AVG':
             title = self.tr('TRMM Aggregate (Average): ') + str(d.year) + '-' + str(month) + '-' + str(day)
         rl = self.iface.addRasterLayer(file_name, title)
         fcn = QgsColorRampShader()
         fcn.setColorRampType(QgsColorRampShader.INTERPOLATED)
         lst = [
             QgsColorRampShader.ColorRampItem(0, QColor(247, 251, 255, 0), '< 2.6 [mm]'),
             QgsColorRampShader.ColorRampItem(2.6, QColor(222, 235, 247), '< 5.2 [mm]'),
             QgsColorRampShader.ColorRampItem(5.2, QColor(199, 220, 239), '< 7.8 [mm]'),
             QgsColorRampShader.ColorRampItem(7.8, QColor(162, 203, 226), '< 10.4 [mm]'),
             QgsColorRampShader.ColorRampItem(10.4, QColor(114, 178, 215), '< 13 [mm]'),
             QgsColorRampShader.ColorRampItem(13, QColor(73, 151, 201), '< 15.6 [mm]'),
             QgsColorRampShader.ColorRampItem(15.6, QColor(40, 120, 184), '< 18 [mm]'),
             QgsColorRampShader.ColorRampItem(18, QColor(13, 87, 161), '< 20 [mm]'),
             QgsColorRampShader.ColorRampItem(20, QColor(8, 48, 107), '>= 20 [mm]')
         ]
         fcn.setColorRampItemList(lst)
         shader = QgsRasterShader()
         shader.setRasterShaderFunction(fcn)
         renderer = QgsSingleBandPseudoColorRenderer(rl.dataProvider(), 1, shader)
         rl.setRenderer(renderer)
         rl.triggerRepaint()
    def testShaderCrash(self):
        """Check if we assign a shader and then reassign it no crash occurs."""
        myPath = os.path.join(unitTestDataPath('raster'),
                              'band1_float32_noct_epsg4326.tif')
        myFileInfo = QFileInfo(myPath)
        myBaseName = myFileInfo.baseName()
        myRasterLayer = QgsRasterLayer(myPath, myBaseName)
        myMessage = 'Raster not loaded: %s' % myPath
        assert myRasterLayer.isValid(), myMessage

        myRasterShader = QgsRasterShader()
        myColorRampShader = QgsColorRampShader()
        myColorRampShader.setColorRampType(QgsColorRampShader.INTERPOLATED)
        myItems = []
        myItem = QgsColorRampShader.ColorRampItem(10,
                                                  QtGui.QColor('#ffff00'), 'foo')
        myItems.append(myItem)
        myItem = QgsColorRampShader.ColorRampItem(100,
                                                  QtGui.QColor('#ff00ff'), 'bar')
        myItems.append(myItem)
        myItem = QgsColorRampShader.ColorRampItem(1000,
                                                  QtGui.QColor('#00ff00'), 'kazam')
        myItems.append(myItem)
        myColorRampShader.setColorRampItemList(myItems)
        myRasterShader.setRasterShaderFunction(myColorRampShader)
        myPseudoRenderer = QgsSingleBandPseudoColorRenderer(
            myRasterLayer.dataProvider(), 1,  myRasterShader)
        myRasterLayer.setRenderer(myPseudoRenderer)

        return
        ######## works first time #############

        myRasterShader = QgsRasterShader()
        myColorRampShader = QgsColorRampShader()
        myColorRampShader.setColorRampType(QgsColorRampShader.INTERPOLATED)
        myItems = []
        myItem = QgsColorRampShader.ColorRampItem(10,
                                                  QtGui.QColor('#ffff00'), 'foo')
        myItems.append(myItem)
        myItem = QgsColorRampShader.ColorRampItem(100,
                                                  QtGui.QColor('#ff00ff'), 'bar')
        myItems.append(myItem)
        myItem = QgsColorRampShader.ColorRampItem(1000,
                                                  QtGui.QColor('#00ff00'), 'kazam')
        myItems.append(myItem)
        myColorRampShader.setColorRampItemList(myItems)
        myRasterShader.setRasterShaderFunction(myColorRampShader)
        ######## crash on next line (fixed now)##################
        myPseudoRenderer = QgsSingleBandPseudoColorRenderer(
            myRasterLayer.dataProvider(), 1,  myRasterShader)
        myRasterLayer.setRenderer(myPseudoRenderer)
def setRamp(layer, iface):
    
    renderer = layer.renderer()
    provider = layer.dataProvider()
    extent = layer.extent()
    
    ver = provider.hasStatistics(1, QgsRasterBandStats.All)
    
    stats = provider.bandStatistics(1, QgsRasterBandStats.All,extent, 0)
    
    if ver is not False:
        print "minimumValue = ", stats.minimumValue
    
        print "maximumValue = ", stats.maximumValue
    
    if (stats.minimumValue < 0):
        min = 0  
    
    else: 
        min= stats.minimumValue
    
    max = stats.maximumValue
    range = max - min
    add = range//2
    interval = min + add
    
    colDic = {'red':'#ff0000', 'yellow':'#ffff00','blue':'#0000ff'}
    
    valueList =[min, interval, max]
    
    lst = [ QgsColorRampShader.ColorRampItem(valueList[0], QColor(colDic['red'])), 
            QgsColorRampShader.ColorRampItem(valueList[1], QColor(colDic['yellow'])), 
            QgsColorRampShader.ColorRampItem(valueList[2], QColor(colDic['blue']))]
    
    myRasterShader = QgsRasterShader()
    myColorRamp = QgsColorRampShader()
    
    myColorRamp.setColorRampItemList(lst)
    myColorRamp.setColorRampType(QgsColorRampShader.INTERPOLATED)
    myRasterShader.setRasterShaderFunction(myColorRamp)
    
    myPseudoRenderer = QgsSingleBandPseudoColorRenderer(layer.dataProvider(), 
                                                        layer.type(),  
                                                        myRasterShader)
    
    layer.setRenderer(myPseudoRenderer)
    
    layer.triggerRepaint()
Beispiel #7
0
def displaced_people_style(layer):
    """Simple style to display a displaced count with a binary style.

    :param layer: The layer to style.
    :type layer: QgsRasterLayer
    """
    color_ramp = QgsColorRampShader()
    color_ramp.setColorRampType(QgsColorRampShader.INTERPOLATED)
    color_ramp.setColorRampItemList(legend_raster_displaced)

    shader = QgsRasterShader()
    shader.setRasterShaderFunction(color_ramp)

    renderer = QgsSingleBandPseudoColorRenderer(
        layer.dataProvider(), 1, shader)

    layer.setRenderer(renderer)
Beispiel #8
0
    def loadLabelImage(imagepath, labeldescriptor = None):
        """
        Load a labeled single band raster in the canvas

        Keyword arguments:
        imagepath -- the path to the image
        labeldescriptor -- a dictionnary for label (int) to tuple (QColor, QString) conversion
        """
        if imagepath is None:
            return

        name = os.path.splitext( os.path.basename(imagepath) )[0]
        qgslayer = QgsRasterLayer(imagepath, name)
        if not qgslayer.isValid():
            QtGui.QMessageBox.critical(None,
                                       u"Erreur",
                                       u"Impossible de charger la couche %s" % unicode(imagepath))

        QgsMapLayerRegistry.instance().addMapLayer(qgslayer)

        qgslayer.setDrawingStyle('SingleBandPseudoColor')

        colorlist = []
        max_label = 0
        for label in sorted(labeldescriptor.keys()):
            color = labeldescriptor[label][0]
            labeltxt = labeldescriptor[label][1]
            colorlist.append(QgsColorRampShader.ColorRampItem(label, color, labeltxt))
            if labeltxt > max_label:
                max_label = labeltxt

        s = QgsRasterShader()
        c = QgsColorRampShader()
        c.setColorRampType(QgsColorRampShader.INTERPOLATED)
        c.setColorRampItemList(colorlist)
        s.setRasterShaderFunction(c)
        ps = QgsSingleBandPseudoColorRenderer(qgslayer.dataProvider(), 1, s)
        qgslayer.setRenderer(ps)

        for bandNo in range(1,qgslayer.dataProvider().bandCount()+1):
            qgslayer.dataProvider().setUseSrcNoDataValue( bandNo, False )

        QGisLayers.iface.legendInterface().refreshLayerSymbology(qgslayer)
        if hasattr(qgslayer, "setCacheImage"):
            qgslayer.setCacheImage(None)
        qgslayer.triggerRepaint()
Beispiel #9
0
def mmi_ramp_roman(raster_layer):
    """Generate an mmi ramp using range of 1-10 on roman.

    A standarised range is used so that two shakemaps of different
    intensities can be properly compared visually with colours stretched
    accross the same range.

    The colours used are the 'standard' colours commonly shown for the
    mercalli scale e.g. on wikipedia and other sources.

    :param raster_layer: A raster layer that will have an mmi style applied.
    :type raster_layer: QgsRasterLayer

    .. versionadded:: 4.0
    """

    items = []
    sorted_mmi_scale = sorted(
        earthquake_mmi_scale['classes'], key=itemgetter('value'))
    for class_max in sorted_mmi_scale:
        colour = class_max['color']
        label = '%s' % class_max['key']
        ramp_item = QgsColorRampShader.ColorRampItem(
            class_max['value'], colour, label)
        items.append(ramp_item)

    raster_shader = QgsRasterShader()
    ramp_shader = QgsColorRampShader()
    ramp_shader.setColorRampType(QgsColorRampShader.INTERPOLATED)
    ramp_shader.setColorRampItemList(items)
    raster_shader.setRasterShaderFunction(ramp_shader)
    band = 1
    renderer = QgsSingleBandPseudoColorRenderer(
        raster_layer.dataProvider(),
        band,
        raster_shader)
    raster_layer.setRenderer(renderer)
    def __init__(self, layer):
        self.colDic = {'tan':'#ffebb0', 'green':'#267300', 'brown':'#734d00', 'white':'#ffffff',
                                'red':'#e60000', 'light gray':'#f0f0f0', 'blue':'#004cab'}
        self.shader = QgsRasterShader()
        self.ramp = QgsColorRampShader()
        self.colLst = []
        self.valLst = []
        self.labLst = []
        self.opacity = 1.0

        self.layer = layer
        self.provider = layer.dataProvider()
        extent = layer.extent()
        self.ver = self.provider.hasStatistics(1, QgsRasterBandStats.All)
        self.stats = self.provider.bandStatistics(1, QgsRasterBandStats.All, extent, 0)
    def testSingleBandPseudoColorRenderer_Interpolated(self):
        # get min and max of the band to renderer
        bandNo = 3
        stats = self.raster_layer.dataProvider().bandStatistics(bandNo, QgsRasterBandStats.Min | QgsRasterBandStats.Max)
        minValue = stats.minimumValue
        maxValue = stats.maximumValue
        # create shader for the renderer
        shader = QgsRasterShader(minValue, maxValue)
        colorRampShaderFcn = QgsColorRampShader(minValue, maxValue)
        colorRampShaderFcn.setColorRampType(QgsColorRampShader.Interpolated)
        colorRampShaderFcn.setClassificationMode(QgsColorRampShader.Continuous)
        colorRampShaderFcn.setClip(True)
        items = []
        for index in range(10):
            items.append(QgsColorRampShader.ColorRampItem(index, QColor('#{0:02d}{0:02d}{0:02d}'.format(index)), "{}".format(index)))
        colorRampShaderFcn.setColorRampItemList(items)
        shader.setRasterShaderFunction(colorRampShaderFcn)
        # create instance to test
        rasterRenderer = QgsSingleBandPseudoColorRenderer(self.raster_layer.dataProvider(), bandNo, shader)
        self.raster_layer.setRenderer(rasterRenderer)

        # do test
        dom, root = self.rendererToSld(self.raster_layer.renderer())
        self.assertNoOpacity(root)
        self.assertChannelBand(root, 'sld:GrayChannel', '{}'.format(bandNo))
        # check ColorMapEntry classes
        colorMap = root.elementsByTagName('sld:ColorMap')
        colorMap = colorMap.item(0).toElement()
        self.assertFalse(colorMap.isNull())
        self.assertEqual(colorMap.attribute('type'), 'ramp')
        colorMapEntries = colorMap.elementsByTagName('sld:ColorMapEntry')
        self.assertEqual(colorMapEntries.count(), 10)
        for index in range(colorMapEntries.count()):
            colorMapEntry = colorMapEntries.at(index).toElement()
            self.assertEqual(colorMapEntry.attribute('quantity'), '{}'.format(index))
            self.assertEqual(colorMapEntry.attribute('label'), '{}'.format(index))
            self.assertEqual(colorMapEntry.attribute('opacity'), '')
            self.assertEqual(colorMapEntry.attribute('color'), '#{0:02d}{0:02d}{0:02d}'.format(index))
Beispiel #12
0
def set_raster_style(raster_layer, style):
    """Set QGIS raster style based on InaSAFE style dictionary for QGIS >= 2.0.

    This function will set both the colour map and the transparency
    for the passed in layer.

    :param raster_layer: A QGIS raster layer that will be styled.
    :type raster_layer: QgsVectorLayer

    :param style: List of the form as in the example below.
    :type style: list

    Example::

        style_classes = [dict(colour='#38A800', quantity=2, transparency=0),
                         dict(colour='#38A800', quantity=5, transparency=50),
                         dict(colour='#79C900', quantity=10, transparency=50),
                         dict(colour='#CEED00', quantity=20, transparency=50),
                         dict(colour='#FFCC00', quantity=50, transparency=34),
                         dict(colour='#FF6600', quantity=100, transparency=77),
                         dict(colour='#FF0000', quantity=200, transparency=24),
                         dict(colour='#7A0000', quantity=300, transparency=22)]

    :returns: A two tuple containing a range list and a transparency list.
    :rtype: (list, list)

    """
    # Note imports here to prevent importing on unsupported QGIS versions
    # pylint: disable=E0611
    # pylint: disable=W0621
    # pylint: disable=W0404
    # noinspection PyUnresolvedReferences
    from qgis.core import (QgsRasterShader,
                           QgsColorRampShader,
                           QgsSingleBandPseudoColorRenderer,
                           QgsRasterTransparency)
    # pylint: enable=E0611
    # pylint: enable=W0621
    # pylint: enable=W0404

    ramp_item_list = []
    transparency_list = []
    LOGGER.debug(style)
    for style_class in style:

        LOGGER.debug('Evaluating class:\n%s\n' % style_class)

        if 'quantity' not in style_class:
            LOGGER.exception('Class has no quantity attribute')
            continue

        class_max = style_class['max']
        if math.isnan(class_max):
            LOGGER.debug('Skipping class - max is nan.')
            continue

        class_min = style_class['min']
        if math.isnan(class_min):
            LOGGER.debug('Skipping class - min is nan.')
            continue

        colour = QtGui.QColor(style_class['colour'])
        label = ''
        if 'label' in style_class:
            label = style_class['label']
        # noinspection PyCallingNonCallable
        ramp_item = QgsColorRampShader.ColorRampItem(class_max, colour, label)
        ramp_item_list.append(ramp_item)

        # Create opacity entries for this range
        transparency_percent = 0
        if 'transparency' in style_class:
            transparency_percent = int(style_class['transparency'])
        if transparency_percent > 0:
            # Check if range extrema are integers so we know if we can
            # use them to calculate a value range
            # noinspection PyCallingNonCallable
            pixel = QgsRasterTransparency.TransparentSingleValuePixel()
            pixel.min = class_min
            # We want it just a little bit smaller than max
            # so that ranges are discrete
            pixel.max = class_max
            # noinspection PyPep8Naming
            pixel.percentTransparent = transparency_percent
            transparency_list.append(pixel)

    band = 1  # gdal counts bands from base 1
    LOGGER.debug('Setting colour ramp list')
    raster_shader = QgsRasterShader()
    color_ramp_shader = QgsColorRampShader()
    color_ramp_shader.setColorRampType(QgsColorRampShader.INTERPOLATED)
    color_ramp_shader.setColorRampItemList(ramp_item_list)
    LOGGER.debug('Setting shader function')
    raster_shader.setRasterShaderFunction(color_ramp_shader)
    LOGGER.debug('Setting up renderer')
    renderer = QgsSingleBandPseudoColorRenderer(
        raster_layer.dataProvider(),
        band,
        raster_shader)
    LOGGER.debug('Assigning renderer to raster layer')
    raster_layer.setRenderer(renderer)

    LOGGER.debug('Setting raster transparency list')

    renderer = raster_layer.renderer()
    transparency = QgsRasterTransparency()
    transparency.setTransparentSingleValuePixelList(transparency_list)
    renderer.setRasterTransparency(transparency)
    # For interest you can also view the list like this:
    # pix = t.transparentSingleValuePixelList()
    # for px in pix:
    #    print 'Min: %s Max %s Percent %s' % (
    #       px.min, px.max, px.percentTransparent)

    LOGGER.debug('Saving style as default')
    raster_layer.saveDefaultStyle()
    LOGGER.debug('Setting raster style done!')
    return ramp_item_list, transparency_list
Beispiel #13
0
def _setNewRasterStyle(theQgsRasterLayer, theStyle):
    """Set QGIS raster style based on InaSAFE style dictionary for QGIS >= 2.0.

    This function will set both the colour map and the transparency
    for the passed in layer.

    Args:
        * theQgsRasterLayer: QgsRasterLayer
        * style: Dictionary of the form as in the example below.

    Returns:
        * list: RangeList
        * list: TransparencyList

    Example:
        style_classes = [dict(colour='#38A800', quantity=2, transparency=0),
                         dict(colour='#38A800', quantity=5, transparency=50),
                         dict(colour='#79C900', quantity=10, transparency=50),
                         dict(colour='#CEED00', quantity=20, transparency=50),
                         dict(colour='#FFCC00', quantity=50, transparency=34),
                         dict(colour='#FF6600', quantity=100, transparency=77),
                         dict(colour='#FF0000', quantity=200, transparency=24),
                         dict(colour='#7A0000', quantity=300, transparency=22)]

    """
    # Note imports here to prevent importing on unsupported QGIS versions
    # pylint: disable=E0611
    # pylint: disable=W0621
    # pylint: disable=W0404
    from qgis.core import (QgsRasterShader,
                           QgsColorRampShader,
                           QgsSingleBandPseudoColorRenderer,
                           QgsRasterTransparency)
    # pylint: enable=E0611
    # pylint: enable=W0621
    # pylint: enable=W0404

    myClasses = theStyle['style_classes']
    myRampItemList = []
    myTransparencyList = []
    myLastValue = 0
    for myClass in myClasses:
        LOGGER.debug('Evaluating class:\n%s\n' % myClass)
        myMax = myClass['quantity']

        if math.isnan(myMax):
            LOGGER.debug('Skipping class.')
            continue

        myColour = QtGui.QColor(myClass['colour'])
        myLabel = QtCore.QString()
        if 'label' in myClass:
            myLabel = QtCore.QString(myClass['label'])
        myRampItem = QgsColorRampShader.ColorRampItem(myMax, myColour, myLabel)
        myRampItemList.append(myRampItem)
        # Create opacity entries for this range
        myTransparencyPercent = 0
        if 'transparency' in myClass:
            myTransparencyPercent = int(myClass['transparency'])
        if myTransparencyPercent > 0:
            # Check if range extrema are integers so we know if we can
            # use them to calculate a value range
            myPixel = QgsRasterTransparency.TransparentSingleValuePixel()
            myPixel.min = myLastValue
            myPixel.max = myMax
            myPixel.percentTransparent = myTransparencyPercent
            myTransparencyList.append(myPixel)
            myLastValue = myMax

    myBand = 1  # gdal counts bands from base 1
    LOGGER.debug('Setting colour ramp list')
    myRasterShader = QgsRasterShader()
    myColorRampShader = QgsColorRampShader()
    myColorRampShader.setColorRampType(QgsColorRampShader.INTERPOLATED)
    myColorRampShader.setColorRampItemList(myRampItemList)
    LOGGER.debug('Setting shader function')
    myRasterShader.setRasterShaderFunction(myColorRampShader)
    LOGGER.debug('Setting up renderer')
    myRenderer = QgsSingleBandPseudoColorRenderer(
        theQgsRasterLayer.dataProvider(),
        myBand,
        myRasterShader)
    LOGGER.debug('Assigning renderer to raster layer')
    theQgsRasterLayer.setRenderer(myRenderer)
    LOGGER.debug('Setting raster transparency list')
    #if len(myTransparencyList) > 0:
    #    myRasterTransparency = QgsRasterTransparency()
    #    myRasterTransparency.setTransparentSingleValuePixelList(
    #        myTransparencyList)
    #    myRenderer.setRasterTransparency(myRasterTransparency)
    LOGGER.debug('Saving style as default')
    theQgsRasterLayer.saveDefaultStyle()
    LOGGER.debug('Setting raster style done!')
    return myRampItemList, myTransparencyList
Beispiel #14
0
def _setNewRasterStyle(theQgsRasterLayer, theClasses):
    """Set QGIS raster style based on InaSAFE style dictionary for QGIS >= 2.0.

    This function will set both the colour map and the transparency
    for the passed in layer.

    Args:
        * theQgsRasterLayer: QgsRasterLayer
        * theClasses: List of the form as in the example below.

    Returns:
        * list: RangeList
        * list: TransparencyList

    Example:
        style_classes = [dict(colour='#38A800', quantity=2, transparency=0),
                         dict(colour='#38A800', quantity=5, transparency=50),
                         dict(colour='#79C900', quantity=10, transparency=50),
                         dict(colour='#CEED00', quantity=20, transparency=50),
                         dict(colour='#FFCC00', quantity=50, transparency=34),
                         dict(colour='#FF6600', quantity=100, transparency=77),
                         dict(colour='#FF0000', quantity=200, transparency=24),
                         dict(colour='#7A0000', quantity=300, transparency=22)]

    """
    # Note imports here to prevent importing on unsupported QGIS versions
    # pylint: disable=E0611
    # pylint: disable=W0621
    # pylint: disable=W0404
    from qgis.core import (QgsRasterShader,
                           QgsColorRampShader,
                           QgsSingleBandPseudoColorRenderer,
                           QgsRasterTransparency)
    # pylint: enable=E0611
    # pylint: enable=W0621
    # pylint: enable=W0404

    myRampItemList = []
    myTransparencyList = []
    LOGGER.debug(theClasses)
    for myClass in theClasses:

        LOGGER.debug('Evaluating class:\n%s\n' % myClass)

        if 'quantity' not in myClass:
            LOGGER.exception('Class has no quantity attribute')
            continue

        myMax = myClass['max']
        if math.isnan(myMax):
            LOGGER.debug('Skipping class - max is nan.')
            continue

        myMin = myClass['min']
        if math.isnan(myMin):
            LOGGER.debug('Skipping class - min is nan.')
            continue

        myColour = QtGui.QColor(myClass['colour'])
        myLabel = QtCore.QString()
        if 'label' in myClass:
            myLabel = QtCore.QString(myClass['label'])
        myRampItem = QgsColorRampShader.ColorRampItem(myMax, myColour, myLabel)
        myRampItemList.append(myRampItem)

        # Create opacity entries for this range
        myTransparencyPercent = 0
        if 'transparency' in myClass:
            myTransparencyPercent = int(myClass['transparency'])
        if myTransparencyPercent > 0:
            # Check if range extrema are integers so we know if we can
            # use them to calculate a value range
            myPixel = QgsRasterTransparency.TransparentSingleValuePixel()
            myPixel.min = myMin
            # We want it just a leeetle bit smaller than max
            # so that ranges are discrete
            myPixel.max = myMax
            myPixel.percentTransparent = myTransparencyPercent
            myTransparencyList.append(myPixel)

    myBand = 1  # gdal counts bands from base 1
    LOGGER.debug('Setting colour ramp list')
    myRasterShader = QgsRasterShader()
    myColorRampShader = QgsColorRampShader()
    myColorRampShader.setColorRampType(QgsColorRampShader.INTERPOLATED)
    myColorRampShader.setColorRampItemList(myRampItemList)
    LOGGER.debug('Setting shader function')
    myRasterShader.setRasterShaderFunction(myColorRampShader)
    LOGGER.debug('Setting up renderer')
    myRenderer = QgsSingleBandPseudoColorRenderer(
        theQgsRasterLayer.dataProvider(),
        myBand,
        myRasterShader)
    LOGGER.debug('Assigning renderer to raster layer')
    theQgsRasterLayer.setRenderer(myRenderer)

    LOGGER.debug('Setting raster transparency list')

    myRenderer = theQgsRasterLayer.renderer()
    myTransparency = QgsRasterTransparency()
    myTransparency.setTransparentSingleValuePixelList(myTransparencyList)
    myRenderer.setRasterTransparency(myTransparency)
    # For interest you can also view the list like this:
    #pix = t.transparentSingleValuePixelList()
    #for px in pix:
    #    print 'Min: %s Max %s Percent %s' % (
    #       px.min, px.max, px.percentTransparent)

    LOGGER.debug('Saving style as default')
    theQgsRasterLayer.saveDefaultStyle()
    LOGGER.debug('Setting raster style done!')
    return myRampItemList, myTransparencyList
def idw_interpolation(layer, parent_dialog):
    """Run interpolation using inverse distance weight algorithm

    :param layer: Vector layer with drivetimes
    :type layer: QgsVectorLayer

    :param parent_dialog: A dialog that called this function.
    :type parent_dialog: QProgressDialog

    :returns raster_layer: Interpolated raster layer with drivetimes
    :rtype raster_layer: QgsRasterLayer

    """
    raster_layer = None
    try:
        Processing.initialize()
        Processing.updateAlgsList()

        output_raster = processing.runalg(
        'gdalogr:gridinvdist',
        layer,
        'minutes',
        2, 0, 0, 0, 0, 0, 0, 0, 5,
        "[temporary file]")

        output_file = output_raster['OUTPUT']
        file_info = QFileInfo(output_file)
        base_name = file_info.baseName()

        # retrieving the raster output , styling it and load it in Qgis

        raster_layer = QgsRasterLayer(output_file, base_name)

    except Exception as exception:  # pylint: disable=broad-except
            # noinspection PyCallByClass,PyTypeChecker,PyArgumentList
        if parent_dialog:
                display_warning_message_box(
                    parent_dialog,
                    parent_dialog.tr(
                        'Error'),
                    parent_dialog.tr('Error loading isochrone map,'
                                     'please check if you have processing '
                                     'plugin installed '))
        else:
            display_warning_message_box(
                parent_dialog,
                'Error',
                'Error loading isochrone map,'
                'please check if you have processing '
                'plugin installed ')

    if raster_layer:
        if raster_layer.isValid():
            color_shader = QgsColorRampShader()
            color_shader.setColorRampType(QgsColorRampShader.INTERPOLATED)
            colors = {
                'deep_green': '#1a9641',
                'light_green': '#a6d96a',
                'pale_yellow': '#ffffc0',
                'light_red': '#fdae61',
                'red': '#d7191c'
            }
            provider = raster_layer.dataProvider()
            stats = provider.bandStatistics(
                1,
                QgsRasterBandStats.All,
                raster_layer.extent(),
                0)

            values = {}

            if stats:
                min = stats.minimumValue
                max = stats.maximumValue
                stat_range = max - min
                add = stat_range / 4
                values[0] = min
                value = min
                for index in range(1, 4):
                    value += add
                    values[index] = value
                values[4] = max
            else:
                display_warning_message_box(
                    parent_dialog,
                    parent_dialog.tr(
                        'Error'),
                    parent_dialog.tr('Error loading isochrone map'
                                     ' Problem indexing the isochrones map'))

            color_list = [
                QgsColorRampShader.ColorRampItem(
                    values[0],
                    QColor(colors['deep_green'])),
                QgsColorRampShader.ColorRampItem(
                    values[1],
                    QColor(colors['light_green'])),
                QgsColorRampShader.ColorRampItem(
                    values[2],
                    QColor(colors['pale_yellow'])),
                QgsColorRampShader.ColorRampItem(
                    values[3],
                    QColor(colors['light_red'])),
                QgsColorRampShader.ColorRampItem(
                    values[4],
                    QColor(colors['red']))
            ]

            color_shader.setColorRampItemList(color_list)
            raster_shader = QgsRasterShader()
            raster_shader.setRasterShaderFunction(color_shader)

            renderer = QgsSingleBandPseudoColorRenderer(
                raster_layer.dataProvider(),
                1,
                raster_shader)
            raster_layer.setRenderer(renderer)

        else:
            if parent_dialog:
                display_warning_message_box(
                    parent_dialog,
                    parent_dialog.tr(
                        'Problem'),
                    parent_dialog.tr('Problem styling the isochrone map'))
            else:
                display_warning_message_box(
                    parent_dialog,
                    'Problem',
                    'Problem styling the isochrone map')

        QgsMapLayerRegistry.instance().addMapLayers([raster_layer])

    else:
        if parent_dialog:

            display_warning_message_box(
                parent_dialog,
                parent_dialog.tr(
                    'Error'),
                parent_dialog.tr('Error loading isochrone map '
                                 'Could not load interpolated file!'))
        else:
            display_warning_message_box(
                parent_dialog,
                'Error',
                'Error loading isochrone map '
                'Could not load interpolated file!')

    return raster_layer
class RasterSymbolizer(QgsRasterLayer):

    def __init__(self, layer):
        self.colDic = {'tan':'#ffebb0', 'green':'#267300', 'brown':'#734d00', 'white':'#ffffff',
                                'red':'#e60000', 'light gray':'#f0f0f0', 'blue':'#004cab'}
        self.shader = QgsRasterShader()
        self.ramp = QgsColorRampShader()
        self.colLst = []
        self.valLst = []
        self.labLst = []
        self.opacity = 1.0

        self.layer = layer
        self.provider = layer.dataProvider()
        extent = layer.extent()
        self.ver = self.provider.hasStatistics(1, QgsRasterBandStats.All)
        self.stats = self.provider.bandStatistics(1, QgsRasterBandStats.All, extent, 0)

    def render_GCD(self, type):

        self.setRendererOptions(type)

        self.shader.setRasterShaderFunction(self.ramp)
        renderer = QgsSingleBandPseudoColorRenderer(self.layer.dataProvider(), 1, self.shader)

        self.layer.setRenderer(renderer)
        self.layer.renderer().setOpacity(self.opacity)
        self.layer.triggerRepaint()

    def setRendererOptions(self, type):

        if type == "DEM":
            self.setValueBreaks_DEM()
            self.setColorRamp_DEM()

        elif type == "DoD":
            self.setValueBreaks_DoD()
            self.setColorRamp_DoD()

        elif type == "Slope_deg":
            self.setValueBreaks_SlopeDeg()
            self.setColorRamp_Slope()

        elif type == "Slope_per":
            self.setValueBreaks_SlopePer()
            self.setColorRamp_Slope()

        elif type == "Roughness":
            self.setValueBreaks_Roughness()
            self.setColorRamp_Roughness()

    def setValueBreaks_DEM(self):
        lo = self.stats.minimumValue
        hi = self.stats.maximumValue
        rng = hi - lo
        interval = rng/3.0
        self.valLst = [lo, lo+interval, hi-interval, hi]

    def setValueBreaks_DoD(self):
        nClasses = 20
        lo = self.stats.minimumValue
        hi = self.stats.maximumValue
        mid = 0.0

        if abs(lo) > abs(hi):
            hi = abs(lo)

        else:
            lo = hi*-1.0

        rng = hi*2.0
        interval = rng/(nClasses*1.0)

        nRound = self.magnitude(rng)

        if nRound < 0:
            nRound = abs(nRound) + 2

        else:
            nRound = 2

        self.valLst.append(lo)

        for i in range(1,nClasses+1,1):
            self.valLst.append(lo + i*interval)
            self.labLst.append(str(round(self.valLst[i-1], nRound))+" to "+str(round(self.valLst[i], nRound)))

    def setValueBreaks_SlopeDeg(self):

        self.valLst.append(self.stats.minimumValue)
        self.valLst.append(2.0)
        self.valLst.append(5.0)
        self.valLst.append(10.0)
        self.valLst.append(15.0)
        self.valLst.append(25.0)
        self.valLst.append(35.0)
        self.valLst.append(45.0)
        self.valLst.append(60.0)
        self.valLst.append(80.0)

        self.labLst.append("0 to 2")
        self.labLst.append("2 to 5")
        self.labLst.append("5 to 10")
        self.labLst.append("10 to 15")
        self.labLst.append("15 to 25")
        self.labLst.append("25 to 35")
        self.labLst.append("35 to 45")
        self.labLst.append("45 to 60")
        self.labLst.append("60 to 80")
        self.labLst.append("80 to 90")

    def setValueBreaks_SlopePer(self):
        self.valLst.append(0.0)
        self.valLst.append(3.5)
        self.valLst.append(8.75)
        self.valLst.append(15.0)
        self.valLst.append(25.0)
        self.valLst.append(45.0)
        self.valLst.append(70.0)
        self.valLst.append(100.0)
        self.valLst.append(175.0)
        self.valLst.append(565.0)

        self.labLst.append("0 to 3.5%")
        self.labLst.append("3.5% to 8.75%")
        self.labLst.append("8.75% to 15%")
        self.labLst.append("15% to 25%")
        self.labLst.append("25% to 45%")
        self.labLst.append("45% to 70%")
        self.labLst.append("70% to 100%")
        self.labLst.append("100% to 175%")
        self.labLst.append("175% to 565%")
        self.labLst.append("> 565%")

    def setValueBreaks_Roughness(self):
        self.valLst.append(0)
        self.valLst.append(2)
        self.valLst.append(16)
        self.valLst.append(64)
        self.valLst.append(256)

        self.labLst.append("Fines, Sand (0 to 2 mm)")
        self.labLst.append("Fine Gravel (2 mm to 16 mm)")
        self.labLst.append("Coarse Gravel (16 mm to 64 mm)")
        self.labLst.append("Cobbles (64 mm to 256 mm)")
        self.labLst.append("Boulders (> 256 mm)")

    def setColorRamp_DEM(self):

        self.colLst = [QgsColorRampShader.ColorRampItem(self.valLst[0], QColor(self.colDic['tan']), str(self.valLst[0])),
                           QgsColorRampShader.ColorRampItem(self.valLst[1], QColor(self.colDic['green']), str(self.valLst[1])),
                           QgsColorRampShader.ColorRampItem(self.valLst[2], QColor(self.colDic['brown']), str(self.valLst[2])),
                           QgsColorRampShader.ColorRampItem(self.valLst[3], QColor(self.colDic['white']), str(self.valLst[3]))]

        self.ramp.setColorRampItemList(self.colLst)
        self.ramp.setColorRampType(QgsColorRampShader.INTERPOLATED)
        self.opacity = 0.6

    def setColorRamp_DoD(self):

        self.colLst = [QgsColorRampShader.ColorRampItem(self.valLst[0], QColor(230,0,0), self.labLst[0]),
                       QgsColorRampShader.ColorRampItem(self.valLst[1], QColor(235,45,23), self.labLst[1]),
                       QgsColorRampShader.ColorRampItem(self.valLst[2], QColor(240,67,41), self.labLst[2]),
                       QgsColorRampShader.ColorRampItem(self.valLst[3], QColor(242,88,61), self.labLst[3]),
                       QgsColorRampShader.ColorRampItem(self.valLst[4], QColor(245,108,81), self.labLst[4]),
                       QgsColorRampShader.ColorRampItem(self.valLst[5], QColor(245,131,105), self.labLst[5]),
                       QgsColorRampShader.ColorRampItem(self.valLst[6], QColor(245,151,130), self.labLst[6]),
                       QgsColorRampShader.ColorRampItem(self.valLst[7], QColor(242,171,155), self.labLst[7]),
                       QgsColorRampShader.ColorRampItem(self.valLst[8], QColor(237,190,180), self.labLst[8]),
                       QgsColorRampShader.ColorRampItem(self.valLst[9], QColor(230,208,207), self.labLst[9]),
                       QgsColorRampShader.ColorRampItem(self.valLst[10], QColor(218,218,224), self.labLst[10]),
                       QgsColorRampShader.ColorRampItem(self.valLst[11], QColor(197,201,219), self.labLst[11]),
                       QgsColorRampShader.ColorRampItem(self.valLst[12], QColor(176,183,214), self.labLst[12]),
                       QgsColorRampShader.ColorRampItem(self.valLst[13], QColor(155,166,207), self.labLst[13]),
                       QgsColorRampShader.ColorRampItem(self.valLst[14], QColor(135,150,201), self.labLst[14]),
                       QgsColorRampShader.ColorRampItem(self.valLst[15], QColor(110,131,194), self.labLst[15]),
                       QgsColorRampShader.ColorRampItem(self.valLst[16], QColor(92,118,189), self.labLst[16]),
                       QgsColorRampShader.ColorRampItem(self.valLst[17], QColor(72,105,184), self.labLst[17]),
                       QgsColorRampShader.ColorRampItem(self.valLst[18], QColor(49,91,176), self.labLst[18]),
                       QgsColorRampShader.ColorRampItem(self.valLst[19], QColor(2,7,168), self.labLst[19])]

        self.ramp.setColorRampItemList(self.colLst)
        self.ramp.setColorRampType(QgsColorRampShader.DISCRETE)

    def setColorRamp_Slope(self):
        self.colLst = [QgsColorRampShader.ColorRampItem(self.valLst[0], QColor(255,235,176), self.labLst[0]),
                       QgsColorRampShader.ColorRampItem(self.valLst[1], QColor(255,219,135), self.labLst[1]),
                       QgsColorRampShader.ColorRampItem(self.valLst[2], QColor(255,202,97), self.labLst[2]),
                       QgsColorRampShader.ColorRampItem(self.valLst[3], QColor(255,186,59), self.labLst[3]),
                       QgsColorRampShader.ColorRampItem(self.valLst[4], QColor(255,170,0), self.labLst[4]),
                       QgsColorRampShader.ColorRampItem(self.valLst[5], QColor(255,128,0), self.labLst[5]),
                       QgsColorRampShader.ColorRampItem(self.valLst[6], QColor(255,85,0), self.labLst[6]),
                       QgsColorRampShader.ColorRampItem(self.valLst[7], QColor(255,42,0), self.labLst[7]),
                       QgsColorRampShader.ColorRampItem(self.valLst[8], QColor(161,120,120), self.labLst[8]),
                       QgsColorRampShader.ColorRampItem(self.valLst[9], QColor(130,10,130), self.labLst[9])]

        self.ramp.setColorRampItemList(self.colLst)
        self.ramp.setColorRampType(QgsColorRampShader.DISCRETE)

    def setColorRamp_Roughness(self):
        self.colLst = [QgsColorRampShader.ColorRampItem(self.valLst[0], QColor(194,82,60), self.labLst[0]),
                       QgsColorRampShader.ColorRampItem(self.valLst[1], QColor(240,180,17), self.labLst[1]),
                       QgsColorRampShader.ColorRampItem(self.valLst[2], QColor(123,237,0), self.labLst[2]),
                       QgsColorRampShader.ColorRampItem(self.valLst[3], QColor(27,168,124), self.labLst[3]),
                       QgsColorRampShader.ColorRampItem(self.valLst[4], QColor(11,44,122), self.labLst[4])]

    def magnitude(self, x):
        return int(math.floor(math.log10(x)))
Beispiel #17
0
def create_raster_layer(matrix):
    driver = gdal.GetDriverByName("GTiff")

    filename = tempfile.mktemp(prefix="hmtk", suffix=".tif")

    # sort the data by lon, lat
    gridded_data = numpy.array(
        sorted(matrix, key=lambda row: (90 + row[1]) * 180 + (180 + row[0])))

    # extract it into separate vars
    lons, lats, vals = (
        gridded_data[:, 0], gridded_data[:, 1], gridded_data[:, 3])

    ncols = lons[lons == lons[0]].size
    nrows = lats[lats == lats[0]].size

    # put values in a grid
    gridded_vals = vals.reshape((ncols, nrows)).T

    dataset = driver.Create(filename, ncols, nrows, 1, gdal.GDT_Float32)

    dataset.SetGeoTransform((
        min(lons),
        (max(lons) - min(lons)) / ncols,
        0,
        max(lats),
        0,
        -(max(lats) - min(lats)) / nrows))

    out_srs = osr.SpatialReference()
    out_srs.ImportFromEPSG(4326)
    dataset.SetProjection(out_srs.ExportToWkt())

    out_band = dataset.GetRasterBand(1)
    out_band.WriteArray(gridded_vals)
    out_band.SetNoDataValue(0)
    out_band.FlushCache()
    out_band = None
    dataset = None

    fileInfo = QFileInfo(filename)
    baseName = fileInfo.baseName()
    layer = QgsRasterLayer(filename, baseName)

    stat = layer.dataProvider().bandStatistics(1)

    minVal = stat.minimumValue
    maxVal = stat.maximumValue
    entries_nr = 20

    colorRamp = QgsStyleV2().defaultStyle().colorRamp("Spectral")
    currentValue = float(minVal)
    intervalDiff = float(maxVal - minVal) / float(entries_nr - 1)

    colorRampItems = []
    for i in reversed(xrange(entries_nr)):
        item = QgsColorRampShader.ColorRampItem()
        item.value = currentValue
        item.label = unicode(currentValue)
        currentValue += intervalDiff
        item.color = colorRamp.color(float(i) / float(entries_nr))
        item.color.setAlphaF(0.75)
        colorRampItems.append(item)

    rasterShader = QgsRasterShader()
    colorRampShader = QgsColorRampShader()

    colorRampShader.setColorRampItemList(colorRampItems)
    colorRampShader.setColorRampType(QgsColorRampShader.INTERPOLATED)
    rasterShader.setRasterShaderFunction(colorRampShader)

    layer.setDrawingStyle('SingleBandPseudoColor')
    layer.renderer().setShader(rasterShader)

    QgsMapLayerRegistry.instance().addMapLayer(layer)

    return layer