def help_blur(): title = tr('Blurring') intro = tr('Plugin to blur point data, such as health personal data, and ' 'get some statistics about this blurring.') inputs = [ tr('Point layer'), tr('Radius'), tr('Enveloppe : The layer will force the algorithm to have an ' 'intersection between the centroid and this layer. This is like a ' 'mask.') ] outputs = [ tr('Blurred layer (polygon)') ] more = [ tr('1 : Creating a buffer (radius r)'), picture('blurring_1.png'), tr('2 : Random selection of a point in each buffer'), picture('blurring_2.png'), tr('3 : Creating a buffer around the new point with the same radius. ' 'The initial point is at a maximal distance 2r of the centroid of ' 'the buffer.'), picture('blurring_3.png'), tr('4 : Deleting the random point and the first buffer'), picture('blurring_4.png'), ] html = html_table(title, intro, inputs, outputs, more) return html
def help_open_raster(): title = tr('Import raster') intro = tr('Import a raster into QGIS.') inputs = [ tr('Raster file') ] outputs = [ tr('New layer') ] more = [ ] html = html_table(title, intro, inputs, outputs, more) return html
def help_open_table(): title = tr('Import table') intro = tr('XLS or DBF format.') inputs = [ tr('Table file') ] outputs = [ tr('New table') ] more = [ ] html = html_table(title, intro, inputs, outputs, more) return html
def help_open_xy(): title = tr('Import CSV table') intro = tr('CSV format with geometry.') inputs = [ tr('CSV file') ] outputs = [ tr('New layer') ] more = [ ] html = html_table(title, intro, inputs, outputs, more) return html
def help_attribute_table(): title = tr('Export attribute table') intro = tr('Export as CSV format without geometry.') inputs = [ tr('Vector layer') ] outputs = [ tr('CSV file') ] more = [ ] html = html_table(title, intro, inputs, outputs, more) return html
def help_open_shapefile(): title = tr('Import shapefile') intro = tr('Import a shapefile into QGIS.') inputs = [ tr('Shapefile') ] outputs = [ tr('New layer') ] more = [ ] html = html_table(title, intro, inputs, outputs, more) return html
def add_layer(self, layer, layer_name): """Add a layer to the datastore. :param layer: The layer to add. :type layer: QgsMapLayer :param layer_name: The name of the layer in the datastore. :type layer_name: str :returns: A two-tuple. The first element will be True if we could add the layer to the datastore. The second element will be the layer name which has been used or the error message. :rtype: (bool, str) .. versionadded:: 4.0 """ if self._use_index: layer_name = '%s-%s' % (self._index, layer_name) self._index += 1 if self.layer_uri(layer_name): return False, tr('The layer already exists in the datastore.') if isinstance(layer, QgsRasterLayer): result = self._add_raster_layer(layer, layer_name) else: if layer.wkbType() == QGis.WKBNoGeometry: result = self._add_tabular_layer(layer, layer_name) else: result = self._add_vector_layer(layer, layer_name) return result
def save_table(self): if not self.tableWidget.rowCount(): return False csv_string = 'parameter,values\n' for i in range(self.tableWidget.rowCount()): item_param = self.tableWidget.item(i, 0) item_value = self.tableWidget.item(i, 1) csv_string += \ str(item_param.text()) + ',' + item_value.text() + '\n' last_directory = get_last_input_path() # noinspection PyArgumentList output_file = QFileDialog.getSaveFileName( parent=self, caption=tr('Select file'), directory=last_directory, filter='CSV (*.csv)') if output_file: path = dirname(output_file) set_last_input_path(path) fh = open(output_file, 'w') fh.write(csv_string) fh.close() return True
def open_file_browser(self): # noinspection PyArgumentList shapefile = QFileDialog.getOpenFileName( parent=self.parent, caption=tr('Select shapefile'), filter='Shapefile (*.shp)') self.le_shapefile.setText(shapefile)
def save_y_values(self): if not self.tableWidget.rowCount(): return False csv_string = 'parameter,values\n' for value in self.tab: csv_string += str(value) + '\n' last_directory = get_last_input_path() # noinspection PyArgumentList output_file = QFileDialog.getSaveFileName( parent=self, caption=tr('Select file'), directory=last_directory, filter='CSV (*.csv)') if output_file: path = dirname(output_file) set_last_input_path(path) fh = open(output_file, 'w') fh.write(csv_string) fh.close() return True
def open_file_browser(self): # noinspection PyArgumentList output_file = QFileDialog.getSaveFileNameAndFilter( parent=self.parent, caption=tr('Export as CSV'), filter='CSV (*.csv)') self.le_output.setText(output_file[0])
def open_file_browser(self): # noinspection PyArgumentList shapefile = QFileDialog.getOpenFileName( parent=self.parent, caption=tr('Select table'), filter='Table (*.xls *.xlsx *.dbf)') self.le_shapefile.setText(shapefile)
def save_csv(self): path = self.le_output.text() layer = self.cbx_layer.currentLayer() if self.tab_delimiter.isChecked(): delimiter = self.delimiters['tab'] elif self.pipe_delimiter.isChecked(): delimiter = self.delimiters['pipe'] elif self.semicolon_delimiter.isChecked(): delimiter = self.delimiters['semicolon'] else: delimiter = self.delimiters['comma'] csv_file = codecs.open(path, 'w', 'utf-8') provider = layer.dataProvider() fields = provider.fieldNameMap() header = u'%s\n' % delimiter.join(fields) csv_file.write(header) for feature in layer.getFeatures(): attributes = feature.attributes() line = u'%s\n' % delimiter.join([unicode(i) for i in attributes]) csv_file.write(line) csv_file.close() self.signalStatus.emit(3, tr('Successful export to %s' % path))
def open_raster(self): path = self.le_shapefile.text() file_info = QFileInfo(path) layer = QgsRasterLayer(path, file_info.baseName()) # noinspection PyArgumentList QgsMapLayerRegistry.instance().addMapLayer(layer) self.signalStatus.emit(3, tr('Successful import from %s' % path))
def open_file_browser(self): # noinspection PyArgumentList raster_filter = QgsProviderRegistry.instance().fileRasterFilters() # noinspection PyArgumentList raster = QFileDialog.getOpenFileName(parent=self.parent, caption=tr('Select raster'), filter=raster_filter) self.le_shapefile.setText(raster)
def open_shapefile(self): path = self.le_shapefile.text() if not path: return name = basename(splitext(path)[0]) layer = QgsVectorLayer(path, name, 'ogr') # noinspection PyArgumentList QgsMapLayerRegistry.instance().addMapLayer(layer) self.signalStatus.emit(3, tr('Successful import from %s' % path))
def help_density(): title = tr('Density') intro = tr('Compute density') inputs = [ tr('Point layer : disease'), tr('Polygon layer : administrative boundary'), tr('Case field'), tr('Ratio'), tr('New column') ] outputs = [ tr('New polygon layer with the density') ] more = [ tr('This algorithm will count the number of points inside each ' 'polygons and run a formula to get the density.'), tr('number of cases / area * ratio') ] html = html_table(title, intro, inputs, outputs, more) return html
def help_incidence_point(): title = tr('Incidence with case layer') intro = tr('You can create an incidence map about a disease.') inputs = [ tr('Point layer : disease'), tr('Polygon layer : administrative boundary with a population field'), tr('Population field'), tr('Ratio'), tr('New column') ] outputs = [ tr('New polygon layer with the incidence') ] more = [ tr('This algorithm will count the number of points inside each ' 'polygons and run a formula to get the incidence.'), tr('number of cases / population * ratio') ] html = html_table(title, intro, inputs, outputs, more) return html
def open_table(self): path = self.le_shapefile.text() if not path: return name = basename(splitext(path)[0]) layer = QgsVectorLayer(path, name, 'ogr') # noinspection PyArgumentList QgsMapLayerRegistry.instance().addMapLayer(layer) self.signalStatus.emit(3, tr('Successful import from %s' % path))
def select_file(self): last_folder = get_last_input_path() # noinspection PyArgumentList output_file = QFileDialog.getSaveFileName(parent=self, caption=tr('Select file'), directory=last_folder, filter='Shapefiles (*.shp)') if output_file: self.lineEdit_outputFile.setText(output_file) path = dirname(output_file) set_last_input_path(path) else: self.lineEdit_outputFile.setText('')
def __init__(self, parent=None): self.parent = parent super(OpenCsv, self).__init__() mdi_area = QMdiArea() # noinspection PyArgumentList dialog = QgsProviderRegistry.instance().selectWidget('delimitedtext') dialog.setWindowTitle(tr('Open a CSV')) layout = QVBoxLayout(self) layout.addWidget(mdi_area) mdi_area.addSubWindow(dialog) dialog.addVectorLayer[str, str, str].connect(self.success) dialog.rejected.connect(self.signalAskCloseWindow.emit)
def help_stats_blurring(): title = tr('Stats') intro = tr('With two layers, the plugin will count the number of ' 'intersections between them and produces some stats.') inputs = [ tr('Blurred layer'), tr('Stats layer : buildings for instanceon layer : administrative ' 'boundary')] outputs = [ tr('New polygon layer with the density') ] more = [ tr('This is usefull if you want to rate your blurring.'), ] html = html_table(title, intro, inputs, outputs, more) return html
def __init__(self, msg=None, suffix=None): if not msg: msg = tr(u'Error while creating the shapefile') if suffix: msg += suffix GeoHealthException.__init__(self, msg)
def __init__(self, msg=None, number=None): if not msg: msg = tr(u'Point number %d is outside the envelope.' % number) GeoHealthException.__init__(self, msg)
def __init__(self, msg=None, epsg1=None, epsg2=None): if not msg: msg = tr(u'It\'s not the same projection system : %s != %s' % (epsg1, epsg2)) GeoHealthException.__init__(self, msg)
def run_blur(self): self.progressBar_blur.setValue(0) self.label_progress.setText('') # Get all the fields. layer_to_blur = self.comboBox_layerToBlur.currentLayer() radius = self.spinBox_radius.value() display = self.checkBox_addToMap.isChecked() selected_features_only = self.checkBox_selectedOnlyFeatures.isChecked() file_name = self.lineEdit_outputFile.text() export_radius = self.checkBox_exportRadius.isChecked() export_centroid = self.checkBox_exportCentroid.isChecked() if self.checkBox_envelope.isChecked(): layer_envelope = self.comboBox_envelope.currentLayer() else: layer_envelope = None # Test values try: if not layer_to_blur: raise NoLayerProvidedException if not file_name and not display: raise NoFileNoDisplayException if layer_to_blur.crs().mapUnits() != 0: msg = tr('The projection of the map or of the layer is not ' 'in meters. These parameters should be in meters.') display_message_bar(msg, level=QgsMessageBar.WARNING, duration=5) if not file_name: file_name = getTempFilenameInTempFolder('blurring.shp') if layer_envelope: if layer_to_blur.crs() != layer_envelope.crs(): raise DifferentCrsException( epsg1=layer_to_blur.crs().authid(), epsg2=layer_envelope.crs().authid()) self.label_progress.setText('Creating index ...') layer_envelope = LayerIndex(layer_envelope) self.progressBar_blur.setValue(0) self.label_progress.setText('Blurring ...') if selected_features_only: features = layer_to_blur.selectedFeatures() nb_features = layer_to_blur.selectedFeatureCount() else: features = layer_to_blur.getFeatures() nb_features = layer_to_blur.featureCount() # Fields fields = layer_to_blur.pendingFields() if export_radius: fields.append(QgsField(u"Radius", QVariant.Int)) if export_centroid: fields.append(QgsField(u"X centroid", QVariant.Int)) fields.append(QgsField(u"Y centroid", QVariant.Int)) # Creating the output shapefile file_writer = QgsVectorFileWriter(file_name, 'utf-8', fields, QGis.WKBPolygon, layer_to_blur.crs(), 'ESRI Shapefile') if file_writer.hasError() != QgsVectorFileWriter.NoError: raise CreatingShapeFileException(suffix=file_writer.hasError()) # Creating the algorithm with radius algo = Blur(radius, layer_envelope, export_radius, export_centroid) for j, feature in enumerate(features): feature = algo.blur(feature) file_writer.addFeature(feature) # Update progress bar percent = int((j + 1) * 100 / nb_features) self.progressBar_blur.setValue(percent) # Write all features in the file del file_writer if display: old_default_projection = self.settings.value( '/Projections/defaultBehaviour') self.settings.setValue('/Projections/defaultBehaviour', 'useProject') layer_name = basename(file_name) new_layer = QgsVectorLayer(file_name, layer_name, 'ogr') new_layer.commitChanges() new_layer.clearCacheImage() # noinspection PyArgumentList QgsMapLayerRegistry.instance().addMapLayers([new_layer]) self.settings.setValue('/Projections/defaultBehaviour', old_default_projection) msg = tr('Successful export in %s' % file_name) iface.messageBar().pushMessage(msg, level=QgsMessageBar.INFO, duration=5) self.signalAskCloseWindow.emit() except GeoHealthException, e: self.label_progress.setText('') display_message_bar(msg=e.msg, level=e.level, duration=e.duration)
def __init__(self, msg=None, suffix=None): if not msg: msg = tr(u'It\'s not a number') if suffix: msg += " : %s" % suffix GeoHealthException.__init__(self, msg)
def success(self, path, base_name, provider_key): iface.addVectorLayer(path, base_name, provider_key) self.signalStatus.emit(3, tr('Successful import'))
def __init__(self, msg=None): if not msg: msg = tr(u'No layer was provided.') GeoHealthException.__init__(self, msg)
def __init__(self, msg=None): if not msg: msg = tr(u'No file provided, "add result to canvas" required') GeoHealthException.__init__(self, msg)
def __init__(self, msg=None, field=None): if not msg: msg = tr(u'The field %s already exists in the layer.' % field) GeoHealthException.__init__(self, msg)
def __init__(self, msg=None, field_1=None, field_2=None): if not msg: msg = tr(u'Fields are not different') if field_1 and field_2: msg += " : %s and %s " % (field_1, field_2) GeoHealthException.__init__(self, msg)
def help(self): return True, tr('For more explanations, go to the vector\'s menu then "Blurring"' ' -> "Help"<br />')
def open_file_browser(self): output_file = QFileDialog.getSaveFileNameAndFilter( self.parent, tr('Save shapefile'), filter='SHP (*.shp)') self.le_output_filepath.setText(output_file[0])
def run_stats(self): """Main function which do the process.""" # Get the common fields. self.admin_layer = self.cbx_aggregation_layer.currentLayer() if self.use_point_layer: # If we use a point layer. point_layer = self.cbx_case_layer.currentLayer() else: # If we use a column with number of case. case_column = self.cbx_case_field.currentField() index_case = self.admin_layer.fieldNameIndex(case_column) if not self.use_area: # If we don't use density. population = self.cbx_population_field.currentField() index_population = self.admin_layer.fieldNameIndex(population) if not self.name_field: self.name_field = self.le_new_column.placeholderText() # Add new column. add_nb_intersections = self.checkBox_addNbIntersections.isChecked() # Ratio ratio = self.cbx_ratio.currentText() ratio = ratio.replace(' ', '') # Output. self.output_file_path = self.le_output_filepath.text() try: self.button_box_ok.setDisabled(True) # noinspection PyArgumentList QApplication.setOverrideCursor(Qt.WaitCursor) # noinspection PyArgumentList QApplication.processEvents() if not self.admin_layer: raise NoLayerProvidedException if not self.admin_layer and self.use_point_layer: raise NoLayerProvidedException crs_admin_layer = self.admin_layer.crs() if self.use_point_layer: crs_point_layer = point_layer.crs() if crs_admin_layer != crs_point_layer: raise DifferentCrsException(epsg1=crs_point_layer.authid(), epsg2=crs_admin_layer.authid()) if not self.use_point_layer and not self.use_area: if index_population == index_case: raise FieldException(field_1='Population', field_2='Case') try: ratio = float(ratio) except ValueError: raise NotANumberException(suffix=ratio) # Output if not self.output_file_path: temp_file = NamedTemporaryFile(delete=False, suffix='-geohealth.shp') self.output_file_path = temp_file.name temp_file.flush() temp_file.close() admin_layer_provider = self.admin_layer.dataProvider() fields = admin_layer_provider.fields() if admin_layer_provider.fieldNameIndex(self.name_field) != -1: raise FieldExistingException(field=self.name_field) fields.append(QgsField(self.name_field, QVariant.Double)) if add_nb_intersections: fields.append(QgsField('nb_of_intersections', QVariant.Int)) data = [] file_writer = QgsVectorFileWriter(self.output_file_path, 'utf-8', fields, QGis.WKBPolygon, self.admin_layer.crs(), 'ESRI Shapefile') if self.use_point_layer: total_case = point_layer.featureCount() else: total_case = 0 for i, feature in enumerate(self.admin_layer.getFeatures()): attributes = feature.attributes() if self.use_point_layer: count = 0 for f in point_layer.getFeatures(): if f.geometry().intersects(feature.geometry()): count += 1 else: count = int(attributes[index_case]) total_case += count try: if self.use_area: area = feature.geometry().area() value = float(count) / area * ratio else: try: population = float(attributes[index_population]) except ValueError: raise NotANumberException( suffix=attributes[index_population]) value = float(count) / population * ratio except ZeroDivisionError: value = None except TypeError: value = None data.append(value) attributes.append(value) if add_nb_intersections: attributes.append(count) new_feature = QgsFeature() new_geom = QgsGeometry(feature.geometry()) new_feature.setAttributes(attributes) new_feature.setGeometry(new_geom) file_writer.addFeature(new_feature) del file_writer self.output_layer = QgsVectorLayer(self.output_file_path, self.name_field, 'ogr') QgsMapLayerRegistry.instance().addMapLayer(self.output_layer) if self.checkBox_incidence_runStats.isChecked(): stats = Stats(data) items_stats = [ 'Incidence null,%d' % stats.null_values(), 'Count(point),%d' % total_case, 'Count(polygon),%d' % self.admin_layer.featureCount(), 'Min,%d' % stats.min(), 'Average,%f' % stats.average(), 'Max,%d' % stats.max(), 'Median,%f' % stats.median(), 'Range,%d' % stats.range(), 'Variance,%f' % stats.variance(), 'Standard deviation,%f' % stats.standard_deviation() ] self.tableWidget.clear() self.tableWidget.setColumnCount(2) labels = ['Parameters', 'Values'] self.tableWidget.setHorizontalHeaderLabels(labels) self.tableWidget.setRowCount(len(items_stats)) for i, item in enumerate(items_stats): s = item.split(',') self.tableWidget.setItem(i, 0, QTableWidgetItem(s[0])) self.tableWidget.setItem(i, 1, QTableWidgetItem(s[1])) self.tableWidget.resizeRowsToContents() self.draw_plot(data) else: self.hide() if self.symbology.isChecked(): self.add_symbology() self.signalStatus.emit(3, tr('Successful process')) except GeoHealthException, e: display_message_bar(msg=e.msg, level=e.level, duration=e.duration)
def run_stats(self): self.progressBar_stats.setValue(0) self.label_progressStats.setText('') # noinspection PyArgumentList QApplication.processEvents() blurred_layer = self.comboBox_blurredLayer.currentLayer() stats_layer = self.comboBox_statsLayer.currentLayer() try: if not blurred_layer or not stats_layer: raise NoLayerProvidedException crs_blurred_layer = blurred_layer.crs() crs_stats_layer = stats_layer.crs() if crs_blurred_layer != crs_stats_layer: raise DifferentCrsException( epsg1=crs_blurred_layer.authid(), epsg2=crs_stats_layer.authid()) if blurred_layer == stats_layer: raise NoLayerProvidedException if not blurred_layer or not stats_layer: raise NoLayerProvidedException nb_feature_stats = stats_layer.featureCount() nb_feature_blurred = blurred_layer.featureCount() features_stats = {} label_preparing = tr('Preparing index on the stats layer') label_creating = tr('Creating index on the stats layer') label_calculating = tr('Calculating') if QGis.QGIS_VERSION_INT < 20700: self.label_progressStats.setText('%s 1/3' % label_preparing) for i, feature in enumerate(stats_layer.getFeatures()): features_stats[feature.id()] = feature percent = int((i + 1) * 100 / nb_feature_stats) self.progressBar_stats.setValue(percent) # noinspection PyArgumentList QApplication.processEvents() self.label_progressStats.setText('%s 2/3' % label_creating) # noinspection PyArgumentList QApplication.processEvents() index = QgsSpatialIndex() for i, f in enumerate(stats_layer.getFeatures()): index.insertFeature(f) percent = int((i + 1) * 100 / nb_feature_stats) self.progressBar_stats.setValue(percent) # noinspection PyArgumentList QApplication.processEvents() self.label_progressStats.setText('%s 3/3' % label_calculating) else: # If QGIS >= 2.7, we can speed up the spatial index. # From 1 min 15 to 7 seconds on my PC. self.label_progressStats.setText('%s 1/2' % label_creating) # noinspection PyArgumentList QApplication.processEvents() index = QgsSpatialIndex(stats_layer.getFeatures()) self.label_progressStats.setText('%s 2/2' % label_calculating) # noinspection PyArgumentList QApplication.processEvents() self.tab = [] for i, feature in enumerate(blurred_layer.getFeatures()): count = 0 ids = index.intersects(feature.geometry().boundingBox()) for unique_id in ids: request = QgsFeatureRequest().setFilterFid(unique_id) f = stats_layer.getFeatures(request).next() if f.geometry().intersects(feature.geometry()): count += 1 self.tab.append(count) percent = int((i + 1) * 100 / nb_feature_blurred) self.progressBar_stats.setValue(percent) # noinspection PyArgumentList QApplication.processEvents() stats = Stats(self.tab) items_stats = [ 'Count(blurred),%d' % nb_feature_blurred, 'Count(stats),%d' % nb_feature_stats, 'Min,%d' % stats.min(), 'Average,%f' % stats.average(), 'Max,%d' % stats.max(), 'Median,%f' % stats.median(), 'Range,%d' % stats.range(), 'Variance,%f' % stats.variance(), 'Standard deviation,%f' % stats.standard_deviation() ] self.tableWidget.clear() self.tableWidget.setColumnCount(2) labels = ['Parameters', 'Values'] self.tableWidget.setHorizontalHeaderLabels(labels) self.tableWidget.setRowCount(len(items_stats)) for i, item in enumerate(items_stats): s = item.split(',') self.tableWidget.setItem(i, 0, QTableWidgetItem(s[0])) self.tableWidget.setItem(i, 1, QTableWidgetItem(s[1])) self.tableWidget.resizeRowsToContents() self.draw_plot(self.tab) except GeoHealthException, e: self.label_progressStats.setText('') display_message_bar(msg=e.msg, level=e.level, duration=e.duration)
def help(self): return True, tr( 'For more explanations, go to the vector\'s menu then "Blurring"' ' -> "Help"<br />')