def clone_layer(layer, keep_selection=True): """Duplicate the layer by taking the same source and copying keywords. :param keep_selection: If we should keep the selection. Default to true. :type keep_selection: bool :param layer: Layer to be duplicated. :type layer: QgsMapLayer :return: The new QgsMapLayer object. :rtype: QgsMapLayer """ if is_vector_layer(layer): new_layer = QgsVectorLayer( layer.source(), layer.name(), layer.providerType()) if keep_selection and layer.selectedFeatureCount() > 0: request = QgsFeatureRequest() request.setFilterFids(layer.selectedFeatureIds()) request.setFlags(QgsFeatureRequest.NoGeometry) iterator = layer.getFeatures(request) new_layer.setSelectedFeatures([k.id() for k in iterator]) else: new_layer = QgsRasterLayer( layer.source(), layer.name(), layer.providerType()) new_layer.keywords = copy_layer_keywords(layer.keywords) return layer
def clone_layer(layer, keep_selection=True): """Duplicate the layer by taking the same source and copying keywords. :param keep_selection: If we should keep the selection. Default to true. :type keep_selection: bool :param layer: Layer to be duplicated. :type layer: QgsMapLayer :return: The new QgsMapLayer object. :rtype: QgsMapLayer """ if is_vector_layer(layer): new_layer = QgsVectorLayer(layer.source(), layer.name(), layer.providerType()) if keep_selection and layer.selectedFeatureCount() > 0: request = QgsFeatureRequest() request.setFilterFids(layer.selectedFeaturesIds()) request.setFlags(QgsFeatureRequest.NoGeometry) iterator = layer.getFeatures(request) new_layer.setSelectedFeatures([k.id() for k in iterator]) else: new_layer = QgsRasterLayer(layer.source(), layer.name(), layer.providerType()) new_layer.keywords = copy_layer_keywords(layer.keywords) return layer
def testRepack(self): vl = QgsVectorLayer(u'{}|layerid=0'.format(self.repackfile), u'test', u'ogr') ids = [f.id() for f in vl.getFeatures(QgsFeatureRequest().setFilterExpression('pk=1'))] vl.setSelectedFeatures(ids) assert vl.selectedFeaturesIds() == ids, vl.selectedFeaturesIds() assert vl.pendingFeatureCount() == 5, vl.pendingFeatureCount() assert vl.startEditing() assert vl.deleteFeature(3) assert vl.commitChanges() assert vl.selectedFeatureCount() == 0 or vl.selectedFeatures()[0]['pk'] == 1
def testRepack(self): vl = QgsVectorLayer(u"{}|layerid=0".format(self.repackfile), u"test", u"ogr") ids = [f.id() for f in vl.getFeatures(QgsFeatureRequest().setFilterExpression("pk=1"))] vl.setSelectedFeatures(ids) self.assertEqual(vl.selectedFeaturesIds(), ids) self.assertEqual(vl.pendingFeatureCount(), 5) self.assertTrue(vl.startEditing()) self.assertTrue(vl.deleteFeature(3)) self.assertTrue(vl.commitChanges()) self.assertTrue(vl.selectedFeatureCount() == 0 or vl.selectedFeatures()[0]["pk"] == 1)
def f(): crs = iface.mapCanvas().mapRenderer().destinationCrs() uri = "%s?srsname=%s&typename=geonode:%s&version=1.0.0&request=GetFeature&service=WFS" % (url, crs.authid(), name) qgslayer = QgsVectorLayer(uri, name, "WFS") if not qgslayer.isValid(): raise Exception ("Layer at %s is not a valid layer" % uri) fieldname = self._getTimeField(qgslayer) if fieldname is None: QgsMapLayerRegistry.instance().addMapLayers([qgslayer]) else: memlayer = QgsVectorLayer("%s?crs=%s" % (GEOM_TYPE_MAP[qgslayer.wkbType()], crs.authid()), name, "memory") memlayer.startEditing() for field in qgslayer.pendingFields(): memlayer.addAttribute(field) for feat in qgslayer.getFeatures(): memlayer.addFeatures([feat]) memlayer.commitChanges() QgsMapLayerRegistry.instance().addMapLayers([memlayer]) memlayer.setSelectedFeatures([]) addWfsAnimation(memlayer, fieldname)
def eliminate(self, inLayer, boundary, progressBar, outFileName): # keep references to the features to eliminate fidsToEliminate = inLayer.selectedFeaturesIds() if outFileName: # user wants a new shape file to be created as result provider = inLayer.dataProvider() error = QgsVectorFileWriter.writeAsVectorFormat(inLayer, outFileName, provider.encoding(), inLayer.crs(), "ESRI Shapefile") if error != QgsVectorFileWriter.NoError: QMessageBox.warning(self, self.tr("Eliminate"), self.tr("Error creating output file")) return None outLayer = QgsVectorLayer(outFileName, QFileInfo(outFileName).completeBaseName(), "ogr") else: QMessageBox.information(self, self.tr("Eliminate"), self.tr("Please specify output shapefile")) return None # delete features to be eliminated in outLayer outLayer.setSelectedFeatures(fidsToEliminate) outLayer.startEditing() if outLayer.deleteSelectedFeatures(): if self.saveChanges(outLayer): outLayer.startEditing() else: QMessageBox.warning(self, self.tr("Eliminate"), self.tr("Could not delete features")) return None # ANALYZE start = 20.00 progressBar.setValue(start) add = 80.00 / len(fidsToEliminate) lastLen = 0 # we go through the list and see if we find any polygons we can merge the selected with # if we have no success with some we merge and then restart the whole story while (lastLen != inLayer.selectedFeatureCount()): # check if we made any progress lastLen = inLayer.selectedFeatureCount() fidsToDeselect = [] #iterate over the polygons to eliminate for fid2Eliminate in inLayer.selectedFeaturesIds(): feat = QgsFeature() if inLayer.getFeatures( QgsFeatureRequest().setFilterFid( fid2Eliminate ).setSubsetOfAttributes([]) ).nextFeature( feat ): geom2Eliminate = feat.geometry() bbox = geom2Eliminate.boundingBox() fit = outLayer.getFeatures( QgsFeatureRequest().setFilterRect( bbox ) ) mergeWithFid = None mergeWithGeom = None max = 0 selFeat = QgsFeature() while fit.nextFeature(selFeat): selGeom = selFeat.geometry() if geom2Eliminate.intersects(selGeom): # we have a candidate iGeom = geom2Eliminate.intersection(selGeom) if boundary: selValue = iGeom.length() else: # we need a common boundary if 0 < iGeom.length(): selValue = selGeom.area() else: selValue = 0 if selValue > max: max = selValue mergeWithFid = selFeat.id() mergeWithGeom = QgsGeometry(selGeom) # deep copy of the geometry if mergeWithFid is not None: # a successful candidate newGeom = mergeWithGeom.combine(geom2Eliminate) if outLayer.changeGeometry(mergeWithFid, newGeom): # write change back to disc if self.saveChanges(outLayer): outLayer.startEditing() else: return None # mark feature as eliminated in inLayer fidsToDeselect.append(fid2Eliminate) else: QMessageBox.warning( self, self.tr("Eliminate"), self.tr("Could not replace geometry of feature with id %s") % (mergeWithFid)) return None start = start + add progressBar.setValue(start) # end for fid2Eliminate # deselect features that are already eliminated in inLayer inLayer.deselect(fidsToDeselect) #end while if inLayer.selectedFeatureCount() > 0: # copy all features that could not be eliminated to outLayer if outLayer.addFeatures(inLayer.selectedFeatures()): # inform user fidList = "" for fid in inLayer.selectedFeaturesIds(): if not fidList == "": fidList += ", " fidList += unicode(fid) QMessageBox.information( self, self.tr("Eliminate"), self.tr("Could not eliminate features with these ids:\n%s") % (fidList)) else: QMessageBox.warning(self, self.tr("Eliminate"), self.tr("Could not add features")) # stop editing outLayer and commit any pending changes if not self.saveChanges(outLayer): return None if outFileName: if self.addToCanvasCheck.isChecked(): ftools_utils.addShapeToCanvas(outFileName) else: QMessageBox.information( self, self.tr("Eliminate"), self.tr("Created output shapefile:\n%s") % (outFileName)) self.iface.mapCanvas().refresh()
class TestSectionPlot(utils_for_tests.MidvattenTestSpatialiteDbSv): """ The test doesn't go through the whole section plot unfortunately """ @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestSpatialiteNotCreated. mock_instance_settings_database) def setUp(self): super(TestSectionPlot, self).setUp() self.midvatten.ms.settingsdict['secplot_loaded_template'] = '' self.midvatten.ms.settingsdict['secplot_templates'] = '' @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestSpatialiteNotCreated. mock_instance_settings_database) def create_and_select_vlayer(self): self.qgs = QgsApplication([], True) self.qgs.initQgis() self.midvatten.ms.settingsdict['secplotdrillstop'] = u"%berg%" dbconnection = db_utils.DbConnectionManager() uri = dbconnection.uri uri.setDataSource('', 'obs_lines', 'geometry', '', 'obsid') dbtype = db_utils.get_dbtype(dbconnection.dbtype) self.vlayer = QgsVectorLayer(uri.uri(), 'TestLayer', dbtype) features = self.vlayer.getFeatures() for feature in features: featureid = feature.id() self.vlayer.setSelectedFeatures([featureid]) @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestSpatialiteNotCreated. mock_instance_settings_database) def test_plot_section(self, mock_messagebar): """For now, the test only initiates the plot. Check that it does not crash """ db_utils.sql_alter_db( u'''INSERT INTO obs_lines (obsid, geometry) VALUES ('L1', ST_GeomFromText('LINESTRING(633466.711659 6720684.24498, 633599.530455 6720727.016568)', 3006))''' ) db_utils.sql_alter_db( u'''INSERT INTO obs_points (obsid, geometry) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006))''' ) db_utils.sql_alter_db( u'''INSERT INTO obs_points (obsid, geometry) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006))''' ) db_utils.sql_alter_db( u'''INSERT INTO obs_points (obsid, geometry) VALUES ('P3', ST_GeomFromText('POINT(6720728 016569)', 3006))''' ) self.create_and_select_vlayer() @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestSpatialiteNotCreated. mock_instance_settings_database) @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True) @mock.patch('qgis.utils.iface', autospec=True) def _test_plot_section(self, mock_iface, mock_getselectedobjectnames): mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer mock_getselectedobjectnames.return_value = (u'P1', u'P2', u'P3') mock_mapcanvas = mock_iface.mapCanvas.return_value mock_mapcanvas.layerCount.return_value = 0 self.midvatten.plot_section() self.midvatten.ms = self.ms self.myplot = self.midvatten.myplot self.myplot.drillstoplineEdit.setText(u"%berg%") self.myplot.draw_plot() self.selected_obsids = self.myplot.selected_obsids _test_plot_section(self) assert """call.info(log_msg=u'Settings {""" in str( mock_messagebar.mock_calls) assert self.myplot.drillstoplineEdit.text() == u'%berg%' assert utils_for_tests.create_test_string( self.myplot.selected_obsids) == "[u'P1' u'P2' u'P3']" assert not mock_messagebar.warning.called assert not mock_messagebar.critical.called @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestSpatialiteNotCreated. mock_instance_settings_database) def test_plot_section_with_depth(self, mock_messagebar): db_utils.sql_alter_db( u'''INSERT INTO obs_lines (obsid, geometry) VALUES ('L1', ST_GeomFromText('LINESTRING(633466.711659 6720684.24498, 633599.530455 6720727.016568)', 3006))''' ) db_utils.sql_alter_db( u'''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006), 2)''' ) db_utils.sql_alter_db( u'''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006), '1')''' ) db_utils.sql_alter_db( u'''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P3', ST_GeomFromText('POINT(6720727 016568)', 3006), NULL)''' ) self.create_and_select_vlayer() @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True) @mock.patch('qgis.utils.iface', autospec=True) def _test(self, mock_iface, mock_getselectedobjectnames): mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer mock_getselectedobjectnames.return_value = (u'P1', u'P2', u'P3') mock_mapcanvas = mock_iface.mapCanvas.return_value mock_mapcanvas.layerCount.return_value = 0 self.midvatten.plot_section() self.myplot = self.midvatten.myplot _test(self) print(str(mock_messagebar.mock_calls)) assert not mock_messagebar.warning.called assert not mock_messagebar.critical.called @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestSpatialiteNotCreated. mock_instance_settings_database) def test_plot_section_with_w_levels(self, mock_messagebar): db_utils.sql_alter_db( u'''INSERT INTO obs_lines (obsid, geometry) VALUES ('L1', ST_GeomFromText('LINESTRING(633466.711659 6720684.24498, 633599.530455 6720727.016568)', 3006))''' ) db_utils.sql_alter_db( u'''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006), 2)''' ) db_utils.sql_alter_db( u'''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006), '1')''' ) db_utils.sql_alter_db( u'''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P3', ST_GeomFromText('POINT(6720727 016568)', 3006), NULL)''' ) db_utils.sql_alter_db( u'''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P1', '2015-01-01 00:00:00', '15', '200', '185')''' ) db_utils.sql_alter_db( u'''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P2', '2015-01-01 00:00:00', '17', '200', '183')''' ) self.create_and_select_vlayer() @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True) @mock.patch('qgis.utils.iface', autospec=True) def _test(self, mock_iface, mock_getselectedobjectnames): mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer mock_getselectedobjectnames.return_value = (u'P1', u'P2', u'P3') mock_mapcanvas = mock_iface.mapCanvas.return_value mock_mapcanvas.layerCount.return_value = 0 self.midvatten.plot_section() self.myplot = self.midvatten.myplot gui_utils.set_combobox(self.myplot.wlvltableComboBox, u'w_levels') self.myplot.datetimetextEdit.append(u'2015') self.myplot.draw_plot() _test(self) print(str(mock_messagebar.mock_calls)) assert not mock_messagebar.warning.called assert not mock_messagebar.critical.called @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestSpatialiteNotCreated. mock_instance_settings_database) def test_plot_section_length_along_slope(self, mock_messagebar): """For now, the test only initiates the plot. Check that it does not crash """ db_utils.sql_alter_db( u'''INSERT INTO obs_lines (obsid, geometry) VALUES ('L1', ST_GeomFromText('LINESTRING(2 0, 10 10)', 3006))''' ) db_utils.sql_alter_db( u'''INSERT INTO obs_points (obsid, geometry) VALUES ('P1', ST_GeomFromText('POINT(1 0)', 3006))''' ) db_utils.sql_alter_db( u'''INSERT INTO obs_points (obsid, geometry) VALUES ('P2', ST_GeomFromText('POINT(3 0)', 3006))''' ) db_utils.sql_alter_db( u'''INSERT INTO obs_points (obsid, geometry) VALUES ('P3', ST_GeomFromText('POINT(5 0)', 3006))''' ) self.create_and_select_vlayer() @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True) @mock.patch('qgis.utils.iface', autospec=True) def _test(midvatten, vlayer, mock_iface, mock_getselectedobjectnames): mock_iface.mapCanvas.return_value.currentLayer.return_value = vlayer mock_getselectedobjectnames.return_value = (u'P1', u'P2', u'P3') mock_mapcanvas = mock_iface.mapCanvas.return_value mock_mapcanvas.layerCount.return_value = 0 midvatten.plot_section() self.myplot = midvatten.myplot self.myplot.drillstoplineEdit.setText(u"%berg%") self.myplot.draw_plot() _test(self.midvatten, self.vlayer) test_string = utils_for_tests.create_test_string( self.myplot.LengthAlong) print(str(test_string)) print(str(mock_messagebar.mock_calls)) assert any([ test_string == u"[ 0. 0.62469505 1.87408514]", test_string == u"[0. 0.62469505 1.87408514]" ]) assert not mock_messagebar.warning.called assert not mock_messagebar.critical.called @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestSpatialiteNotCreated. mock_instance_settings_database) def test_plot_section_length_along(self, mock_messagebar): """For now, the test only initiates the plot. Check that it does not crash """ db_utils.sql_alter_db( u'''INSERT INTO obs_lines (obsid, geometry) VALUES ('L1', ST_GeomFromText('LINESTRING(0 0, 1 0, 10 0)', 3006))''' ) db_utils.sql_alter_db( u'''INSERT INTO obs_points (obsid, geometry) VALUES ('P1', ST_GeomFromText('POINT(1 0)', 3006))''' ) db_utils.sql_alter_db( u'''INSERT INTO obs_points (obsid, geometry) VALUES ('P2', ST_GeomFromText('POINT(3 5)', 3006))''' ) db_utils.sql_alter_db( u'''INSERT INTO obs_points (obsid, geometry) VALUES ('P3', ST_GeomFromText('POINT(5 10)', 3006))''' ) self.create_and_select_vlayer() @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True) @mock.patch('qgis.utils.iface', autospec=True) def _test(midvatten, vlayer, mock_iface, mock_getselectedobjectnames): mock_iface.mapCanvas.return_value.currentLayer.return_value = vlayer mock_getselectedobjectnames.return_value = (u'P1', u'P2', u'P3') mock_mapcanvas = mock_iface.mapCanvas.return_value mock_mapcanvas.layerCount.return_value = 0 midvatten.plot_section() myplot = midvatten.myplot myplot.drillstoplineEdit.setText(u"%berg%") myplot.draw_plot() return myplot myplot = _test(self.midvatten, self.vlayer) test_string = utils_for_tests.create_test_string(myplot.LengthAlong) assert any( [test_string == u"[ 1. 3. 5.]", test_string == u"[1. 3. 5.]"]) assert mock.call.info( log_msg= u'Hidden features, obsids and length along section:\nP1;P2;P3\\1.0;3.0;5.0' ) in mock_messagebar.mock_calls assert not mock_messagebar.warning.called assert not mock_messagebar.critical.called def tearDown(self): QgsMapLayerRegistry.instance().addMapLayer(self.vlayer) QgsMapLayerRegistry.instance().removeMapLayer(self.vlayer.id()) super(self.__class__, self).tearDown()
def eliminate(self, inLayer, boundary, progressBar, outFileName): # keep references to the features to eliminate fidsToEliminate = inLayer.selectedFeaturesIds() if outFileName: # user wants a new shape file to be created as result provider = inLayer.dataProvider() error = QgsVectorFileWriter.writeAsVectorFormat( inLayer, outFileName, provider.encoding(), inLayer.crs(), "ESRI Shapefile") if error != QgsVectorFileWriter.NoError: QMessageBox.warning(self, self.tr("Eliminate"), self.tr("Error creating output file")) return None outLayer = QgsVectorLayer( outFileName, QFileInfo(outFileName).completeBaseName(), "ogr") else: QMessageBox.information(self, self.tr("Eliminate"), self.tr("Please specify output shapefile")) return None # delete features to be eliminated in outLayer outLayer.setSelectedFeatures(fidsToEliminate) outLayer.startEditing() if outLayer.deleteSelectedFeatures(): if self.saveChanges(outLayer): outLayer.startEditing() else: QMessageBox.warning(self, self.tr("Eliminate"), self.tr("Could not delete features")) return None # ANALYZE start = 20.00 progressBar.setValue(start) add = 80.00 / len(fidsToEliminate) lastLen = 0 # we go through the list and see if we find any polygons we can merge the selected with # if we have no success with some we merge and then restart the whole story while (lastLen != inLayer.selectedFeatureCount() ): # check if we made any progress lastLen = inLayer.selectedFeatureCount() fidsToDeselect = [] #iterate over the polygons to eliminate for fid2Eliminate in inLayer.selectedFeaturesIds(): feat = QgsFeature() if inLayer.getFeatures(QgsFeatureRequest().setFilterFid( fid2Eliminate).setSubsetOfAttributes( [])).nextFeature(feat): geom2Eliminate = feat.geometry() bbox = geom2Eliminate.boundingBox() fit = outLayer.getFeatures( QgsFeatureRequest().setFilterRect(bbox)) mergeWithFid = None mergeWithGeom = None max = 0 selFeat = QgsFeature() while fit.nextFeature(selFeat): selGeom = selFeat.geometry() if geom2Eliminate.intersects( selGeom): # we have a candidate iGeom = geom2Eliminate.intersection(selGeom) if boundary: selValue = iGeom.length() else: # we need a common boundary if 0 < iGeom.length(): selValue = selGeom.area() else: selValue = 0 if selValue > max: max = selValue mergeWithFid = selFeat.id() mergeWithGeom = QgsGeometry( selGeom) # deep copy of the geometry if mergeWithFid is not None: # a successful candidate newGeom = mergeWithGeom.combine(geom2Eliminate) if outLayer.changeGeometry(mergeWithFid, newGeom): # write change back to disc if self.saveChanges(outLayer): outLayer.startEditing() else: return None # mark feature as eliminated in inLayer fidsToDeselect.append(fid2Eliminate) else: QMessageBox.warning( self, self.tr("Eliminate"), self. tr("Could not replace geometry of feature with id %s" ) % (mergeWithFid)) return None start = start + add progressBar.setValue(start) # end for fid2Eliminate # deselect features that are already eliminated in inLayer inLayer.deselect(fidsToDeselect) #end while if inLayer.selectedFeatureCount() > 0: # copy all features that could not be eliminated to outLayer if outLayer.addFeatures(inLayer.selectedFeatures()): # inform user fidList = "" for fid in inLayer.selectedFeaturesIds(): if not fidList == "": fidList += ", " fidList += unicode(fid) QMessageBox.information( self, self.tr("Eliminate"), self.tr("Could not eliminate features with these ids:\n%s") % (fidList)) else: QMessageBox.warning(self, self.tr("Eliminate"), self.tr("Could not add features")) # stop editing outLayer and commit any pending changes if not self.saveChanges(outLayer): return None if outFileName: if self.addToCanvasCheck.isChecked(): ftools_utils.addShapeToCanvas(outFileName) else: QMessageBox.information( self, self.tr("Eliminate"), self.tr("Created output shapefile:\n%s") % (outFileName)) self.iface.mapCanvas().refresh()
class TestStratigraphy(utils_for_tests.MidvattenTestPostgisDbSv): @mock.patch('db_utils.QgsProject.instance', utils_for_tests. MidvattenTestPostgisNotCreated.mock_instance_settings_database) @mock.patch( 'db_utils.get_postgis_connections', utils_for_tests.MidvattenTestPostgisNotCreated.mock_postgis_connections ) def create_and_select_vlayer(self): self.qgs = QgsApplication([], True) self.qgs.initQgis() self.midvatten.ms.settingsdict['secplotdrillstop'] = u"%berg%" dbconnection = db_utils.DbConnectionManager() uri = dbconnection.uri uri.setDataSource('', 'obs_points', 'geometry', '', 'obsid') dbtype = db_utils.get_dbtype(dbconnection.dbtype) self.vlayer = QgsVectorLayer(uri.uri(), 'TestLayer', dbtype) features = self.vlayer.getFeatures() feature_ids = [feature.id() for feature in features] self.vlayer.setSelectedFeatures(feature_ids) @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) @mock.patch('db_utils.QgsProject.instance', utils_for_tests. MidvattenTestPostgisNotCreated.mock_instance_settings_database) @mock.patch( 'db_utils.get_postgis_connections', utils_for_tests.MidvattenTestPostgisNotCreated.mock_postgis_connections ) def test_stratigraphy(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ db_utils.sql_alter_db( u'''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('P1', 5, ST_GeomFromText('POINT(633466 711659)', 3006))''' ) db_utils.sql_alter_db( u'''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('P2', 10, ST_GeomFromText('POINT(6720727 016568)', 3006))''' ) db_utils.sql_alter_db( u'''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('P3', 20, ST_GeomFromText('POINT(6720728 016569)', 3006))''' ) db_utils.sql_alter_db( u'''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('P1', 1, 0, 1, 'sand', 'sand', '3', 'j')''' ) db_utils.sql_alter_db( u'''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('P1', 2, 1, 4.5, 'morän', 'morän', '3', 'j')''' ) self.create_and_select_vlayer() print(str(self.vlayer.isValid())) print(str(db_utils.sql_load_fr_db(u'select * from obs_points'))) print(str(db_utils.sql_load_fr_db(u'select * from stratigraphy'))) dlg = Stratigraphy(self.iface, self.vlayer, self.ms.settingsdict) print(str(mock_messagebar.mock_calls)) print(str(mock_skippopup.mock_calls)) dlg.showSurvey() test = utils.anything_to_string_representation(dlg.data) test_survey = utils.anything_to_string_representation( repr(dlg.data[u'P1'])) test_strata = utils.anything_to_string_representation( utils.returnunicode(dlg.data[u'P1'].strata, keep_containers=True)) assert len(mock_skippopup.mock_calls) == 0 print(str(mock_messagebar.mock_calls)) assert len(mock_messagebar.mock_calls) == 0 assert test == u"""{u"P1": SURVEY('P1', 5.000000, '(633466,711659)')}""" assert test_survey == u'''"SURVEY('P1', 5.000000, '(633466,711659)')"''' assert test_strata == u'''[u"strata(1, '3', 'sand', 'sand', 0.000000-1.000000)", u"strata(2, '3', 'morän', 'moran', 1.000000-4.500000)"]''' @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) @mock.patch('db_utils.QgsProject.instance', utils_for_tests. MidvattenTestPostgisNotCreated.mock_instance_settings_database) @mock.patch( 'db_utils.get_postgis_connections', utils_for_tests.MidvattenTestPostgisNotCreated.mock_postgis_connections ) def test_stratigraphy_gap(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ db_utils.sql_alter_db( u'''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('P1', 5, ST_GeomFromText('POINT(633466 711659)', 3006))''' ) db_utils.sql_alter_db( u'''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('P2', 10, ST_GeomFromText('POINT(6720727 016568)', 3006))''' ) db_utils.sql_alter_db( u'''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('P3', 20, ST_GeomFromText('POINT(6720728 016569)', 3006))''' ) db_utils.sql_alter_db( u'''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('P1', 1, 0, 1, 'sand', 'sand', '3', 'j')''' ) db_utils.sql_alter_db( u'''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('P1', 2, 2, 4.5, 'morän', 'morän', '3', 'j')''' ) self.create_and_select_vlayer() print(str(self.vlayer.isValid())) print(str(db_utils.sql_load_fr_db(u'select * from obs_points'))) print(str(db_utils.sql_load_fr_db(u'select * from stratigraphy'))) dlg = Stratigraphy(self.iface, self.vlayer, self.ms.settingsdict) print(str(mock_messagebar.mock_calls)) print(str(mock_skippopup.mock_calls)) dlg.showSurvey() test = utils.anything_to_string_representation(dlg.data) test_survey = utils.anything_to_string_representation( repr(dlg.data[u'P1'])) test_strata = utils.anything_to_string_representation( utils.returnunicode(dlg.data[u'P1'].strata, keep_containers=True)) assert len(mock_skippopup.mock_calls) == 0 assert len(mock_messagebar.mock_calls) == 0 assert test == u"""{u"P1": SURVEY('P1', 5.000000, '(633466,711659)')}""" assert test_survey == u'''"SURVEY('P1', 5.000000, '(633466,711659)')"''' assert test_strata == u'''[u"strata(1, '3', 'sand', 'sand', 0.000000-1.000000)", u"strata(2, '', '', '', 1.000000-2.000000)", u"strata(3, '3', 'morän', 'moran', 2.000000-4.500000)"]''' @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) @mock.patch('db_utils.QgsProject.instance', utils_for_tests. MidvattenTestPostgisNotCreated.mock_instance_settings_database) @mock.patch( 'db_utils.get_postgis_connections', utils_for_tests.MidvattenTestPostgisNotCreated.mock_postgis_connections ) def test_stratigraphy_missing_h_gs(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ db_utils.sql_alter_db( u'''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('P1', 5, ST_GeomFromText('POINT(633466 711659)', 3006))''' ) db_utils.sql_alter_db( u'''INSERT INTO obs_points (obsid, h_gs, h_toc, geometry) VALUES ('P2', NULL, 10, ST_GeomFromText('POINT(6720727 016568)', 3006))''' ) db_utils.sql_alter_db( u'''INSERT INTO obs_points (obsid, geometry) VALUES ('P3', ST_GeomFromText('POINT(6720728 016569)', 3006))''' ) db_utils.sql_alter_db( u'''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('P1', 1, 0, 1, 'sand', 'sand', '3', 'j')''' ) db_utils.sql_alter_db( u'''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('P1', 2, 1, 4.5, 'morän', 'morän', '3', 'j')''' ) db_utils.sql_alter_db( u'''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('P2', 1, 0, 1, 'sand', 'sand', '3', 'j')''' ) db_utils.sql_alter_db( u'''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('P2', 2, 1, 4.5, 'morän', 'morän', '3', 'j')''' ) db_utils.sql_alter_db( u'''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('P3', 1, 0, 2, 'sand', 'sand', '3', 'j')''' ) db_utils.sql_alter_db( u'''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('P3', 2, 2, 6, 'morän', 'morän', '3', 'j')''' ) self.create_and_select_vlayer() dlg = Stratigraphy(self.iface, self.vlayer, self.ms.settingsdict) dlg.showSurvey() test = utils.anything_to_string_representation(dlg.data) test_survey = utils.anything_to_string_representation( repr(dlg.data[u'P1'])) test_strata = utils.anything_to_string_representation( utils.returnunicode(dlg.data[u'P1'].strata, keep_containers=True)) assert len(mock_skippopup.mock_calls) == 1 print(str(mock_skippopup.mock_calls)) print(str(mock_messagebar.mock_calls)) assert mock_skippopup.mock_calls == [ mock.call(u'Warning, h_gs is missing. See messagebar.') ] assert mock_messagebar.mock_calls == [ mock.call.warning( bar_msg= u"Obsid P2: using h_gs '' failed, using 'h_toc' instead.", duration=90, log_msg=u'False'), mock.call.warning( bar_msg=u"Obsid P3: using h_gs '' failed, using '-1' instead.", duration=90, log_msg=u'False') ] print(test) assert test == u"""{u"P1": SURVEY('P1', 5.000000, '(633466,711659)'), u"P2": SURVEY('P2', 10.000000, '(6.72073e+06,16568)'), u"P3": SURVEY('P3', -1.000000, '(6.72073e+06,16569)')}""" assert test_survey == u'''"SURVEY('P1', 5.000000, '(633466,711659)')"''' print("Test strata " + test_strata) assert test_strata == u'''[u"strata(1, '3', 'sand', 'sand', 0.000000-1.000000)", u"strata(2, '3', 'morän', 'moran', 1.000000-4.500000)"]''' def tearDown(self): QgsMapLayerRegistry.instance().addMapLayer(self.vlayer) QgsMapLayerRegistry.instance().removeMapLayer(self.vlayer.id()) super(self.__class__, self).tearDown()
class TestSectionPlot(object): """ The test doesn't go through the whole section plot unfortunately """ answer_yes = mock_answer('yes') answer_no = mock_answer('no') crs_question = MockUsingReturnValue([3006]) mocked_iface = MockQgisUtilsIface() #Used for not getting messageBar errors mock_askuser = MockReturnUsingDictIn({u'It is a strong': answer_no.get_v(), u'Please note!\nThere are ': answer_yes.get_v()}, 1) skip_popup = MockUsingReturnValue('') @mock.patch('create_db.utils.NotFoundQuestion') @mock.patch('midvatten_utils.askuser', answer_yes.get_v) @mock.patch('midvatten_utils.QgsProject.instance') @mock.patch('create_db.PyQt4.QtGui.QInputDialog.getInteger') @mock.patch('create_db.PyQt4.QtGui.QFileDialog.getSaveFileName') def setUp(self, mock_savefilename, mock_crsquestion, mock_qgsproject_instance, mock_locale): mock_crsquestion.return_value = [3006] mock_savefilename.return_value = TEMP_DB_PATH mock_qgsproject_instance.return_value.readEntry = MIDV_DICT self.dummy_iface = DummyInterface2() self.iface = self.dummy_iface.mock self.midvatten = midvatten(self.iface) try: os.remove(TEMP_DB_PATH) except OSError: pass mock_locale.return_value.answer = u'ok' mock_locale.return_value.value = u'sv_SE' self.midvatten.new_db() self.midvatten.ms.settingsareloaded = True def tearDown(self): #Delete database try: os.remove(TEMP_DB_PATH) except OSError: pass @mock.patch('midvatten_utils.QgsProject.instance') def test_plot_section(self, mock_qgsproject_instance): mock_qgsproject_instance.return_value.readEntry = MIDV_DICT """For now, the test only initiates the plot. Check that it does not crash """ utils.sql_alter_db(u'''insert into obs_lines (obsid, geometry) values ("L1", GeomFromText('LINESTRING(633466.711659 6720684.24498, 633599.530455 6720727.016568)', 3006))''') utils.sql_alter_db(u'''insert into obs_points (obsid, geometry) values ("P1", GeomFromText('POINT(633466, 711659)', 3006))''') utils.sql_alter_db(u'''insert into obs_points (obsid, geometry) values ("P2", GeomFromText('POINT(6720727, 016568)', 3006))''') utils.sql_alter_db(u'''insert into obs_points (obsid, geometry) values ("P3", GeomFromText('POINT(6720728, 016569)', 3006))''') uri = QgsDataSourceURI() uri.setDatabase(TEMP_DB_PATH) uri.setDataSource('', 'obs_lines', 'geometry', '', 'obsid') self.vlayer = QgsVectorLayer(uri.uri(), 'TestLayer', 'spatialite') features = self.vlayer.getFeatures() for feature in features: featureid = feature.id() self.vlayer.setSelectedFeatures([featureid]) @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True) @mock.patch('qgis.utils.iface', autospec=True) def _test_plot_section(self, mock_iface, mock_getselectedobjectnames): mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer mock_getselectedobjectnames.return_value = (u'P1', u'P2', u'P3') mock_mapcanvas = mock_iface.mapCanvas.return_value mock_mapcanvas.layerCount.return_value = 0 self.midvatten.plot_section() self.myplot = self.midvatten.myplot self.myplot.drillstoplineEdit.setText(u"%berg%") self.myplot.draw_plot() self.selected_obsids = self.myplot.selected_obsids _test_plot_section(self) assert self.myplot.drillstoplineEdit.text() == u'%berg%' assert utils_for_tests.create_test_string(self.myplot.selected_obsids) == "['P1' 'P2' 'P3']" @mock.patch('midvatten_utils.QgsProject.instance') def test_plot_section_with_depth(self, mock_qgsproject_instance): mock_qgsproject_instance.return_value.readEntry = MIDV_DICT utils.sql_alter_db(u'''insert into obs_lines (obsid, geometry) values ("L1", GeomFromText('LINESTRING(633466.711659 6720684.24498, 633599.530455 6720727.016568)', 3006))''') utils.sql_alter_db(u'''insert into obs_points (obsid, geometry, length) values ("P1", GeomFromText('POINT(633466, 711659)', 3006), 2)''') utils.sql_alter_db(u'''insert into obs_points (obsid, geometry, length) values ("P2", GeomFromText('POINT(6720727, 016568)', 3006), "1")''') utils.sql_alter_db(u'''insert into obs_points (obsid, geometry, length) values ("P3", GeomFromText('POINT(6720727, 016568)', 3006), NULL)''') uri = QgsDataSourceURI() uri.setDatabase(TEMP_DB_PATH) uri.setDataSource('', 'obs_lines', 'geometry', '', 'obsid') self.vlayer = QgsVectorLayer(uri.uri(), 'TestLayer', 'spatialite') features = self.vlayer.getFeatures() for feature in features: featureid = feature.id() self.vlayer.setSelectedFeatures([featureid]) @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True) @mock.patch('qgis.utils.iface', autospec=True) def _test_plot_section_with_depth(self, mock_iface, mock_getselectedobjectnames): mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer mock_getselectedobjectnames.return_value = (u'P1', u'P2', u'P3') mock_mapcanvas = mock_iface.mapCanvas.return_value mock_mapcanvas.layerCount.return_value = 0 self.midvatten.plot_section() _test_plot_section_with_depth(self) @mock.patch('midvatten_utils.QgsProject.instance') def test_plot_section_with_w_levels(self, mock_qgsproject_instance): mock_qgsproject_instance.return_value.readEntry = MIDV_DICT utils.sql_alter_db(u'''insert into obs_lines (obsid, geometry) values ("L1", GeomFromText('LINESTRING(633466.711659 6720684.24498, 633599.530455 6720727.016568)', 3006))''') utils.sql_alter_db(u'''insert into obs_points (obsid, geometry, length) values ("P1", GeomFromText('POINT(633466, 711659)', 3006), 2)''') utils.sql_alter_db(u'''insert into obs_points (obsid, geometry, length) values ("P2", GeomFromText('POINT(6720727, 016568)', 3006), "1")''') utils.sql_alter_db(u'''insert into obs_points (obsid, geometry, length) values ("P3", GeomFromText('POINT(6720727, 016568)', 3006), NULL)''') utils.sql_alter_db(u'''insert into w_levels (obsid, date_time, meas, h_toc, level_masl) values ("P1", "2015-01-01 00:00:00", "15", "200", "185")''') utils.sql_alter_db(u'''insert into w_levels (obsid, date_time, meas, h_toc, level_masl) values ("P2", "2015-01-01 00:00:00", "17", "200", "183")''') uri = QgsDataSourceURI() uri.setDatabase(TEMP_DB_PATH) uri.setDataSource('', 'obs_lines', 'geometry', '', 'obsid') self.vlayer = QgsVectorLayer(uri.uri(), 'TestLayer', 'spatialite') features = self.vlayer.getFeatures() for feature in features: featureid = feature.id() self.vlayer.setSelectedFeatures([featureid]) @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True) @mock.patch('qgis.utils.iface', autospec=True) def _test_plot_section_with_depth(self, mock_iface, mock_getselectedobjectnames): mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer mock_getselectedobjectnames.return_value = (u'P1', u'P2', u'P3') mock_mapcanvas = mock_iface.mapCanvas.return_value mock_mapcanvas.layerCount.return_value = 0 self.midvatten.plot_section() _test_plot_section_with_depth(self)
class islh_parser: """QGIS Plugin Implementation.""" def __init__(self, iface): """Constructor. :param iface: An interface instance that will be passed to this class which provides the hook by which you can manipulate the QGIS application at run time. :type iface: QgsInterface """ # Save reference to the QGIS interface self.iface = iface # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join( self.plugin_dir, 'i18n', 'islh_parser_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Declare instance attributes self.actions = [] self.menu = self.tr(u'&LHPO data viewer') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'islh_parser') self.toolbar.setObjectName(u'islh_parser') #print "** INITIALIZING islh_parser" self.pluginIsActive = False self.dockwidget = None self.hk_widget = None # noinspection PyMethodMayBeStatic def tr(self, message): """Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject. :param message: String for translation. :type message: str, QString :returns: Translated version of message. :rtype: QString """ # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return QCoreApplication.translate('islh_parser', message) def add_action( self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): """Add a toolbar icon to the toolbar. :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :type icon_path: str :param text: Text that should be shown in menu items for this action. :type text: str :param callback: Function to be called when the action is triggered. :type callback: function :param enabled_flag: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled_flag: bool :param add_to_menu: Flag indicating whether the action should also be added to the menu. Defaults to True. :type add_to_menu: bool :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar. Defaults to True. :type add_to_toolbar: bool :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action. :type status_tip: str :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :returns: The action that was created. Note that the action is also added to self.actions list. :rtype: QAction """ icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: self.toolbar.addAction(action) if add_to_menu: self.iface.addPluginToMenu( self.menu, action) self.actions.append(action) return action def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" icon_path = ':/plugins/islh_parser/icon.png' self.add_action( icon_path, text=self.tr(u'ISLH'), callback=self.run, parent=self.iface.mainWindow()) #-------------------------------------------------------------------------- def onClosePlugin(self): """Cleanup necessary items here when plugin dockwidget is closed""" #print "** CLOSING islh_parser" # disconnects self.dockwidget.closingPlugin.disconnect(self.onClosePlugin) # remove this statement if dockwidget is to remain # for reuse if plugin is reopened # Commented next statement since it causes QGIS crashe # when closing the docked window: self.dockwidget = None self.pluginIsActive = False del(self.psk_layer) del(self.klo_layer) del(self.kto_layer) del(self.kpo_layer) del(self.kbo_layer) del(self.bzl_layer) del(self.jp_layer) del(self.op_layer) del(self.doc) del(self.root) del(barva) del(znacka) self = None def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" #print "** UNLOAD islh_parser" for action in self.actions: self.iface.removePluginMenu( self.tr(u'&LHPO data viewer'), action) self.iface.removeToolBarIcon(action) # remove the toolbar del self.toolbar #smaze fci znacka #del islh_parser.znacka #-------------------------------------------------------------------------- #widget functions #-------------------------------------------------------------------------- def select_input_xml(self): filename = QFileDialog.getOpenFileName(self.dockwidget, "Select ISLH XML file ","", '*.xml') self.dockwidget.input_file.setText(filename) def read_islh(self): os.chdir(self.plugin_dir) #musim do plugin diru, abysem nacet svg if not self.dockwidget.input_file.text(): QMessageBox.critical(QDialog() ,u"Missing file",u"Není vybrán žádný soubor") else: self.f = open(self.dockwidget.input_file.text()) try: #nachroustam xml self.dockwidget.output_working_on.setText(u"načítám XML") self.load_xml() except: QMessageBox.critical(QDialog() ,u"vadný soubor",u"soubor se nepodařilo načíst") #pridam skupinu self.layerTreeRoot = QgsProject.instance().layerTreeRoot() self.por_mapa_group = self.layerTreeRoot.insertGroup(0, u'Porostní mapa') #self.psk_layer = self.iface.addVectorLayer('MultiPolygon' self.psk_layer = QgsVectorLayer('MultiPolygon' , 'PSK', 'memory') self.psk_layer.loadNamedStyle('styles/por_mapa.qml') #self.crs = self.psk_layer.crs() #self.crs.createFromId(5514) #self.psk_layer.setCrs(self.crs) self.crs = QgsCoordinateReferenceSystem() self.crs.createFromId(5514) self.psk_layer.setCrs(self.crs) self.dockwidget.output_working_on.setText(u"generuji vrstvu PSK") try: self.populate_layer('ODD/DIL/POR/PSK', self.psk_layer) #pridam index self.psk_index = QgsSpatialIndex() for f in self.psk_layer.getFeatures(): self.psk_index.insertFeature(f) QgsMapLayerRegistry.instance().addMapLayer(self.psk_layer, False) self.por_mapa_group.addLayer(self.psk_layer) except: QMessageBox.critical(QDialog() ,u"Nevhodný formát dat",u"nepodařilo se vytvořit vrstvu PSK") #kpo self.kpo_layer = QgsVectorLayer('Multipolygon' , 'KPO', 'memory') self.kpo_layer.loadNamedStyle('styles/por_mapa_kpo.qml') self.kpo_layer.setCrs(self.crs) self.dockwidget.output_working_on.setText(u"generuji vrstvu KPO") try: self.populate_layer('KPO', self.kpo_layer) #index nepridam, je to jen kartoska QgsMapLayerRegistry.instance().addMapLayer(self.kpo_layer, False) #self.por_mapa_group.addLayer(self.kpo_layer) self.por_mapa_group.insertLayer(0, self.kpo_layer) except: QMessageBox.critical(QDialog() ,u"Chyba vytváření KPO",u"nepodařilo se vytvořit vrstvu KPO") #----- #klo self.klo_layer = QgsVectorLayer('Linestring' , 'KLO', 'memory') self.klo_layer.loadNamedStyle('styles/porostni_mapa_linie.qml') self.klo_layer.setCrs(self.crs) self.dockwidget.output_working_on.setText(u"generuji vrstvu KLO") try: self.populate_layer('KLO', self.klo_layer) #index nepridam, je to jen kartoska QgsMapLayerRegistry.instance().addMapLayer(self.klo_layer, False) #self.por_mapa_group.addLayer(self.klo_layer) self.por_mapa_group.insertLayer(0, self.klo_layer) except: QMessageBox.critical(QDialog() ,u"Chyba vytváření KLO",u"nepodařilo se vytvořit vrstvu KLO") #----- #kbo self.kbo_layer = QgsVectorLayer('MultiPoint' , 'KBO', 'memory') self.kbo_layer.loadNamedStyle('styles/styly_body.qml') self.kbo_layer.setCrs(self.crs) self.dockwidget.output_working_on.setText(u"generuji vrstvu KBO") try: self.populate_layer('KBO', self.kbo_layer) #index nepridam, je to jen kartoska QgsMapLayerRegistry.instance().addMapLayer(self.kbo_layer, False) #self.por_mapa_group.addLayer(self.kbo_layer) self.por_mapa_group.insertLayer(0, self.kbo_layer) except: QMessageBox.critical(QDialog() ,u"Chyba vytváření KBO",u"nepodařilo se vytvořit vrstvu KBO") #----- #kto self.kto_layer = QgsVectorLayer('Point' , 'KTO', 'memory') self.kto_layer.loadNamedStyle('styles/styly_txt.qml') self.kto_layer.setCrs(self.crs) self.dockwidget.output_working_on.setText(u"generuji vrstvu KTO") try: self.populate_layer('KTO', self.kto_layer) #index nepridam, je to jen kartoska QgsMapLayerRegistry.instance().addMapLayer(self.kto_layer, False) #self.por_mapa_group.addLayer(self.kto_layer) self.por_mapa_group.insertLayer(0, self.kto_layer) except: QMessageBox.critical(QDialog() ,u"Chyba vytváření KTO",u"nepodařilo se vytvořit vrstvu KTO") #----- #BZL JP OP #skupina self.bzl_jp_op_mapa_group = self.layerTreeRoot.insertGroup(1, u'BZL, JP, OP') #----- #bzl self.bzl_layer = QgsVectorLayer('Multipolygon' , 'BZL', 'memory') #self.psk_layer.loadNamedStyle('styles/por_mapa.qml') self.bzl_layer.setCrs(self.crs) self.dockwidget.output_working_on.setText(u"generuji vrstvu BZL") try: self.populate_layer('ODD/DIL/POR/BZL', self.bzl_layer) #index nepridam, je to jen kartoska QgsMapLayerRegistry.instance().addMapLayer(self.bzl_layer, False) #self.por_mapa_group.addLayer(self.bzl_layer) self.bzl_jp_op_mapa_group.insertLayer(0, self.bzl_layer) except: QMessageBox.critical(QDialog() ,u"Chyba vytváření BZL",u"nepodařilo se vytvořit vrstvu BZL") #------ #jp self.jp_layer = QgsVectorLayer('Multipolygon' , 'JP', 'memory') #self.psk_layer.loadNamedStyle('styles/por_mapa.qml') self.jp_layer.setCrs(self.crs) self.dockwidget.output_working_on.setText(u"generuji vrstvu JP") self.populate_layer('ODD/DIL/POR/JP', self.jp_layer) #index nepridam, je to jen kartoska QgsMapLayerRegistry.instance().addMapLayer(self.jp_layer, False) #self.por_mapa_group.addLayer(self.jp_layer) self.bzl_jp_op_mapa_group.insertLayer(0, self.jp_layer) try: a=1 except: QMessageBox.critical(QDialog() ,u"Chyba vytváření JP",u"nepodařilo se vytvořit vrstvu JP") #------ #op self.op_layer = QgsVectorLayer('Multipolygon' , 'OP', 'memory') #self.psk_layer.loadNamedStyle('styles/por_mapa.qml') self.op_layer.setCrs(self.crs) self.dockwidget.output_working_on.setText(u"generuji vrstvu OP") #try: self.populate_layer('ODD/DIL/POR/OP', self.op_layer) #index nepridam, je to jen kartoska QgsMapLayerRegistry.instance().addMapLayer(self.op_layer, False) #self.por_mapa_group.addLayer(self.op_layer) self.bzl_jp_op_mapa_group.insertLayer(0, self.op_layer) try: a=1 except: QMessageBox.critical(QDialog() ,u"Chyba vytváření OP",u"nepodařilo se vytvořit vrstvu OP") #------ self.bzl_jp_op_mapa_group.setVisible(Qt.Unchecked) lhc_list = [self.lhc.get('LHC_KOD')] self.dockwidget.input_lhc.clear() self.dockwidget.input_lhc.addItems(lhc_list) #nastavit komba na zacatek self.select_lhc() self.select_odd() self.select_dil() self.select_por() self.select_psk() def select_lhc(self): self.dockwidget.input_odd.clear() self.dockwidget.input_dil.clear() self.dockwidget.input_por.clear() self.dockwidget.input_psk.clear() self.dockwidget.input_odd.addItems( [ odd.get('ODD') for odd in self.lhc.xpath('ODD')] ) def select_odd(self): self.odd = self.lhc.find("ODD[@ODD='%s']"%self.dockwidget.input_odd.currentText()) self.dockwidget.input_dil.clear() self.dockwidget.input_por.clear() self.dockwidget.input_psk.clear() self.dockwidget.input_dil.addItems( [ dil.get('DIL') for dil in self.odd.xpath('DIL')] ) self.jprl = ( self.lhc.get('LHC_KOD') , self.odd.get('ODD')) #zrus vybrane graficky self.psk_layer.setSelectedFeatures([]) #vyber request = QgsFeatureRequest().setFilterExpression( "lhc_kod = '%s' AND odd = '%s'"% self.jprl) it = self.psk_layer.getFeatures( request ) self.psk_layer.setSelectedFeatures([f.id() for f in it]) box = self.psk_layer.boundingBoxOfSelected() self.iface.mapCanvas().setExtent(box) self.iface.mapCanvas().refresh() def select_dil(self): self.dil = self.odd.find("DIL[@DIL='%s']"%self.dockwidget.input_dil.currentText()) self.dockwidget.input_por.clear() self.dockwidget.input_psk.clear() self.dockwidget.input_por.addItems( [ por.get('POR') for por in self.dil.xpath('POR')] ) self.jprl = ( self.lhc.get('LHC_KOD') , self.odd.get('ODD') , self.dil.get('DIL')) #zrus vybrane graficky self.psk_layer.setSelectedFeatures([]) #vyber request = QgsFeatureRequest().setFilterExpression( "lhc_kod = '%s' AND odd = '%s' AND dil ='%s'"% self.jprl) it = self.psk_layer.getFeatures( request ) self.psk_layer.setSelectedFeatures([f.id() for f in it]) box = self.psk_layer.boundingBoxOfSelected() self.iface.mapCanvas().setExtent(box) self.iface.mapCanvas().refresh() def select_por(self): self.por = self.dil.find("POR[@POR='%s']"%self.dockwidget.input_por.currentText()) self.dockwidget.input_psk.clear() self.dockwidget.input_psk.addItems( [ psk.get('PSK') for psk in self.por.xpath('PSK')] ) self.jprl = ( self.lhc.get('LHC_KOD') , self.odd.get('ODD') , self.dil.get('DIL') , self.por.get('POR')) #zrus vybrane graficky self.psk_layer.setSelectedFeatures([]) #vyber request = QgsFeatureRequest().setFilterExpression( "lhc_kod = '%s' AND odd = '%s' AND dil ='%s' AND por = '%s'"% self.jprl) it = self.psk_layer.getFeatures( request ) self.psk_layer.setSelectedFeatures([f.id() for f in it]) box = self.psk_layer.boundingBoxOfSelected() self.iface.mapCanvas().setExtent(box) self.iface.mapCanvas().refresh() #self.select_psk() #workaround kvuli def select_psk(self): self.psk = self.por.find("PSK[@PSK='%s']"%self.dockwidget.input_psk.currentText()) self.jprl = ( self.lhc.get('LHC_KOD') , self.odd.get('ODD') , self.dil.get('DIL') , self.por.get('POR') , self.psk.get('PSK')) #zrus vybrane graficky self.psk_layer.setSelectedFeatures([]) #vyber request = QgsFeatureRequest().setFilterExpression( "lhc_kod = '%s' AND odd = '%s' AND dil ='%s' AND por = '%s' AND psk = '%s'"% self.jprl) it = self.psk_layer.getFeatures( request ) self.psk_layer.setSelectedFeatures([f.id() for f in it]) box = self.psk_layer.boundingBoxOfSelected() self.iface.mapCanvas().setExtent(box) self.iface.mapCanvas().refresh() def show_hk(self): #nejdriv zjistim, jestli je vybrany nejaky prvek graficky #pak musim u vyberu pomoci roletek dat odselektovani vseho if len(self.psk_layer.selectedFeatures()) == 0 and len(self.jprl) < 5: QMessageBox.critical(QDialog() ,u"Chyba výběru",u"Není vybrána žádná porostní skupina") return(None) if len(self.psk_layer.selectedFeatures()) > 0: #musi bejt prave jeden #kdyz je jich vic, vem prvni selected_psk = self.psk_layer.selectedFeatures()[0] self.jprl = (selected_psk['lhc_kod'] , selected_psk['odd'] , selected_psk['dil'] , selected_psk['por'] , selected_psk['psk']) #nastavim comba index = self.dockwidget.input_lhc.findText(selected_psk['lhc_kod']) if index >= 0: self.dockwidget.input_lhc.setCurrentIndex(index) self.select_lhc() index = self.dockwidget.input_odd.findText(selected_psk['odd']) if index >= 0: self.dockwidget.input_odd.setCurrentIndex(index) self.select_odd() index = self.dockwidget.input_dil.findText(selected_psk['dil']) if index >= 0: self.dockwidget.input_dil.setCurrentIndex(index) self.select_dil() index = self.dockwidget.input_por.findText(selected_psk['por']) if index >= 0: self.dockwidget.input_por.setCurrentIndex(index) self.select_por() index = self.dockwidget.input_psk.findText(selected_psk['psk']) if index >= 0: self.dockwidget.input_psk.setCurrentIndex(index) self.select_psk() #self.psk_layer.setSelectedFeatures([]) if self.hk_widget == None: self.hk_widget = hk_displayDockWidget() self.iface.addDockWidget(Qt.TopDockWidgetArea, self.hk_widget) self.result = self.transform(self.root , ODD="'%s'"%self.jprl[1] , DIL="'%s'"%self.jprl[2] , POR="'%s'"%self.jprl[3] , PSK="'%s'"%self.jprl[4]) self.hk_widget.webView.setHtml( etree.tostring(self.result) ) self.hk_widget.show() #-------------------------------------------------------------------------- def run(self): """Run method that loads and starts the plugin""" if not self.pluginIsActive: self.pluginIsActive = True #print "** STARTING islh_parser" # dockwidget may not exist if: # first run of plugin # removed on close (see self.onClosePlugin method) if self.dockwidget == None: # Create the dockwidget (after translation) and keep reference self.dockwidget = islh_parserDockWidget() # connect to provide cleanup on closing of dockwidget self.dockwidget.closingPlugin.connect(self.onClosePlugin) # show the dockwidget # TODO: fix to allow choice of dock location self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dockwidget) self.dockwidget.show() #buttons actions self.dockwidget.input_file.clear() self.dockwidget.input_file_button.clicked.connect(self.select_input_xml) self.dockwidget.input_read.clicked.connect(self.read_islh) self.dockwidget.input_lhc.activated.connect(self.select_lhc) self.dockwidget.input_odd.activated.connect(self.select_odd) self.dockwidget.input_dil.activated.connect(self.select_dil) self.dockwidget.input_por.activated.connect(self.select_por) self.dockwidget.input_psk.activated.connect(self.select_psk) self.dockwidget.input_hk_button.clicked.connect(self.show_hk) #load xslt stuff self.ns = etree.FunctionNamespace("http://ciselniky") self.ns.prefix = "cis" self.ns['lesni_oblast'] = ciselniky.lesni_oblast self.ns['slt'] = ciselniky.slt self.ns['katuze'] = ciselniky.katuze self.ns['lvs'] = ciselniky.lvs self.ns['zvl_statut'] = ciselniky.zvl_statut self.xslt_root = etree.XML(open('%s/xslt/hk.xsl'%self.plugin_dir,'r').read()) self.transform = etree.XSLT(self.xslt_root) #nastavim barvu na neco, co neni v por mape self.iface.mapCanvas().setSelectionColor(QColor('#f40')) from karto_fce import * #---------------------------------------------------- #plugin logic def load_xml(self): """:param f: file with islh xml data""" self.doc = etree.parse(self.f) self.root = self.doc.getroot() self.lhc = self.root.find("./LHC") def populate_layer(self, PATH, layer): """return layer with psk as geoJSON""" layer_data = self.lhc.xpath(PATH) if not layer_data: return(None) featureCount = len(layer_data) self.dockwidget.progressBar.setRange(0, featureCount) self.progres = iter(range(0, featureCount)) pr = layer.dataProvider() attnames = [k for k in layer_data[0].attrib.keys()] tag = layer_data[0].tag if tag in ['PSK', 'BZL', 'JP', 'OP']: attnames = ['lhc_kod','odd','dil','por'] + attnames if tag == 'PSK': attnames.append('etz') pr.addAttributes( [QgsField(k , QVariant.String ) for k in attnames] ) layer.updateFields() geom_tag = { 'PSK':'PSK_OBRAZ' , 'BZL':'BZL_OBRAZ' , 'JP':'JP_OBRAZ' , 'OP':'OP_OBRAZ' , 'KLO':'LIN_OBRAZ' , 'KTO':'TXT_OBRAZ' , 'KBO':'BOD_OBRAZ' , 'KPO':'PLO_OBRAZ' }[tag] for feature_data in layer_data: feature = QgsFeature() if tag in ['BZL', 'JP', 'OP']: feature.setAttributes([ feature_data.find('../../../..').get('LHC_KOD') , feature_data.find('../../..').get('ODD') , feature_data.find('../..').get('DIL') , feature_data.find('..').get('POR')] +[feature_data.get(a) for a in attnames if a not in [ 'lhc_kod', 'odd', 'dil', 'por'] ]) elif tag == 'PSK': feature.setAttributes([ feature_data.find('../../../..').get('LHC_KOD') , feature_data.find('../../..').get('ODD') , feature_data.find('../..').get('DIL') , feature_data.find('..').get('POR')] +[feature_data.get(a) for a in attnames if a not in [ 'lhc_kod', 'odd', 'dil', 'por','etz']] #+ [ json.dumps(dict(etz.attrib)) for etz in feature_data.xpath('ETZ')] + [json.dumps([dict(etz.attrib) for etz in feature_data.xpath('ETZ')])] ) else: feature.setAttributes([feature_data.get(a) for a in attnames]) try: feature.setGeometry( islh_parser.parse_geometry(feature_data.find(geom_tag)) ) except TypeError: QMessageBox.critical(QDialog() ,u"Prvek se nepodařilo vytvořit",u"%s"%etree.tostring(feature_data)) pr.addFeatures([feature]) #posunu progres bar self.dockwidget.progressBar.setValue(self.progres.next()) #nakonec se mrknu, esli je PSK ZNACKA if tag == 'PSK' and not 'PSK_ZNACKA' in attnames: layer.addExpressionField('znacka(etz)', QgsField('PSK_ZNACKA',QVariant.Int)) #------------------------------------ ##geometry @staticmethod def parse_geometry(gr): """node s ISLH grafikou""" g = gr[0] #obraz ma jen jeden prvek geom = ( QgsGeometry.fromPoint(islh_parser.parse_point(g)) if g.tag == 'B' else QgsGeometry.fromPolyline(islh_parser.parse_line(g)) if g.tag == 'L' else QgsGeometry.fromMultiPoint(islh_parser.parse_multipoint(g)) if g.tag == 'MB' else QgsGeometry.fromMultiPolyline(islh_parser.parse_multiline(g)) if g.tag == 'ML' else QgsGeometry.fromPolygon(islh_parser.parse_polygon(g)) if g.tag == 'P' else QgsGeometry.fromMultiPolygon(islh_parser.parse_multipolygon(g)) if g.tag == 'MP' else None) return(geom) @staticmethod def parse_point(p): """udělá z bodu ogr bod""" (y,x) = map(lambda x: -float(x), p.get('S').split('$')) return( QgsPoint(x,y) ) @staticmethod def parse_line(l): """udělá z bodu ogr bod""" return( [islh_parser.parse_point(point) for point in l.xpath('B')] ) @staticmethod def parse_multipoint(l): return( [islh_parser.parse_point(point) for point in l.xpath('B')] ) @staticmethod def parse_multiline(p): return( [islh_parser.parse_line(line) for line in p.xpath('L')] ) @staticmethod def parse_polygon(p): return( [islh_parser.parse_line(line) for line in p.xpath('L')] ) @staticmethod def parse_multipolygon(p): return( [islh_parser.parse_polygon(polygon) for polygon in p.xpath('P')] )