Ejemplo n.º 1
0
 def refresh_layer_list(self):
     from mole import extensions
     """
     Update the color-pickers layer-dropdown with a list of the currently visible .tif-files
     :return:
     :rtype:
     """
     legend.nodeExitSolo()
     dropdown = self.layers_dropdown
     dropdown.clear()
     raster_list = layer_interaction.get_raster_layer_list(iface, visibility='visible')
     layer = None
     for layer in raster_list:
         source = layer.publicSource()
         dropdown.addItem(layer.name())
         self.color_entry_manager.add_layer(layer.name())
         ext = extensions.by_layername(layer.name())
         if ext == []:
             ltu_file = os.path.dirname(layer.publicSource())
             ltu_file = os.path.join(ltu_file, layer.name() + '.qml')
         else:
             ext = ext[0]
             ltu_file = ext.colortable
             #print ext.colortable
         #print ltu_file
         if ltu_file != None:
             if os.path.isfile(os.path.join(ltu_file)):
                 self.color_entry_manager.read_color_map_from_qml(os.path.join(ltu_file))
     oeq_global.QeQ_current_work_layer = layer_interaction.find_layer_by_name(self.layers_dropdown.currentText())
     if oeq_global.QeQ_current_work_layer != None:
         #print config.open_layers_layer_name
         legend.nodeInitSolo([config.investigation_shape_layer_name, config.building_outline_layer_name, oeq_global.QeQ_current_work_layer.name(), config.open_layers_layer_name])
Ejemplo n.º 2
0
def load(self=None):
    from mole.extensions import by_layername
    if bool(
            by_layername(
                config.building_outline_layer_name)[0].createDatabase()):
        return True
    return False
Ejemplo n.º 3
0
    def save_color_map(self):
        """
        Save the currently open color-map as a qml-file into the project folder.
        :return:
        :rtype:
        """
        from mole import extensions

        layer = iface.activeLayer()
        selected_layer = self.layers_dropdown.currentText()
        if layer.name() != selected_layer:
            layer = layer_interaction.find_layer_by_name(selected_layer)

        out_path = os.path.dirname(layer.publicSource())
        out_path = os.path.join(out_path, layer.name() + '.qml')
        self.update_color_values()
        entry_written = self.color_entry_manager.write_color_map_as_qml(
            layer.name(), out_path)
        if entry_written:
            self.message_label.setStyleSheet(_fromUtf8("color: green;"))
            self.message_label.setText(
                'Success - Legend was successfully written to \n\t"{}".'.
                format(out_path))
        else:
            self.message_label.setStyleSheet(_fromUtf8("color: red;"))
            self.message_label.setText(
                'Failure - Could not write legend to to \n\t"{}".'.format(
                    out_path))
        activeextensions = extensions.by_layername(layer.name())
        try:
            activeextensions[0].colortable = out_path
        except:
            pass
Ejemplo n.º 4
0
    def save_color_map(self):
        """
        Save the currently open color-map as a qml-file into the project folder.
        :return:
        :rtype:
        """
        from mole import extensions

        layer = iface.activeLayer()
        selected_layer = self.layers_dropdown.currentText()
        if layer.name() != selected_layer:
            layer = layer_interaction.find_layer_by_name(selected_layer)

        out_path = os.path.dirname(layer.publicSource())
        out_path = os.path.join(out_path, layer.name() + '.qml')
        self.update_color_values()
        entry_written = self.color_entry_manager.write_color_map_as_qml(layer.name(), out_path)
        if entry_written:
            self.message_label.setStyleSheet(_fromUtf8("color: green;"))
            self.message_label.setText('Success - Legend was successfully written to \n\t"{}".'.format(out_path))
        else:
            self.message_label.setStyleSheet(_fromUtf8("color: red;"))
            self.message_label.setText('Failure - Could not write legend to to \n\t"{}".'.format(out_path))
        activeextensions = extensions.by_layername(layer.name())
        try:
            activeextensions[0].colortable = out_path
        except:
            pass
