Ejemplo n.º 1
0
def smooth_shakemap(shakemap_layer_path,
                    output_file_path='',
                    active_band=1,
                    smoothing_method=NUMPY_SMOOTHING,
                    smoothing_sigma=0.9):
    """Make a smoother shakemap layer from a shake map.

    :param shakemap_layer_path: The shake map raster layer path.
    :type shakemap_layer_path: basestring

    :param active_band: The band which the data located, default to 1.
    :type active_band: int

    :param smoothing_method: The smoothing method that wanted to be used.
    :type smoothing_method: NONE_SMOOTHING, NUMPY_SMOOTHING, SCIPY_SMOOTHING

    :param smooth_sigma: parameter for gaussian filter used in smoothing
        function.
    :type smooth_sigma: float

    :returns: The contour of the shake map layer.
    :rtype: QgsRasterLayer
    """
    # Set output path
    if not output_file_path:
        output_file_path = unique_filename(suffix='.tiff', dir=temp_dir())

    # convert to numpy
    shakemap_file = gdal.Open(shakemap_layer_path)
    shakemap_array = np.array(
        shakemap_file.GetRasterBand(active_band).ReadAsArray())

    # do smoothing
    if smoothing_method == NUMPY_SMOOTHING:
        smoothed_array = convolve(shakemap_array,
                                  gaussian_kernel(smoothing_sigma))
    else:
        smoothed_array = shakemap_array

    # Create smoothed shakemap raster layer
    driver = gdal.GetDriverByName('GTiff')
    smoothed_shakemap_file = driver.Create(output_file_path,
                                           shakemap_file.RasterXSize,
                                           shakemap_file.RasterYSize, 1)
    smoothed_shakemap_file.GetRasterBand(1).WriteArray(smoothed_array)

    # CRS
    smoothed_shakemap_file.SetProjection(shakemap_file.GetProjection())
    smoothed_shakemap_file.SetGeoTransform(shakemap_file.GetGeoTransform())
    smoothed_shakemap_file.FlushCache()

    del smoothed_shakemap_file

    if not os.path.isfile(output_file_path):
        raise FileNotFoundError(
            tr('The smoothed shakemap is not created. It should be at '
               '{output_file_path}'.format(output_file_path=output_file_path)))

    return output_file_path
Ejemplo n.º 2
0
    def prepare_input(self):
        """Fetch all the input from dialog, validate, and store it.

        Consider this as a bridge between dialog interface and our logical
        stored data in this class

        :raises: InvalidLayerError, CanceledImportDialogError
        """
        # Validate The combobox impact layers (they should be different)
        first_layer_index = self.first_layer.currentIndex()
        second_layer_index = self.second_layer.currentIndex()

        if first_layer_index < 0:
            raise InvalidLayerError(self.tr('First layer is not valid.'))

        if second_layer_index < 0:
            raise InvalidLayerError(self.tr('Second layer is not valid.'))

        if first_layer_index == second_layer_index:
            raise InvalidLayerError(
                self.tr('First layer must be different to second layer'
                        '.'))

        # Get all chosen layers
        self.first_impact['layer'] = self.first_layer.itemData(
            self.first_layer.currentIndex(), QtCore.Qt.UserRole)
        self.second_impact['layer'] = self.second_layer.itemData(
            self.second_layer.currentIndex(), QtCore.Qt.UserRole)
        self.aggregation['layer'] = self.aggregation_layer.itemData(
            self.aggregation_layer.currentIndex(), QtCore.Qt.UserRole)

        # Validate the output directory
        self.require_directory()

        # Get output directory
        self.out_dir = self.output_directory.text()

        # Whether to use own report template:
        if self.report_template_checkbox.isChecked():
            own_template_path = self.report_template_le.text()
            if os.path.isfile(own_template_path):
                self.template_path = own_template_path
            else:
                raise FileNotFoundError(
                    self.tr('Template file does not exist.'))

        # Flag whether to merge entire area or based on aggregation unit
        # Rizky: Fix nasty bug where the dialog stuck in entire_area_mode
        # the mode should be rechecked based on selected aggregation layer
        self.entire_area_mode = True
        if (self.aggregation_layer.currentIndex() > 0
                and not self.aggregation['layer'] is None):
            self.entire_area_mode = False
Ejemplo n.º 3
0
def add_layers(scenario_dir, paths, iface):  # pylint: disable=W0621
    """Add the layers described in a scenario file to QGIS.

    :param scenario_dir: Base directory to find path.
    :type scenario_dir: str

    :param paths: Path of scenario file (or a list of paths).
    :type paths: str, list

    :param iface: iface instance to do necessary things to QGIS.
    :type iface: QgsInterface

    :raises: Exception, TypeError, FileNotFoundError

    Note:
        * Exception - occurs when paths have illegal extension
        * TypeError - occurs when paths is not string or list
        * FileNotFoundError - occurs when file not found
    """

    path_list = []
    if isinstance(paths, str):
        path_list.append(extract_path(scenario_dir, paths))
    elif isinstance(paths, list):
        path_list = [extract_path(scenario_dir, path) for path in paths]
    else:
        message = "Paths must be string or list not %s" % type(paths)
        raise TypeError(message)

    layer_set = []
    for path, base_name in path_list:
        extension = os.path.splitext(path)[-1]
        if not os.path.exists(path):
            raise FileNotFoundError('File not found: %s' % path)

        if extension in ['.asc', '.tif']:
            LOGGER.debug("add raster layer %s" % path)
            # noinspection PyCallingNonCallable
            layer = QgsRasterLayer(path, base_name)
            layer_set.append(layer)
        elif extension in ['.shp']:
            LOGGER.debug("add vector layer %s" % path)
            # noinspection PyCallingNonCallable
            layer = QgsVectorLayer(path, base_name, 'ogr')
            layer_set.append(layer)
        else:
            raise Exception('File %s had illegal extension' % path)
    # noinspection PyUnresolvedReferences
    QgsMapLayerRegistry.instance().addMapLayers(layer_set)
    # noinspection PyCallingNonCallable
    iface.mapCanvas().setLayerSet(
        [QgsMapCanvasLayer(layer) for layer in layer_set])