Example #1
0
    def testRepack(self):
        vl = QgsVectorLayer('{}|layerid=0'.format(self.repackfile), 'test', 'ogr')

        ids = [f.id() for f in vl.getFeatures(QgsFeatureRequest().setFilterExpression('pk=1'))]
        vl.selectByIds(ids)
        self.assertEqual(vl.selectedFeatureIds(), ids)
        self.assertEqual(vl.featureCount(), 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)
Example #2
0
    def testRepack(self):
        vl = QgsVectorLayer('{}|layerid=0'.format(self.repackfile), 'test', 'ogr')

        ids = [f.id() for f in vl.getFeatures(QgsFeatureRequest().setFilterExpression('pk=1'))]
        vl.selectByIds(ids)
        self.assertEqual(vl.selectedFeatureIds(), 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 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
Example #4
0
    def testRepack(self):
        vl = QgsVectorLayer("{}|layerid=0".format(self.repackfile), "test", "ogr")

        ids = [f.id() for f in vl.getFeatures(QgsFeatureRequest().setFilterExpression("pk=1"))]
        vl.selectByIds(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)
Example #5
0
    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
class TestSectionPlot(utils_for_tests.MidvattenTestPostgisDbSv):
    """ The test doesn't go through the whole section plot unfortunately
    """
    @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 setUp(self):
        super(TestSectionPlot, self).setUp()
        self.midvatten.ms.settingsdict['secplot_loaded_template'] = ''
        self.midvatten.ms.settingsdict['secplot_templates'] = ''
        self.midvatten.ms.settingsdict['secplotlocation'] = 0
    
    @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'] = "%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()
        feature_ids = [feature.id() for feature in features]
        self.vlayer.selectByIds(feature_ids)

    @mock.patch('midvatten_utils.MessagebarAndLog')
    @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_plot_section(self, mock_messagebar):
        """For now, the test only initiates the plot. Check that it does not crash """
        db_utils.sql_alter_db('''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('''INSERT INTO obs_points (obsid, geometry) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006))''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006))''')
        db_utils.sql_alter_db('''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.MidvattenTestPostgisNotCreated.mock_instance_settings_database)
        @mock.patch('db_utils.get_postgis_connections', utils_for_tests.MidvattenTestPostgisNotCreated.mock_postgis_connections)
        @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 = ('P1', 'P2', '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("%berg%")
            self.myplot.draw_plot()
            self.selected_obsids = self.myplot.selected_obsids
        _test_plot_section(self)

        assert """call.info(log_msg='Settings {""" in str(mock_messagebar.mock_calls)

        assert self.myplot.drillstoplineEdit.text() == '%berg%'
        assert utils_for_tests.create_test_string(self.myplot.selected_obsids) == "['P1' 'P2' 'P3']"
        assert not mock_messagebar.warning.called
        assert not mock_messagebar.critical.called
        assert len(self.myplot.p) == len(self.myplot.Labels)

    @mock.patch('midvatten_utils.MessagebarAndLog')
    @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_plot_section_with_string_obsid(self, mock_messagebar):
        """For now, the test only initiates the plot. Check that it does not crash with string obsid """
        db_utils.sql_alter_db('''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('''INSERT INTO obs_points (obsid, geometry) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006))''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006))''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P3', ST_GeomFromText('POINT(6720728 016569)', 3006))''')

        self.create_and_select_vlayer()
        print(str(self.vlayer.selectedFeatureCount()))

        @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestPostgisNotCreated.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 = ('P1', 'P2', '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("%berg%")
            self.myplot.draw_plot()
            self.selected_obsids = self.myplot.selected_obsids
        _test_plot_section(self)

        assert """call.info(log_msg='Settings {""" in str(mock_messagebar.mock_calls)
        assert self.myplot.drillstoplineEdit.text() == '%berg%'
        assert utils_for_tests.create_test_string(self.myplot.selected_obsids) == "['P1' 'P2' '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.MidvattenTestPostgisNotCreated.mock_instance_settings_database)
    @mock.patch('db_utils.get_postgis_connections', utils_for_tests.MidvattenTestPostgisNotCreated.mock_postgis_connections)
    def test_plot_section_with_depth(self, mock_messagebar):
        db_utils.sql_alter_db('''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('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006), 2)''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006), '1')''')
        db_utils.sql_alter_db('''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_plot_section_with_depth(self, mock_iface, mock_getselectedobjectnames):
            mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer
            mock_getselectedobjectnames.return_value = ('P1', 'P2', 'P3')
            mock_mapcanvas = mock_iface.mapCanvas.return_value
            mock_mapcanvas.layerCount.return_value = 0
            self.midvatten.plot_section()
            self.myplot = self.midvatten.myplot
        _test_plot_section_with_depth(self)

        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.MidvattenTestPostgisNotCreated.mock_instance_settings_database)
    @mock.patch('db_utils.get_postgis_connections', utils_for_tests.MidvattenTestPostgisNotCreated.mock_postgis_connections)
    def test_plot_section_with_w_levels(self, mock_messagebar):
        db_utils.sql_alter_db('''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('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006), 2)''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006), '1')''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P3', ST_GeomFromText('POINT(6720727 016568)', 3006), NULL)''')
        db_utils.sql_alter_db('''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('''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 = ('P1', 'P2', '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, 'w_levels')
            self.myplot.datetimetextEdit.append('2015')
            self.myplot.draw_plot()

        _test(self)

        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.MidvattenTestPostgisNotCreated.mock_instance_settings_database)
    @mock.patch('db_utils.get_postgis_connections', utils_for_tests.MidvattenTestPostgisNotCreated.mock_postgis_connections)
    def test_plot_section_length_along_slope(self, mock_messagebar):

        db_utils.sql_alter_db('''INSERT INTO obs_lines (obsid, geometry) VALUES ('L1', ST_GeomFromText('LineString(2 0, 10 10)', 3006))''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P1', ST_GeomFromText('POINT(1 0)', 3006))''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P2', ST_GeomFromText('POINT(3 0)', 3006))''')
        db_utils.sql_alter_db('''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 = ('P1', 'P2', '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("%berg%")
            self.myplot.draw_plot()
        _test(self.midvatten, self.vlayer)

        test_string = utils_for_tests.create_test_string(self.myplot.LengthAlong)
        assert any([test_string == "[ 0.          0.62469505  1.87408514]",
                    test_string == "[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.MidvattenTestPostgisNotCreated.mock_instance_settings_database)
    @mock.patch('db_utils.get_postgis_connections', utils_for_tests.MidvattenTestPostgisNotCreated.mock_postgis_connections)
    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('''INSERT INTO obs_lines (obsid, geometry) VALUES ('L1', ST_GeomFromText('LineString(0 0, 1 0, 10 0)', 3006))''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P1', ST_GeomFromText('POINT(1 0)', 3006))''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P2', ST_GeomFromText('POINT(3 5)', 3006))''')
        db_utils.sql_alter_db('''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 = ('P1', 'P2', 'P3')
            mock_mapcanvas = mock_iface.mapCanvas.return_value
            mock_mapcanvas.layerCount.return_value = 0
            midvatten.plot_section()
            myplot = midvatten.myplot
            myplot.drillstoplineEdit.setText("%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 == "[ 1.  3.  5.]", test_string == "[1. 3. 5.]"])
        assert mock.call.info(log_msg='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

    @mock.patch('midvatten_utils.MessagebarAndLog')
    @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_plot_section_p_label_lengths(self, mock_messagebar):
        db_utils.sql_alter_db('''INSERT INTO obs_lines (obsid, geometry) VALUES ('1', ST_GeomFromText('LINESTRING(633466.711659 6720684.24498, 633599.530455 6720727.016568)', 3006))''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006), 2)''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006), '1')''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P3', ST_GeomFromText('POINT(6720727 016568)', 3006), NULL)''')
        db_utils.sql_alter_db('''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('''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 = ('P1', 'P2', '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.Stratigraphy_checkBox.setChecked(True)
            gui_utils.set_combobox(self.myplot.wlvltableComboBox, 'w_levels')
            self.myplot.datetimetextEdit.append('2015')
            self.myplot.draw_plot()
        _test(self)

        print(str(mock_messagebar.mock_calls))
        print(str(self.myplot.p))
        print(str(self.myplot.Labels))
        assert len(self.myplot.skipped_bars) == len(self.myplot.Labels)
        assert len(self.myplot.skipped_bars) == 2
        #assert False

    @mock.patch('midvatten_utils.MessagebarAndLog')
    @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_plot_section_p_label_lengths_with_geology(self, mock_messagebar):
        db_utils.sql_alter_db('''INSERT INTO obs_lines (obsid, geometry) VALUES ('1', ST_GeomFromText('LINESTRING(633466.711659 6720684.24498, 633599.530455 6720727.016568)', 3006))''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006), 2)''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006), '1')''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P3', ST_GeomFromText('POINT(6720727 016568)', 3006), NULL)''')
        db_utils.sql_alter_db('''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('''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P2', '2015-01-01 00:00:00', '17', '200', '183')''')
        db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geoshort) VALUES ('P1', 1, 0, 1, 'sand')''')
        db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geoshort) VALUES ('P1', 2, 1, 2, 'gravel')''')

        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 = ('P1', 'P2', '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.Stratigraphy_checkBox.setChecked(True)
            gui_utils.set_combobox(self.myplot.wlvltableComboBox, 'w_levels')
            self.myplot.datetimetextEdit.append('2015')
            self.myplot.draw_plot()

        _test(self)

        print(str(mock_messagebar.mock_calls))
        print(str(self.myplot.p))
        print(str(self.myplot.Labels))
        assert len(self.myplot.skipped_bars) == len(self.myplot.Labels)
        assert len(self.myplot.skipped_bars) == 4

    def tearDown(self):
        QgsProject.instance().addMapLayer(self.vlayer)
        QgsProject.instance().removeMapLayer(self.vlayer.id())
        super(self.__class__, self).tearDown()
Example #7
0
    def unionespacial(self, event):
        # Datos de viviendas de catastro
        bu = self.input_gml.filePath()

        # Datos de perímetros de núcleos de población EIEL
        nucleo = self.input_shp.filePath()

        # Unir aributos por localización: Viviendas y núcleos
        bu_output = 'C:/V_EIEL/viviendasclasificadas.shp'
        processing.run(
            "qgis:joinattributesbylocation", {
                'INPUT': bu,
                'JOIN': nucleo,
                'PREDICATE': 0,
                'JOIN_FIELDS': ['CODIGO', 'DENOMINACI'],
                'METHOD': 0,
                'PREFIX': 'NU_',
                'OUTPUT': bu_output
            })

        joinat = QgsVectorLayer(bu_output, "Viviendas clasificadas nucleo",
                                "ogr")
        QgsProject.instance().addMapLayers([joinat])

        # Selecciono registros sin clasificar de la capa de viviendas clasificadas utilizando la capa núcleos

        expresion = "NU_CODIGO is NULL"
        joinat.selectByExpression(expresion, QgsVectorLayer.SetSelection)

        #Genero el buffer de la capa núcleos

        nucleo = self.input_shp.filePath()
        file_output = 'C:/V_EIEL/buffernucleo.shp'

        processing.run(
            "native:buffer", {
                'INPUT': nucleo,
                'DISTANCE': 200,
                'SEGMENTS': 10,
                'DISSOLVE': False,
                'END_CAP_STYLE': 0,
                'JOIN_STYLE': 0,
                'MITER_LIMIT': 1,
                'OUTPUT': file_output
            })

        lyrBuffer = QgsVectorLayer(file_output, "Buffer nucleo", "ogr")
        QgsProject.instance().addMapLayers([lyrBuffer])

        # Unión espacial de los registros seleccionados de joinat con buffer
        bu_output_2 = 'C:/V_EIEL/viviendasclasificadas_2.shp'
        processing.run(
            "qgis:joinattributesbylocation", {
                'INPUT':
                QgsProcessingFeatureSourceDefinition(
                    'Viviendas clasificadas nucleo', True),
                'JOIN':
                lyrBuffer,
                'PREDICATE':
                0,
                'JOIN_FIELDS': ['CODIGO', 'DENOMINACI'],
                'METHOD':
                0,
                'PREFIX':
                'NU_',
                'OUTPUT':
                bu_output_2
            })

        joinat_2 = QgsVectorLayer(bu_output_2, "Viviendas clasificadas buffer",
                                  "ogr")
        QgsProject.instance().addMapLayers([joinat_2])

        joinat.removeSelection()
        joinat.commitChanges()

        # El resto de viviendas no clasificadas mediante la union con capa buffer pasan a estar en diseminado
        joinat_2 = iface.activeLayer()

        expresion_2 = "NU_CODIGO_ is NULL"
        joinat_2.selectByExpression(expresion_2, QgsVectorLayer.SetSelection)
        joinat_2.startEditing()
        n = joinat_2.selectedFeatureCount()

        for i in range(0, n):
            diseminado = joinat_2.selectedFeatures()
            viv_diseminado = diseminado[i]
            viv_diseminado.setAttribute("NU_CODIGO_", "99")
            viv_diseminado["NU_CODIGO_"] = "99"
            joinat_2.updateFeature(viv_diseminado)
            viv_diseminado.setAttribute("NU_DENOM_1", "DISEMINADO")
            viv_diseminado["NU_DENOM_1"] = "DISEMINADO"
            joinat_2.updateFeature(viv_diseminado)

        joinat_2.commitChanges()
        joinat_2.removeSelection()

        joinat_2.startEditing()
        features = joinat_2.getFeatures()
        for feature in features:
            feature.setAttribute(feature.fieldNameIndex('NU_CODIGO'),
                                 feature['NU_CODIGO_'])
            feature.setAttribute(feature.fieldNameIndex('NU_DENOMIN'),
                                 feature['NU_DENOM_1'])
            joinat_2.updateFeature(feature)

        joinat_2.commitChanges()
        joinat_2.removeSelection()

        # Elimino los campos NU_CODIGO_ y NU_DENOM_1 para conservar la misma estructura en las dos capas joint attributes
        joinat_2.startEditing()
        joinat_2.deleteAttributes([27, 28])
        joinat_2.updateFields()
        joinat_2.commitChanges()

        # Creo la capa union de Viviendas clasificadas nucleo(solo la selección) y viviendas clasificadas buffer
        # En primer lugar extraigo las viviendas clasificadas en la union con la capa nucleos
        expresion_3 = "NU_CODIGO is not NULL"
        joinat.selectByExpression(expresion_3, QgsVectorLayer.SetSelection)
        joinat.startEditing()

        seleccion = 'C:/V_EIEL/viviendasclasificadas_seleccion.shp'
        processing.run("native:saveselectedfeatures", {
            'INPUT': joinat,
            'OUTPUT': seleccion
        })
        nucleo_seleccion = QgsVectorLayer(
            seleccion, "Viviendas clasificadas nucleo seleccion", "ogr")
        QgsProject.instance().addMapLayers([nucleo_seleccion])

        joinat.removeSelection()

        resultado = 'C:/V_EIEL/viviendasclasificadas_resultado.shp'
        processing.run("native:mergevectorlayers", {
            'LAYERS': [nucleo_seleccion, joinat_2],
            'OUTPUT': resultado
        })

        resultado_merge = QgsVectorLayer(resultado, "Viviendas clasificadas",
                                         "ogr")
        QgsProject.instance().addMapLayers([resultado_merge])

        # Suprimo del proyecto todas las capas intermedias generadas en el proceso
        QgsProject.instance().removeMapLayer(nucleo_seleccion)
        QgsProject.instance().removeMapLayer(joinat_2)
        QgsProject.instance().removeMapLayer(joinat)
        QgsProject.instance().removeMapLayer(lyrBuffer)

        #Representación categorizada de la capa resultado
        #Valores únicos
        resultado_merge = iface.activeLayer()

        valoresnucleo = []
        unico = resultado_merge.dataProvider()
        campos = unico.fields()
        id = campos.indexFromName('NU_DENOMIN')
        valoresnucleo = unico.uniqueValues(id)

        #Creación de categorías
        categorias = []
        for valornucleo in valoresnucleo:

            # inicio el valor de símbolo por defecto para la geometría tipo
            symbol = QgsSymbol.defaultSymbol(resultado_merge.geometryType())

            # configuración de capa de simbología
            layer_style = {}
            layer_style['color'] = '%d, %d, %d' % (random.randint(
                0, 256), random.randint(0, 256), random.randint(0, 256))
            layer_style['outline'] = '#000000'
            symbol_layer = QgsSimpleFillSymbolLayer.create(layer_style)

            # sustitución de simbología por defecto por simbología configurada
            if symbol_layer is not None:
                symbol.changeSymbolLayer(0, symbol_layer)

            # creación de objeto renderer
            categoria = QgsRendererCategory(valornucleo, symbol,
                                            str(valornucleo))

            # generación de entrada para la lista de categorías
            categorias.append(categoria)

        renderer = QgsCategorizedSymbolRenderer('NU_DENOMIN', categorias)
        # asignación del renderer a la capa
        if renderer is not None:
            resultado_merge.setRenderer(renderer)

        resultado_merge.triggerRepaint()

        # Cálculo de estadísticas

        resultado = iface.activeLayer()
        estadisticas = 'C:/V_EIEL/estadisticas.csv'
        processing.run(
            "qgis:statisticsbycategories", {
                'CATEGORIES_FIELD_NAME': ['NU_DENOMIN', 'NU_CODIGO'],
                'INPUT': 'Viviendas clasificadas',
                'OUTPUT': 'C:/V_EIEL/estadisticas.csv',
                'VALUES_FIELD_NAME': 'numberOfDw',
            })

        # Cargo datos calculados de estadísticas de distribución de viviendas en QTableWidget tbl_resultados
        with open(estadisticas, 'r') as leer_estadisticas:
            registros = leer_estadisticas.read().splitlines()
            contar = 0  #Descarto la primera linea del archivo por contener las cabeceras de los campos
            for registro in registros:
                r = 0
                if contar > 0:
                    campos = registro.split(',')
                    #Puesto que el campo codigo se almacena con "" las elimino para que no aparezcan en la tabla
                    sc = campos[1].lstrip('"').rstrip('"')

                    #Cargo datos del csv en Qtable widget
                    self.tbl_resultados.insertRow(r)
                    self.tbl_resultados.setItem(r, 0,
                                                QTableWidgetItem(str(sc)))
                    self.tbl_resultados.setItem(
                        r, 1, QTableWidgetItem(str(campos[0])))
                    self.tbl_resultados.setItem(
                        r, 2, QTableWidgetItem(str(campos[7])))
                    r = r + 1
                contar = contar + 1

        # Rastreo de registros duplicados en capa resultado por intersectar con dos buffer o dos núcleos
        features = resultado_merge.getFeatures()
        referencias = []
        referencias_dup = []
        for f in features:
            idr = f.fieldNameIndex('reference')
            referencia = f.attribute(idr)
            if referencia not in referencias:
                referencias.append(referencia)
            else:
                referencias_dup.append(referencia)

        self.lst_duplicados.addItems(referencias_dup)
        total_duplicados = self.lst_duplicados.count()
        self.text_duplicados.append(str(total_duplicados))
# algorithms, etc.

# load combined node and link layers
print('loading nodes and links layers')
allNodesLayer = QgsVectorLayer(args.nodesLayer, "AllNodes", "ogr")
allLinksLayer = QgsVectorLayer(args.linksLayer, "AllLinks", "ogr")

# get all mesh_ids, edge node pairs, and point coordinates of edge nodes
allMeshIds = set()
allNodePairs = dict()
allPointsByMeshNode = dict()

print('iterating through all nodes')
allNodesLayer.selectAll()
for nodeFeature in tqdm(allNodesLayer.getFeatures(),
                        total=allNodesLayer.selectedFeatureCount()):
    meshId = nodeFeature['MESH_ID']
    allMeshIds.add(nodeFeature['MESH_ID'])

    adjacentMeshId = nodeFeature['ADJMAP_ID']
    adjacentNode = nodeFeature['ADJND_ID']

    if adjacentMeshId > 0 or adjacentNode > 0:
        currentNode = nodeFeature['NODE_ID']
        allNodePairs[(meshId, currentNode)] = (adjacentMeshId, adjacentNode)
        allPointsByMeshNode[(
            meshId, currentNode)] = nodeFeature.geometry().asWkt()[7:-1]

print('{} edge nodes found'.format(len(allNodePairs.keys())))

fixedCount = 0
Example #9
0
class TestSectionPlot(utils_for_tests.MidvattenTestPostgisDbSv):
    """ The test doesn't go through the whole section plot unfortunately
    """

    def setUp(self):
        super(TestSectionPlot, self).setUp()
        self.midvatten.ms.settingsdict['secplot_loaded_template'] = ''
        self.midvatten.ms.settingsdict['secplot_templates'] = ''
        self.midvatten.ms.settingsdict['secplotlocation'] = 0

    def create_and_select_vlayer(self):
        self.midvatten.ms.settingsdict['secplotdrillstop'] = "%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)
        QgsProject.instance().addMapLayer(self.vlayer)
        features = self.vlayer.getFeatures()
        feature_ids = [feature.id() for feature in features]
        print(str(feature_ids))
        self.vlayer.selectByIds(feature_ids)

    @mock.patch('midvatten_utils.MessagebarAndLog')
    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('''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('''INSERT INTO obs_points (obsid, geometry) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006))''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006))''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P3', ST_GeomFromText('POINT(6720728 016569)', 3006))''')
        self.create_and_select_vlayer()

        @mock.patch('midvatten_utils.find_layer')
        @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True)
        @mock.patch('qgis.utils.iface', autospec=True)
        def _test_plot_section(self, mock_iface, mock_getselectedobjectnames, mock_findlayer):
            mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer
            mock_findlayer.return_value.isEditable.return_value = False
            mock_getselectedobjectnames.return_value = ('P1', 'P2', '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("%berg%")
            self.myplot.draw_plot()
            self.selected_obsids = self.myplot.selected_obsids
        _test_plot_section(self)

        assert """call.info(log_msg='Settings {""" in str(mock_messagebar.mock_calls)

        assert self.myplot.drillstoplineEdit.text() == '%berg%'
        assert utils_for_tests.create_test_string(self.myplot.selected_obsids) == "['P1' 'P2' 'P3']"
        assert not mock_messagebar.warning.called
        assert not mock_messagebar.critical.called
        print("self.myplot.p {} self.myplot.labels {}".format(str(self.myplot.p), str(self.myplot.labels)))
        assert len(self.myplot.p) - 1 == len(self.myplot.labels) # The bars should not be labeled, so there is one less label than plot.

    @mock.patch('midvatten_utils.MessagebarAndLog')
    def test_plot_section_no_linelayer_message(self, mock_messagebar):

        @mock.patch('sectionplot.SectionPlot.do_it')
        @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True)
        @mock.patch('qgis.utils.iface', autospec=True)
        def _test(self, mock_iface, mock_getselectedobjectnames, mock_sectionplot):
            mock_layer = mock.Mock(spec=QgsVectorLayer)
            mock_iface.mapCanvas.return_value.currentLayer.return_value = mock_layer
            mock_layer.selectedFeatureCount.return_value = 2
            mock_geom = mock.Mock()
            mock_geom.wkbType.return_value = 'test'
            mock_feature = mock.Mock()
            mock_feature.geometry.return_value = mock_geom
            mock_layer.getFeatures.return_value = [mock_feature]
            self.midvatten.plot_section()

        _test(self)
        assert call.info(bar_msg='No line layer was selected. The stratigraphy bars will be lined up from south-north or west-east and no DEMS will be plotted.', duration=10) in mock_messagebar.mock_calls
        assert not mock_messagebar.warning.called
        assert not mock_messagebar.critical.called

    @mock.patch('midvatten_utils.MessagebarAndLog')
    def test_plot_section_with_string_obsid(self, mock_messagebar):
        """For now, the test only initiates the plot. Check that it does not crash with string obsid """
        db_utils.sql_alter_db('''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('''INSERT INTO obs_points (obsid, geometry) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006))''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006))''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P3', ST_GeomFromText('POINT(6720728 016569)', 3006))''')

        self.create_and_select_vlayer()
        print(str(self.vlayer.selectedFeatureCount()))
        @mock.patch('midvatten_utils.find_layer')
        @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True)
        @mock.patch('qgis.utils.iface', autospec=True)
        def _test_plot_section(self, mock_iface, mock_getselectedobjectnames, mock_findlayer):
            mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer
            mock_findlayer.return_value.isEditable.return_value = False
            mock_getselectedobjectnames.return_value = ('P1', 'P2', '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("%berg%")
            self.myplot.draw_plot()
            self.selected_obsids = self.myplot.selected_obsids
        _test_plot_section(self)

        assert """call.info(log_msg='Settings {""" in str(mock_messagebar.mock_calls)
        assert self.myplot.drillstoplineEdit.text() == '%berg%'
        assert utils_for_tests.create_test_string(self.myplot.selected_obsids) == "['P1' 'P2' 'P3']"
        assert not mock_messagebar.warning.called
        assert not mock_messagebar.critical.called

    @mock.patch('midvatten_utils.MessagebarAndLog')
    def test_plot_section_with_depth(self, mock_messagebar):
        db_utils.sql_alter_db('''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('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006), 2)''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006), '1')''')
        db_utils.sql_alter_db('''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.find_layer')
        @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_findlayer):
            mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer
            mock_findlayer.return_value.isEditable.return_value = False
            mock_getselectedobjectnames.return_value = ('P1', 'P2', 'P3')
            mock_mapcanvas = mock_iface.mapCanvas.return_value
            mock_mapcanvas.layerCount.return_value = 0
            self.midvatten.plot_section()
            self.myplot = self.midvatten.myplot
        _test_plot_section_with_depth(self)

        assert not mock_messagebar.warning.called
        assert not mock_messagebar.critical.called

    @mock.patch('midvatten_utils.MessagebarAndLog')
    def test_plot_section_with_w_levels(self, mock_messagebar):
        db_utils.sql_alter_db('''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('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006), 2)''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006), '1')''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P3', ST_GeomFromText('POINT(6720727 016568)', 3006), NULL)''')
        db_utils.sql_alter_db('''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('''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.find_layer')
        @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True)
        @mock.patch('qgis.utils.iface', autospec=True)
        def _test(self, mock_iface, mock_getselectedobjectnames, mock_findlayer):
            mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer
            mock_findlayer.return_value.isEditable.return_value = False
            mock_getselectedobjectnames.return_value = ('P1', 'P2', '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, 'w_levels')
            self.myplot.datetimetextEdit.append('2015')
            self.myplot.draw_plot()

        _test(self)

        assert not mock_messagebar.warning.called
        assert not mock_messagebar.critical.called

    @mock.patch('midvatten_utils.MessagebarAndLog')
    def test_plot_section_with_w_levels_duplicate_label(self, mock_messagebar):
        db_utils.sql_alter_db('''INSERT INTO obs_lines (obsid, geometry) VALUES ('1', ST_GeomFromText('LINESTRING(633466.711659 6720684.24498, 633599.530455 6720727.016568)', 3006))''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006), 2)''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006), '1')''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P3', ST_GeomFromText('POINT(6720727 016568)', 3006), NULL)''')
        db_utils.sql_alter_db('''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('''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.find_layer')
        @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True)
        @mock.patch('qgis.utils.iface', autospec=True)
        def _test(self, mock_iface, mock_getselectedobjectnames, mock_findlayer):
            mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer
            mock_findlayer.return_value.isEditable.return_value = False
            mock_getselectedobjectnames.return_value = ('P1', 'P2', '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, 'w_levels')
            self.myplot.datetimetextEdit.append('2015')
            self.myplot.datetimetextEdit.append('2015')
            self.myplot.secplot_templates.loaded_template['wlevels_Axes_plot'] = {'2015': {'label': '1', 'linestyle': '-', 'linewidth': 1, 'marker': 'v', 'markersize': 6, 'zorder': 8},
                                                                                  '2015_2': {'label': '2', 'linestyle': '-', 'linewidth': 1, 'marker': 'v', 'markersize': 6, 'zorder': 8},
                                                                                  'DEFAULT': {'label': 'DEFAULT', 'linestyle': '-', 'linewidth': 1, 'marker': 'v', 'markersize': 6, 'zorder': 8}}
            self.myplot.draw_plot()

        _test(self)

        print(str(mock_messagebar.mock_calls))
        assert not mock_messagebar.warning.called
        assert not mock_messagebar.critical.called
        labels = [p.get_label() for p in self.myplot.p]
        assert anything_to_string_representation(labels) == '''["1", "2", "drillstop like %berg%", "_container0"]'''
        assert anything_to_string_representation(self.myplot.water_level_labels_duplicate_check) == '''["2015", "2015_2"]'''

    @mock.patch('midvatten_utils.MessagebarAndLog')
    def test_plot_section_length_along_slope(self, mock_messagebar):

        db_utils.sql_alter_db('''INSERT INTO obs_lines (obsid, geometry) VALUES ('L1', ST_GeomFromText('LineString(2 0, 10 10)', 3006))''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P1', ST_GeomFromText('POINT(1 0)', 3006))''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P2', ST_GeomFromText('POINT(3 0)', 3006))''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P3', ST_GeomFromText('POINT(5 0)', 3006))''')

        self.create_and_select_vlayer()

        @mock.patch('midvatten_utils.find_layer')
        @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True)
        @mock.patch('qgis.utils.iface', autospec=True)
        def _test(midvatten, vlayer, mock_iface, mock_getselectedobjectnames, mock_findlayer):
            mock_iface.mapCanvas.return_value.currentLayer.return_value = vlayer
            mock_findlayer.return_value.isEditable.return_value = False
            mock_getselectedobjectnames.return_value = ('P1', 'P2', '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("%berg%")
            self.myplot.draw_plot()
        _test(self.midvatten, self.vlayer)

        test_string = utils_for_tests.create_test_string(self.myplot.length_along)
        assert any([test_string == "[ 0.          0.62469505  1.87408514]",
                    test_string == "[0.         0.62469505 1.87408514]"])

        assert not mock_messagebar.warning.called
        assert not mock_messagebar.critical.called

    @mock.patch('midvatten_utils.MessagebarAndLog')
    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('''INSERT INTO obs_lines (obsid, geometry) VALUES ('L1', ST_GeomFromText('LineString(0 0, 1 0, 10 0)', 3006))''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P1', ST_GeomFromText('POINT(1 0)', 3006))''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P2', ST_GeomFromText('POINT(3 5)', 3006))''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P3', ST_GeomFromText('POINT(5 10)', 3006))''')

        self.create_and_select_vlayer()

        @mock.patch('midvatten_utils.find_layer')
        @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True)
        @mock.patch('qgis.utils.iface', autospec=True)
        def _test(midvatten, vlayer, mock_iface, mock_getselectedobjectnames, mock_findlayer):
            mock_iface.mapCanvas.return_value.currentLayer.return_value = vlayer
            mock_findlayer.return_value.isEditable.return_value = False
            mock_getselectedobjectnames.return_value = ('P1', 'P2', 'P3')
            mock_mapcanvas = mock_iface.mapCanvas.return_value
            mock_mapcanvas.layerCount.return_value = 0
            midvatten.plot_section()
            myplot = midvatten.myplot
            myplot.drillstoplineEdit.setText("%berg%")
            myplot.draw_plot()
            return myplot
        myplot = _test(self.midvatten, self.vlayer)

        test_string = utils_for_tests.create_test_string(myplot.length_along)
        assert any([test_string == "[ 1.  3.  5.]", test_string == "[1. 3. 5.]"])
        assert mock.call.info(log_msg='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

    @mock.patch('midvatten_utils.MessagebarAndLog')
    def test_plot_section_p_label_lengths(self, mock_messagebar):
        db_utils.sql_alter_db('''INSERT INTO obs_lines (obsid, geometry) VALUES ('1', ST_GeomFromText('LINESTRING(633466.711659 6720684.24498, 633599.530455 6720727.016568)', 3006))''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006), 2)''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006), '1')''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P3', ST_GeomFromText('POINT(6720727 016568)', 3006), NULL)''')
        db_utils.sql_alter_db('''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('''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.find_layer')
        @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True)
        @mock.patch('qgis.utils.iface', autospec=True)
        def _test(self, mock_iface, mock_getselectedobjectnames, mock_findlayer):
            mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer
            mock_findlayer.return_value.isEditable.return_value = False
            mock_getselectedobjectnames.return_value = ('P1', 'P2', '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.Stratigraphy_radioButton.setChecked(True)
            self.myplot.Legend_checkBox.setChecked(True)
            gui_utils.set_combobox(self.myplot.wlvltableComboBox, 'w_levels')
            self.myplot.datetimetextEdit.append('2015')
            self.myplot.draw_plot()
        _test(self)

        print(str(mock_messagebar.mock_calls))
        print(str(self.myplot.p))
        print(str(self.myplot.labels))
        assert len(self.myplot.skipped_bars) == len(self.myplot.labels)
        assert len(self.myplot.skipped_bars) == 2
        #assert False

    @mock.patch('midvatten_utils.MessagebarAndLog')
    def test_plot_section_p_label_lengths_with_geology(self, mock_messagebar):
        db_utils.sql_alter_db('''INSERT INTO obs_lines (obsid, geometry) VALUES ('1', ST_GeomFromText('LINESTRING(633466.711659 6720684.24498, 633599.530455 6720727.016568)', 3006))''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006), 2)''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006), '1')''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P3', ST_GeomFromText('POINT(6720727 016568)', 3006), NULL)''')
        db_utils.sql_alter_db('''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('''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P2', '2015-01-01 00:00:00', '17', '200', '183')''')
        db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geoshort) VALUES ('P1', 1, 0, 1, 'sand')''')
        db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geoshort) VALUES ('P1', 2, 1, 2, 'gravel')''')

        self.create_and_select_vlayer()

        @mock.patch('midvatten_utils.find_layer')
        @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True)
        @mock.patch('qgis.utils.iface', autospec=True)
        def _test(self, mock_iface, mock_getselectedobjectnames, mock_findlayer):
            mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer
            mock_findlayer.return_value.isEditable.return_value = False
            mock_getselectedobjectnames.return_value = ('P1', 'P2', '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.Stratigraphy_radioButton.setChecked(True)
            self.myplot.Legend_checkBox.setChecked(True)
            gui_utils.set_combobox(self.myplot.wlvltableComboBox, 'w_levels')
            self.myplot.datetimetextEdit.append('2015')
            self.myplot.draw_plot()

        _test(self)

        print(str(mock_messagebar.mock_calls))
        print(str(self.myplot.p))
        print(str(self.myplot.labels))
        assert len(self.myplot.skipped_bars) == len(self.myplot.labels)
        assert len(self.myplot.skipped_bars) == 4

    @mock.patch('midvatten_utils.MessagebarAndLog')
    def test_plot_section_p_label_lengths_with_geology_changed_label(self, mock_messagebar):
        db_utils.sql_alter_db('''INSERT INTO obs_lines (obsid, geometry) VALUES ('1', ST_GeomFromText('LINESTRING(633466.711659 6720684.24498, 633599.530455 6720727.016568)', 3006))''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006), 2)''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006), '1')''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P3', ST_GeomFromText('POINT(6720727 016568)', 3006), NULL)''')
        db_utils.sql_alter_db('''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('''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P2', '2015-01-01 00:00:00', '17', '200', '183')''')
        db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geoshort) VALUES ('P1', 1, 0, 1, 'sand')''')
        db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geoshort) VALUES ('P1', 2, 1, 2, 'gravel')''')

        self.create_and_select_vlayer()

        @mock.patch('midvatten_utils.find_layer')
        @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True)
        @mock.patch('qgis.utils.iface', autospec=True)
        def _test(self, mock_iface, mock_getselectedobjectnames, mock_findlayer):
            mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer
            mock_findlayer.return_value.isEditable.return_value = False
            mock_getselectedobjectnames.return_value = ('P1', 'P2', '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.secplot_templates.loaded_template['geology_Axes_bar'] = {'sand': {'label': 'sandtest', 'edgecolor': 'black', 'zorder': 5},
                                                                                  'grus': {'label': 'grustest', 'edgecolor': 'black', 'zorder': 5},
                                                                                  'DEFAULT': {'edgecolor': 'black', 'zorder': 5}}
            print("before: " + str(self.myplot.secplot_templates.loaded_template['geology_Axes_bar']))
            self.myplot.Stratigraphy_radioButton.setChecked(True)
            self.myplot.Legend_checkBox.setChecked(True)
            gui_utils.set_combobox(self.myplot.wlvltableComboBox, 'w_levels')
            self.myplot.datetimetextEdit.append('2015')

            self.myplot.draw_plot()

        _test(self)

        #print(str(mock_messagebar.mock_calls))
        #print(str(self.myplot.p))
        #print(str(self.myplot.labels))
        labels = [p.get_label() for p in self.myplot.p]
        assert len(self.myplot.skipped_bars) == len(self.myplot.labels)
        assert len(self.myplot.skipped_bars) == 4
        assert anything_to_string_representation(labels) == '''["sandtest", "grustest", "2015", "drillstop like %berg%", "_container2"]'''
        assert anything_to_string_representation(self.myplot.water_level_labels_duplicate_check) == '''["2015"]'''

    @mock.patch('midvatten_utils.MessagebarAndLog')
    def test_plot_section_p_label_lengths_with_geology_changed_label(self, mock_messagebar):
        db_utils.sql_alter_db('''INSERT INTO obs_lines (obsid, geometry) VALUES ('1', ST_GeomFromText('LINESTRING(633466.711659 6720684.24498, 633599.530455 6720727.016568)', 3006))''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006), 2)''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006), '1')''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P3', ST_GeomFromText('POINT(6720727 016568)', 3006), NULL)''')
        db_utils.sql_alter_db('''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('''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P2', '2015-01-01 00:00:00', '17', '200', '183')''')
        db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geoshort) VALUES ('P1', 1, 0, 1, 'sand')''')
        db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geoshort) VALUES ('P1', 2, 1, 2, 'gravel')''')

        self.create_and_select_vlayer()

        @mock.patch('midvatten_utils.find_layer')
        @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True)
        @mock.patch('qgis.utils.iface', autospec=True)
        def _test(self, mock_iface, mock_getselectedobjectnames, mock_findlayer):
            mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer
            mock_findlayer.return_value.isEditable.return_value = False
            mock_getselectedobjectnames.return_value = ('P1', 'P2', '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.secplot_templates.loaded_template['geology_Axes_bar'] = {'sand': {'label': 'sandtest', 'edgecolor': 'black', 'zorder': 5},
                                                                                  'grus': {'label': 'grustest', 'edgecolor': 'black', 'zorder': 5},
                                                                                  'DEFAULT': {'edgecolor': 'black', 'zorder': 5}}
            print("before: " + str(self.myplot.secplot_templates.loaded_template['geology_Axes_bar']))
            self.myplot.Stratigraphy_radioButton.setChecked(True)
            self.myplot.Legend_checkBox.setChecked(True)
            gui_utils.set_combobox(self.myplot.wlvltableComboBox, 'w_levels')
            self.myplot.datetimetextEdit.append('2015')

            self.myplot.draw_plot()

        _test(self)

        #print(str(mock_messagebar.mock_calls))
        #print(str(self.myplot.p))
        #print(str(self.myplot.labels))
        labels = [p.get_label() for p in self.myplot.p]
        assert len(self.myplot.skipped_bars) == len(self.myplot.labels)
        assert len(self.myplot.skipped_bars) == 4
        assert anything_to_string_representation(labels) == '''["sandtest", "grustest", "2015", "drillstop like %berg%", "_container2"]'''
        assert anything_to_string_representation(self.myplot.water_level_labels_duplicate_check) == '''["2015"]'''

    @mock.patch('midvatten_utils.MessagebarAndLog')
    def test_plot_section_with_w_levels_animation(self, mock_messagebar):
        db_utils.sql_alter_db('''INSERT INTO obs_lines (obsid, geometry) VALUES ('1', ST_GeomFromText('LINESTRING(633466.711659 6720684.24498, 633599.530455 6720727.016568)', 3006))''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006), 2)''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006), '1')''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P3', ST_GeomFromText('POINT(6720727 016568)', 3006), NULL)''')
        db_utils.sql_alter_db('''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('''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P2', '2015-01-01 00:00:00', '17', '200', '183')''')
        db_utils.sql_alter_db('''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P1', '2015-01-02 00:00:00', '15', '200', '185')''')
        db_utils.sql_alter_db('''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P1', '2015-01-03 00:00:00', '15', '200', '185')''')
        self.create_and_select_vlayer()

        @mock.patch('midvatten_utils.find_layer')
        @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True)
        @mock.patch('qgis.utils.iface', autospec=True)
        def _test(self, mock_iface, mock_getselectedobjectnames, mock_findlayer):
            mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer
            mock_findlayer.return_value.isEditable.return_value = False
            mock_getselectedobjectnames.return_value = ('P1', 'P2', '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, 'w_levels')
            self.myplot.interactive_groupbox.setChecked(True)
            #self.myplot.datetimetextEdit.append('2015')

            self.myplot.draw_plot()
            return self.myplot

        myplot = _test(self)
        print(str(mock_messagebar.mock_calls))
        assert myplot.interactive_groupbox.isChecked()
        assert len(myplot.figure.axes) > 1
        assert not mock_messagebar.warning.called
        assert not mock_messagebar.critical.called

    @mock.patch('midvatten_utils.MessagebarAndLog')
    def test_plot_section_obsids(self, mock_messagebar):
        db_utils.sql_alter_db('''INSERT INTO obs_lines (obsid, geometry) VALUES ('1', ST_GeomFromText('LINESTRING(1 0, 4 0)', 3006))''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, h_gs, length) VALUES ('P1', ST_GeomFromText('POINT(1 1)', 3006), 50, 2)''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, h_gs, length) VALUES ('P2', ST_GeomFromText('POINT(2 2)', 3006), 70, '1')''')
        db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, h_toc,length) VALUES ('P3', ST_GeomFromText('POINT(4 4)', 3006), 90, NULL)''')
        db_utils.sql_alter_db('''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('''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P2', '2015-01-01 00:00:00', '17', '200', '183')''')
        db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geoshort) VALUES ('P1', 1, 0, 1, 'sand')''')
        db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geoshort) VALUES ('P3', 2, 1, 2, 'gravel')''')

        self.create_and_select_vlayer()
        @mock.patch('midvatten_utils.find_layer')
        @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True)
        @mock.patch('qgis.utils.iface', autospec=True)
        def _test(self, mock_iface, mock_getselectedobjectnames, mock_findlayer):
            mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer
            mock_findlayer.return_value.isEditable.return_value = False
            mock_getselectedobjectnames.return_value = ('P1', 'P2', '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, 'w_levels')
            self.myplot.datetimetextEdit.append('2015')
            self.myplot.draw_plot()

        _test(self)
        #print(str(self.myplot.obsid_annotation))
        assert str(self.myplot.obsid_annotation) == '''{'P1': (0.0, 50.0), 'P3': (3.0, 90.0), 'P2': (1.0, 183.0)}'''
        print(str(mock_messagebar.mock_calls))
        assert not mock_messagebar.warning.called
        assert not mock_messagebar.critical.called
def main():
    """reads in a pre-processed groundwater layer, with recharge-discharge (CSV) and returns tif
    
    Args:
        state(str): state for which well elevations must be obtained
        season(str): e.g. rech-96, disc-96
        
    Returns:
        None: well elevations with locations stored in CSV as SHP
    
    """
    state = sys.argv[1]
    season = sys.argv[2]
    dataPath = root.joinpath("data","groundwater")
    metaPath = root.joinpath("outputs","groundwater","csv",state+"_metadata.log")
    outputsPath = root.joinpath("outputs","groundwater")
    
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s %(message)s',
                        datefmt='%m/%d/%Y %I:%M:%S %p',
                        handlers=[logging.FileHandler(str(metaPath))],
                       )
    
    logging.info("get Recharge-Discharge for '%s' dataset",state)

    # Initialize QGIS Application
    QgsApplication.setPrefixPath("G:\\Users\\Craig\\miniconda3\\envs\\geo_env\\Library\\python\\qgis", True)
    qgs = QgsApplication([], False)
    qgs.initQgis()
    
    # Append the path where QGIS processing plugin can be found
    sys.path.append('G:\\Users\\Craig\\miniconda3\\envs\\geo_env\\Library\\python\\plugins')
    import processing
    from processing.core.Processing import Processing
    Processing.initialize()
    feedback = QgsProcessingFeedback()
    
    QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms())

    # Get file with recharge-discharge values from previous step
    vectorPath = outputsPath.joinpath("shapefiles",state+"_processed_wRD.shp")
    print(vectorPath,vectorPath.exists())
    vLayer = QgsVectorLayer(str(vectorPath), 'well_rech_disc_layer', 'ogr') #.setSubsetString(season + " IS NOT NULL")
    print("islayer valid:", vLayer.isValid())
    
    # subset layer for the chosen season and choose only non null values
    filter = "\"" + season + "\"" + " IS NOT NULL"
    expr = QgsExpression(filter)
    subset = vLayer.getFeatures(QgsFeatureRequest(expr))
    vLayer.selectByIds([k.id() for k in subset])  # why didn't direct selection work? addFeature (false)
    print(vLayer.selectedFeatureCount())
    
    # write subsetted layer to shapefile
    subsetPath = outputsPath.joinpath("shapefiles","noNulls",state+"_"+season+"_noNulls.shp")
    _writer = QgsVectorFileWriter.writeAsVectorFormat(vLayer, str(subsetPath), "utf-8", vLayer.crs(), "ESRI Shapefile", onlySelected=True)
    
    # import subsetted layer
    subLayer = QgsVectorLayer(str(subsetPath), 'well_rech_disc_layer_nonulls', 'ogr') 
    print("is sub layer valid:", subLayer.isValid())
    
    # declare params for grid layer 
    # https://gdal.org/tutorials/gdal_grid_tut.html
    params = {
        'INPUT':subLayer,
        'POWER':2,    # FOR gridinversedistance
#         'RADIUS':0.25,    # FOR gridinversedistancenearestneighbor / gridlinear
#         'RADIUS_1':0.25,    # FOR gridinversedistance / gridnearestneighbor / gridaverage
#         'RADIUS_2':0.25,    # FOR gridinversedistance  /  gridnearestneighbor / gridaverage
        'MAX_POINTS':12,    # FOR gridinversedistance 
        'MIN_POINTS':1,    # FOR gridinversedistance / gridaverage
        'NODATA': -9999,
        'Z_FIELD':season,
        'OUTPUT':str(outputsPath.joinpath("tif","idw",state+"_"+season+"_grid_id_min_1_max_12_nonulls.tif"))
    }
    
    res = processing.run("gdal:gridinversedistance",params,feedback=feedback)
    print(res['OUTPUT'])