Ejemplo n.º 5
0
    def add_color(self, color):
        """
        Insert a new color (and the values associated to it, if any), into the color-table.
        :param color: The color in RGBa
        :type color: QColor
        :return:
        :rtype:
        """
        from mole import extensions

        layer = self.layers_dropdown.currentText()
        self.recent_layer = layer
        color_map = self.color_entry_manager.layer_values_map[layer]
        model = QColorTableModel(color_map, self.header, self)
        self.color_table_view.setModel(model)

        color_key = 'RGBa({}, {}, {}, {})'.format(color.red(), color.green(), color.blue(), color.alpha())
        if color_map.has_key(color_key):
            self.message_label.setStyleSheet(_fromUtf8("color: red;"))
            self.message_label.setText('Attention: Color {} is defined already.'.format(color_key))

        else:
            self.message_label.clear()
            #ToDo change to use the correct para-name instead
            #parameter_name = str(self.layers_dropdown.currentText())[:10]
            parameter_name = extensions.by_layername(layer)
            if not parameter_name: return None
            parameter_name = parameter_name[0].field_id
            self.color_entry_manager.add_color_value_quadruple_to_layer([color_key, parameter_name, 0, 0], layer)
            color_map = self.color_entry_manager.layer_values_map[layer]
            model = QColorTableModel(color_map, self.header, self)
            self.color_table_view.setModel(model)
        self.raise_()
Ejemplo n.º 6
0
 def add_layer(self, layer_name):
     from mole import extensions
     if not self.layer_values_map.has_key(layer_name):
         self.layer_values_map[layer_name] = OrderedDict()
     ext = extensions.by_layername(layer_name)
     if ext != []:
         if ext[0].colortable != None:
             self.read_color_map_from_qml(ext[0].colortable)
Ejemplo n.º 7
0
def add_parameter_info_to_layer(color_dict, field_name, layer):
    """
    Adds the color-legend to the given layers corresponding field
    :param color_dict: Dictionary containing the color-value map
    :type color_dict: dict
    :param field_name: The fields name-prefix to which the information belongs
    :type field_name: str
    :param layer: The layer which holds the fields
    :type layer: QgsVectorLayer
    :return:
    :rtype:
    """

    import mole.extensions as extensions
    extension = extensions.by_layername(layer.name(), 'Import')
    if extension != []:
        extension = extension[0]
        try:
            provider = layer.dataProvider()
        except AttributeError, NoneTypeError:
            print(__name__, NoneTypeError)
            return

        for color_key in color_dict.keys():
            color_quadriple = color_key[5:-1].split(',')
            color_quadriple = map(int, color_quadriple)

            for feat in provider.getFeatures():
                if colors_match_feature(color_quadriple, feat, field_name):
                    result = {extension.field_id + '_P': {'type': QVariant.String,
                                                          'value': color_dict[color_key][0]},
                               extension.par_in[0]: {'type': QVariant.Double,
                                                    'value': color_dict[color_key][1]},
                               extension.par_in[1]: {'type': QVariant.Double,
                                                    'value': color_dict[color_key][2]}}

                    result.update(extension.evaluate({extension.par_in[0]: color_dict[color_key][1],
                                                      extension.par_in[1]: color_dict[color_key][2]}))
                    attributes = []
                    attributevalues = {}
                    for i in result.keys():
                        attributes.append(QgsField(i, result[i]['type']))
                        attributevalues.update(provider.fieldNameIndex(i), result[i]['value'])

                    add_attributes_if_not_exists(layer, attributes)
                    provider.changeAttributeValues({feat.id(): attributevalues})
Ejemplo n.º 8
0
 def refresh_layer_list(self):
     from mole import extensions
     """
     Update the color-pickers layer-dropdown with a list of the currently visible .tif-files
     :return:
     :rtype:
     """
     legend.nodeExitSolo()
     dropdown = self.layers_dropdown
     dropdown.clear()
     raster_list = layer_interaction.get_raster_layer_list(
         iface, visibility='visible')
     layer = None
     for layer in raster_list:
         source = layer.publicSource()
         dropdown.addItem(layer.name())
         self.color_entry_manager.add_layer(layer.name())
         ext = extensions.by_layername(layer.name())
         if ext == []:
             ltu_file = os.path.dirname(layer.publicSource())
             ltu_file = os.path.join(ltu_file, layer.name() + '.qml')
         else:
             ext = ext[0]
             ltu_file = ext.colortable
             #print ext.colortable
         #print ltu_file
         if ltu_file != None:
             if os.path.isfile(os.path.join(ltu_file)):
                 self.color_entry_manager.read_color_map_from_qml(
                     os.path.join(ltu_file))
     oeq_global.QeQ_current_work_layer = layer_interaction.find_layer_by_name(
         self.layers_dropdown.currentText())
     if oeq_global.QeQ_current_work_layer != None:
         #print config.open_layers_layer_name
         legend.nodeInitSolo([
             config.investigation_shape_layer_name,
             config.building_outline_layer_name,
             oeq_global.QeQ_current_work_layer.name(),
             config.open_layers_layer_name
         ])
Ejemplo n.º 9
0
    def add_color(self, color):
        """
        Insert a new color (and the values associated to it, if any), into the color-table.
        :param color: The color in RGBa
        :type color: QColor
        :return:
        :rtype:
        """
        from mole import extensions

        layer = self.layers_dropdown.currentText()
        self.recent_layer = layer
        color_map = self.color_entry_manager.layer_values_map[layer]
        model = QColorTableModel(color_map, self.header, self)
        self.color_table_view.setModel(model)

        color_key = 'RGBa({}, {}, {}, {})'.format(color.red(), color.green(),
                                                  color.blue(), color.alpha())
        if color_map.has_key(color_key):
            self.message_label.setStyleSheet(_fromUtf8("color: red;"))
            self.message_label.setText(
                'Attention: Color {} is defined already.'.format(color_key))

        else:
            self.message_label.clear()
            #ToDo change to use the correct para-name instead
            #parameter_name = str(self.layers_dropdown.currentText())[:10]
            parameter_name = extensions.by_layername(layer)
            if not parameter_name: return None
            parameter_name = parameter_name[0].field_id
            self.color_entry_manager.add_color_value_quadruple_to_layer(
                [color_key, parameter_name, 0, 0], layer)
            color_map = self.color_entry_manager.layer_values_map[layer]
            model = QColorTableModel(color_map, self.header, self)
            self.color_table_view.setModel(model)
        self.raise_()
Ejemplo n.º 10
0
    def select_and_rename_files_for_sampling(self,sample_fields):
        """
        Select all available layers for the point sampling and rename multiple occurrences of the same name.
        Prepend an index, to separate the layers and append the information, which color value is displayed.
        :return plugin: Return the plugin if it was found or None otherwise
        :rtype: plugin instance
        """
        import mole.extensions as extensions

        sample_list = self.pst_dialog.inData
        table = self.pst_dialog.fieldsTable
        number_of_samples = len(sample_list)

        RGBa_appendices = ['R', 'G', 'B', 'a']
        RGBa_index = 0
        last_name = ''
        prefix = 0

        replacement_map = {}

        for i in range(number_of_samples):
            # select all fields via the inData-view,
            # so the point sampling tool can manage its model accordingly/appropriately
            sample_list.setItemSelected(sample_list.item(i), True)

            # Get the source-name (as displayed in the field-table) and check if it was used already
            # (the name has to be split, since it is displayed in the form 'layer_name : Band x' to get the layer_name)
            table_index = table.rowCount()-1
            table_text = table.item(table_index, 0).text().split(' : ')
            layer_name = table_text[0]
            band_name = table_text[1]
            layer = find_layer_by_name(layer_name)
            ext=extensions.by_layername(layer_name, 'Import')
            #if ext:
            #    print "Test: "+ext[0].layer_name
            # Check if the layer was already used
            if last_name != layer_name:
                last_name = layer_name
                prefix += 1
                RGBa_index = 0

            if (layer.name() == config.building_outline_layer_name and
                    (band_name.startswith('AREA') or band_name.startswith('PERIMETER') or band_name.startswith(config.building_id_key))):
                continue
            elif (layer.type() == QgsMapLayer.RasterLayer and
                  layer.rasterType() == QgsRasterLayer.Multiband and
                  layer.bandCount() == 4
                  ):
                # Truncate the name to a maximum of 6 characters, since QGIS limits the length of a feature's name to 10
                # prepend prefix (with leading zero), truncated name and RGBa-appendix
                try:
                    rgba = RGBa_appendices[RGBa_index]
                    RGBa_index += 1
                except IndexError as IError:
                    RGBa_index = 0
                    print(self.__module__, 'IndexError when appending the RGBa-Appendix: {}'.format(IError))
                if ext:
                    export_name = ext[0].field_id + '_' + rgba
                else:
                    export_name = '{:02d}{}_{}'.format(prefix, layer_name[0:6], rgba)


                replacement_map[layer_name] = export_name[:-2]
                # Change the text in the table, so the pst can manage its model accordingly/appropriately
                table.item(table_index, 1).setText(export_name)
                continue
            elif ext:
                # NEW fieldname ist nicht klar
                if ext[0].field_rename is not None:
                    if band_name.startswith(tuple(ext[0].field_rename.keys())):
                        if ext[0].field_rename[band_name]:
                            table.item(table_index, 1).setText(ext[0].field_rename[band_name])
                            continue
                    elif band_name.startswith(tuple(ext[0].par_in)):
                        continue
            sample_list.setItemSelected(sample_list.item(i), False)


        return replacement_map
Ejemplo n.º 11
0
    def select_and_rename_files_for_sampling(self, sample_fields):
        """
        Select all available layers for the point sampling and rename multiple occurrences of the same name.
        Prepend an index, to separate the layers and append the information, which color value is displayed.
        :return plugin: Return the plugin if it was found or None otherwise
        :rtype: plugin instance
        """
        import mole.extensions as extensions

        sample_list = self.pst_dialog.inData
        table = self.pst_dialog.fieldsTable
        number_of_samples = len(sample_list)

        RGBa_appendices = ['R', 'G', 'B', 'a']
        RGBa_index = 0
        last_name = ''
        prefix = 0

        replacement_map = {}

        for i in range(number_of_samples):
            # select all fields via the inData-view,
            # so the point sampling tool can manage its model accordingly/appropriately
            sample_list.setItemSelected(sample_list.item(i), True)

            # Get the source-name (as displayed in the field-table) and check if it was used already
            # (the name has to be split, since it is displayed in the form 'layer_name : Band x' to get the layer_name)
            table_index = table.rowCount() - 1
            table_text = table.item(table_index, 0).text().split(' : ')
            layer_name = table_text[0]
            band_name = table_text[1]
            layer = find_layer_by_name(layer_name)
            ext = extensions.by_layername(layer_name, 'Import')
            #if ext:
            #    print "Test: "+ext[0].layer_name
            # Check if the layer was already used
            if last_name != layer_name:
                last_name = layer_name
                prefix += 1
                RGBa_index = 0

            if (layer.name() == config.building_outline_layer_name
                    and (band_name.startswith('AREA')
                         or band_name.startswith('PERIMETER')
                         or band_name.startswith(config.building_id_key))):
                continue
            elif (layer.type() == QgsMapLayer.RasterLayer
                  and layer.rasterType() == QgsRasterLayer.Multiband
                  and layer.bandCount() == 4):
                # Truncate the name to a maximum of 6 characters, since QGIS limits the length of a feature's name to 10
                # prepend prefix (with leading zero), truncated name and RGBa-appendix
                try:
                    rgba = RGBa_appendices[RGBa_index]
                    RGBa_index += 1
                except IndexError as IError:
                    RGBa_index = 0
                    print(
                        self.__module__,
                        'IndexError when appending the RGBa-Appendix: {}'.
                        format(IError))
                if ext:
                    export_name = ext[0].field_id + '_' + rgba
                else:
                    export_name = '{:02d}{}_{}'.format(prefix, layer_name[0:6],
                                                       rgba)

                replacement_map[layer_name] = export_name[:-2]
                # Change the text in the table, so the pst can manage its model accordingly/appropriately
                table.item(table_index, 1).setText(export_name)
                continue
            elif ext:
                # NEW fieldname ist nicht klar
                if ext[0].field_rename is not None:
                    if band_name.startswith(tuple(ext[0].field_rename.keys())):
                        if ext[0].field_rename[band_name]:
                            table.item(table_index, 1).setText(
                                ext[0].field_rename[band_name])
                            continue
                    elif band_name.startswith(tuple(ext[0].par_in)):
                        continue
            sample_list.setItemSelected(sample_list.item(i), False)

        return replacement_map
Ejemplo n.º 12
0
def load(self=None):
    from mole.extensions import by_layername
    if bool(by_layername(config.building_outline_layer_name)[0].createDatabase()):
        return True
    return False