Пример #1
0
    def processAlgorithm(self, progress):
        """Here is where the processing itself takes place."""
        progress.setInfo(u'Start querying "{}" in PCJupiterXL...'.format(
            self.name))
        progress.setPercentage(50)

        plantinput = self.getParameterValue(self.PLANTIDORNAME)
        onlypublic_watersupply = self.getParameterValue(
            self.ONLYPUBLICWATERSUPPLY)
        output = self.getOutputFromName(self.OUTPUT)

        JupiterAux.log_info(u'\nprocessAlgorithm: {}'.format(self.tablename))

        pgtablename = u'mstmvw_catchperm'

        ok_add_map = True

        if ok_add_map:
            progress.setInfo(u'End querying "{}" in PCJupiterXL...'.format(
                self.name))
            progress.setPercentage(100)

            progress.setText(u'<br><b>RESULTAT:</b>')
            progress.setText(
                u'<br><b>Tabel {} er åbnet med navnet {}</b>'.format(
                    self.tablename, self.PLANTIDORNAME))
        else:
            progress.setInfo(u'Der er sket en fejl i "{}"'.format(self.name))
            progress.setPercentage(100)
Пример #2
0
    def selectedFeatureToWKT(self,
                             layername,
                             only_allow_one_selected_feature=True):
        """
        Returns wkt geom of just one selected feature
        :param layer: Layer with just one selection
        """
        if only_allow_one_selected_feature:
            if self.countSelectedFeatures(layername) != 1:
                JupiterAux.msg_box(
                    u'Der understøttes kun een valgt feature som forespørgelsesafgrænsning!'
                )
                return None

            layerObj = dataobjects.getObjectFromUri(layername)

            #return layerObj.selectedFeatures()[0].geometry().exportToWkt() #? crashes qgis with a pure virtual call

            fts = layerObj.selectedFeatures()
            ft = fts[0]
            g = ft.geometry()
            wkt = g.exportToWkt()

            return wkt
        else:
            JupiterAux.msg_box(
                u'Der understøttes kun een valgt feature som forespørgelsesafgrænsning!'
            )
            return None
Пример #3
0
    def writeOutputVector(self, progress, pglayer, output, isSpatial=True):
        """Write output
        :param pglayer: quried pg layer qgsvectorlayer to be written
        :param output: output processing object
        :param isSpatial: non spatial loads explictly
        :return: True if no error
        """
        JupiterAux.log_info('writing output vector: {}'.format(output.value))

        #error = QgsVectorFileWriter.writeAsVectorFormat(vlayer, outputfile, "utf-8", None, "ESRI Shapefile")
        #error = QgsVectorFileWriter.writeAsVectorFormat(vlayer, outputfile, "utf-8", None)

        output_writer = output.getVectorWriter(pglayer.fields(),
                                               pglayer.wkbType(),
                                               pglayer.crs())

        outFeat = QgsFeature()
        features = vector.features(pglayer)
        total = 100.0 / len(features) if len(features) > 0 else 1
        for current, feat in enumerate(features):
            progress.setPercentage(int(current * total))

            if isSpatial:
                geom = feat.geometry()
                outFeat.setGeometry(geom)

            atMap = feat.attributes()
            atMap.append(None)
            outFeat.setAttributes(atMap)
            output_writer.addFeature(outFeat)

        del output_writer

        return True
Пример #4
0
 def showFeatureCount(self, layername, show=True):
     """Set the feature count. TODO not working ...
     :param layername: layer to set style for
     :param show: toggle visibility
     :return: True if no error
     """
     root = QgsProject.instance().layerTreeRoot()
     for child in root.children():
         if isinstance(child, QgsLayerTreeLayer):
             JupiterAux.log_info('----- {}'.format(child.layerName()))
             if child.layerName() == layername:
                 child.setCustomProperty("showFeatureCount", show)
    def processAlgorithm(self, progress):
        JupiterAux.log_info(u'\nprocessAlgorithm: {}'.format(self.tablename))

        progress.setInfo(u'Start querying "{}" in PCJupiterXL...'.format(
            self.name))
        progress.setPercentage(30)

        extent = self.getParameterValue(self.EXTENT)
        extent_layer = self.getParameterValue(self.VECTOR_SELECTION)
        compoundname1 = unicode(self.getParameterValue(self.COMPOUNDNAME1))
        compoundname2 = unicode(self.getParameterValue(self.COMPOUNDNAME2))
        xaxeline = self.getParameterValue(self.XAXELINE)
        yaxeline = self.getParameterValue(self.YAXELINE)
        showannotations = self.getParameterValue(self.SHOWANNOTATIONS)
        date_from = self.getParameterValue(self.DATE_FROM)
        date_to = self.getParameterValue(self.DATE_TO)

        qgis = JupiterQGIS()
        if extent == "0,0,0,0":
            if qgis.countSelectedFeatures(extent_layer) != 1:
                JupiterAux.msg_box(
                    u'Der skal være valgt een (og kun en) geometri i {}\nNår afgrænsningen er 0,0,0,0'
                    .format(extent_layer))
                return

        # Create plot
        mapplot = JupiterMatplot()
        result = mapplot.scatterplot(extent,
                                     compoundname1,
                                     compoundname2,
                                     date_from,
                                     date_to,
                                     extent_layer=extent_layer,
                                     x_marker=xaxeline,
                                     y_marker=yaxeline,
                                     showannotations=showannotations)

        progress.setPercentage(100)

        #if self.tablename == u'Plot Nitrat mod sulfat':
        #    pgtablename = u'mstmvw_bulk_grwchem_alldates'
        #else:
        #    raise Exception(u'Fejl: Tabel eller view: "{}" findes ikke'.format(self.tablename))

        if result:
            progress.setInfo(u'End querying "{}" in PCJupiterXL...'.format(
                self.name))

            progress.setText(u'<br><b>RESULTAT:</b>')
            progress.setText(u'<br><b>Scatterplot oprettet og åbnet</b>')
        else:
            progress.setInfo(u'Der er sket en fejl i "{}"'.format(self.name))
Пример #6
0
    def getQgsVectorLayerFromUri(self, uri, pglayername):
        """Get QgsVectorLayer from URI
        :param uri: URI to get layer from
        :param pglayername: name of new layer
        :return:
        """
        pglayer = QgsVectorLayer(uri.uri(), pglayername, "postgres")

        if not pglayer.isValid():
            # A default next val sequence and reader and writer grants must be set
            JupiterAux.log_error(
                'MST-layer: "{}" is not valid!'.format(pglayername))

            return False, None

        return True, pglayer
Пример #7
0
    def addStyle(self, pglayername, vlayer, uri):
        """Add style to layer. Assumes tablename if stylename
        :param pglayername: layer to query for in public.layer_styles
        :param vlayer: layer to apply style for
        :return: True if no error
        """

        qmlfile = os.path.join(JupiterAux.pluginpath(), 'style',
                               'borehole.qml')
        msg, styleloaded = vlayer.loadNamedStyle(qmlfile, True)
        iface.mapCanvas().refresh()
        iface.legendInterface().refreshLayerSymbology(vlayer)
        vlayer.triggerRepaint()

        return True

        JupiterAux.log_info(u'Loading default style from db...')
        db = JupiterDb()
        styleqml = db.get_style(pglayername)

        if styleqml:
            #vlayer.applyNamedStyle(pglayername)
            styleok = vlayer.loadNamedStyle(styleqml, True)
            iface.mapCanvas().refresh()
            iface.legendInterface().refreshLayerSymbology(vlayer)
            vlayer.triggerRepaint()
            JupiterAux.log_info(u'Style applied to: {}'.format(pglayername))
        else:
            JupiterAux.log_info(
                u'Table {} has no default style in db'.format(pglayername))

        return True
Пример #8
0
    def processAlgorithm(self, progress):
        """Here is where the processing itself takes place."""
        progress.setInfo(u'Start querying "{}" in PCJupiterXL...'.format(self.name))
        progress.setPercentage(50)

        extent = self.getParameterValue(self.EXTENT)
        extent_layer = self.getParameterValue(self.VECTOR_SELECTION)
        date_from = self.getParameterValue(self.DATE_FROM)
        date_to = self.getParameterValue(self.DATE_TO)
        output = self.getOutputFromName(self.OUTPUT)

        where_sql = None

        JupiterAux.log_info(u'\nprocessAlgorithm: {}'.format(self.tablename))

        if self.tablename == u'Hent alle stoffer fra grundvand (boring)':
            pgtablename = u'mstmvw_bulk_grwchem_alldates'
            where_sql = u"sampledate > to_date('{}', 'YYYY-MM-DD') AND sampledate < to_date('{}', 'YYYY-MM-DD') AND geom IS NOT NULL".\
                format(date_from, date_to)
            output.description = 'Alle_stoffer_grw'
        elif self.tablename == u'Hent alle stoffer fra vandværk (anlæg)':
            pgtablename = u'mstmvw_bulk_pltchem_alldates'
            where_sql = u"sampledate > to_date('{}', 'YYYY-MM-DD') AND sampledate < to_date('{}', 'YYYY-MM-DD') AND geom IS NOT NULL".\
                format(date_from, date_to)
            output.description = 'Alle_stoffer_plt'
        else:
            raise Exception(u'Fejl: Tabel eller view: "{}" findes ikke'.format(self.tablename))

        jq = JupiterQGIS()
        ok_add_map = jq.add_maplayer(
            progress,
            pgtablename,
            output,
            extent,
            selectionLayername=extent_layer,
            rowid='row_id',
            where_sql2=where_sql)

        if ok_add_map:
            progress.setInfo(u'End querying "{}" in PCJupiterXL...'.format(self.name))

            progress.setText(u'<br><b>RESULTAT:</b>')
            progress.setText(u'<br><b>Tabel med alle stofanalyser er åbnet</b>')
        else:
            progress.setInfo(u'Der er sket en fejl i "{}"'.format(self.name))
Пример #9
0
    def add_rubberband_borehole(self, boreholeno):
        """ Warning - this method fails silently on error """
        self.remove_canvas_vertexmarkers()

        # Add new rubberband
        points = [[
            QgsPoint(6640629.039, 6087146.608),
            QgsPoint(640629.039, 6087146.608),
            QgsPoint(640629.039, 6087146.608),
            QgsPoint(6640629.039, 6087146.608)
        ]]  # lower left, upper right
        r = QgsRubberBand(iface.mapCanvas, True)  # True = a polygon
        r.setColor(QColor(0, 255, 0, 255))
        r.setWidth(3)
        r.setToGeometry(QgsGeometry.fromPolygon(points), None)

        JupiterAux.log_info(
            u'rubberband added for borehole {}'.format(boreholeno))
Пример #10
0
    def processAlgorithm(self, progress):
        """Here is where the processing itself takes place
        """
        progress.setInfo(u'Start querying "{}" in PCJupiterXL...'.format(
            self.name))
        progress.setPercentage(10)

        # Get user input

        output = self.getOutputFromName(
            self.OUTPUT)  #<class 'processing.core.outputs.OutputVector'>

        pgtablename = ''

        if self.dktablename == u'Åbn synchronizationlog':
            output.description = u'synchronizationlog'
            pgtablename = u'synchronizationlog'
        elif self.dktablename == u'Åbn synchronizationevent':
            output.description = u'synchronizationevent'
            pgtablename = u'synchronizationevent'
        elif self.dktablename == u'Åbn exporttime':
            output.description = u'exporttime'
            pgtablename = u'exporttime'

        JupiterAux.log_info(
            u'Valgt alphanumeric tabel med pgtablename: {}\n'.format(
                pgtablename))

        qgis = JupiterQGIS()
        ok_add_alphatable = qgis.add_alphaview(progress, pgtablename, output)

        progress.setPercentage(100)

        if ok_add_alphatable:
            progress.setInfo(u'End querying "{}" in PCJupiterXL...'.format(
                self.name))

            progress.setText(u'<br><b>RESULTAT:</b>')
            progress.setText(
                u'<br><b>Tabel med databasenavn: {} er åbnet som: {}</b>'.
                format(pgtablename, output.description))
        else:
            progress.setText(u'<br><b>Fejl i udtræk. Se log:</b>')
    def processAlgorithm(self, progress):
        """Here is where the processing itself takes place."""
        progress.setInfo(u'Start querying "{}" in PCJupiterXL...'.format(self.name))
        progress.setPercentage(50)

        pgtablename = u'mst_bekendtgoerelse_pesticide_list'
        output = self.getOutputFromName(self.OUTPUT)  #<class 'processing.core.outputs.OutputVector'>

        JupiterAux.log_info('Valgte tabel eller view: {}\n'.format(self.dktablename))

        jq = JupiterQGIS()
        ok_added = jq.add_alphaview(progress, pgtablename, output)

        if ok_added:
            progress.setInfo(u'End querying "{}" in PCJupiterXL...'.format(self.name))
            progress.setPercentage(100)

            progress.setText(u'<br><b>RESULTAT:</b>')
            progress.setText(u'<br><b>Tabel: {} er åbnet med navnet: {}</b>'.format(self.dktablename, pgtablename))
        else:
            progress.setInfo(u'Der er sket en fejl i "{}"'.format(self.name))
            progress.setPercentage(100)
Пример #12
0
    def processAlgorithm(self, progress):
        """Here is where the processing itself takes place."""
        progress.setInfo(u'Start querying "{}" in PCJupiterXL...'.format(
            self.name))
        progress.setPercentage(50)

        pgtablename = u'borehole'
        input = self.getParameterValue(self.INPUT)
        fieldname = self.getParameterValue(self.DGUNR_FIELD)
        output = self.getOutputFromName(
            self.OUTPUT)  #<class 'processing.core.outputs.OutputVector'>

        JupiterAux.log_info('Valgte tabel med dgunummer: {}\n'.format(
            self.dktablename))

        jq = JupiterQGIS()
        ok_added, str_no_match, str_duplicates = jq.make_dguno_spatial(
            progress, pgtablename, input, fieldname, output)

        if ok_added:
            progress.setInfo(u'End querying "{}" in PCJupiterXL...'.format(
                self.name))
            progress.setPercentage(100)

            progress.setText(u'<br><b>RESULTAT:</b>')
            progress.setText(
                u'<br><b>Tabel: {} er åbnet med navnet: {}</b>'.format(
                    pgtablename, self.dktablename))
            progress.setText(u'<br><b>BEMÆRK:</b>')
            progress.setText(
                u'<br><b>Ikke fundet dguno: "{}" og fejl dublere: {}</b><br>'.
                format(str_no_match, str_duplicates))

        else:
            progress.setInfo(u'Der er sket en fejl i "{}"'.format(self.name))
            progress.setPercentage(100)
Пример #13
0
    def add_alphaview(self, progress, pglayername, output):
        """Load a non spatial table or view from postgresql - currently pesticide list
        :param progress: Information text and progress
        :param pglayername: Name of alpha view to load
        :param output: processing.core.outputs.OutputVector object
        :return: True if no error
        """
        db = JupiterDb()
        uri = db.getUri()
        uri.setDataSource("jupiter", pglayername, None)

        JupiterAux.log_info(
            'Loading alphalayer: {} from URI'.format(pglayername),
            progress=progress)

        ok, pglayer = self.getQgsVectorLayerFromUri(uri, pglayername)
        if not ok:
            return False

        if not self.writeOutputVector(
                progress, pglayer, output, isSpatial=False):
            return False

        return True
Пример #14
0
    def timeseries_onecompound_multipleborehole(self,
                                                boreholenolist,
                                                compound,
                                                datefrom,
                                                dateto,
                                                progress=None):
        """ Based of matplotlib.plot_date. Multiple borehole and one compound """

        from datetime import datetime

        def onclick(event):
            JupiterAux.msg_box(
                '%s click: button=%d, x=%d, y=%d, xdata=%f, ydata=%f' %
                ('double' if event.dblclick else 'single', event.button,
                 event.x, event.y, event.xdata, event.ydata))

        def onpick(event):
            thisline = event.artist
            borehole_graph_pick = thisline.get_label()

            #JupiterAux.msg_box('Picked borehole graph: {}'.format(borehole_graph_pick))

            #xdata = thisline.get_xdata()  #convert to  dates.num2date(dt)
            #ydata = thisline.get_ydata()
            #ind = event.ind
            #points = tuple(zip(xdata[ind], ydata[ind]))
            #JupiterAux.msg_box('{} - onpick points: {}'.format(borehole_graph_selection, points))

            qgis = JupiterQGIS()
            qgis.add_vertexmarker_borehole(borehole_graph_pick)

        # General Figure
        plt.figure(1)
        fig = plt.figure(1)
        plt.subplots_adjust(left=0.1, right=0.75, top=0.9, bottom=0.15)

        #cid = fig.canvas.mpl_connect('button_press_event', onclick)
        cid = fig.canvas.mpl_connect('pick_event', onpick)

        # General Axis
        ax = fig.add_subplot(1, 1, 1)

        # Draw compound limit as a horizontal line
        #plt.axhline(y=2.7)  only relevant for drwplant, no boreholes

        # X-Axis
        ax.set_xlabel(u'År')

        # Y-Axis - get unit of compound
        db = JupiterDb()
        unit_tuple_list = db.count_compound_units(compound)
        ax_ylabel = compound.title()
        if unit_tuple_list is None:
            # No unit for compound - not likely
            ax_ylabel += u' [???]'
            JupiterAux.msg_box(
                u'Bemærk der findes ingen enhed for stoffet: {} i PCJupiterXL'.
                format(compound))
        else:
            if len(unit_tuple_list) == 1:
                # Perfect - just one unit for compound
                unit_count, unit = unit_tuple_list[0]
                ax_ylabel += u' [{}]'.format(unit)
            elif len(unit_tuple_list) > 1:
                # More than one unit pr compound
                units = []
                for unit_count, unit in unit_tuple_list:
                    units.append(u'{}?'.format(unit))

                ax_ylabel = u' [{}]'.format(' '.join(units))
                JupiterAux.msg_box(
                    u'Bemærk stoffet: {} har flere enheder: ({}) i PCJupiterXL'
                    .format(compound, ', '.join(units)))

        ax.set_ylabel(ax_ylabel)

        ax.yaxis.grid()

        boreholes = boreholenolist.split(',')
        not_found = []
        borehole_index = 0

        for b in boreholes:
            borehole_index += 1

            if progress is not None:
                progress.setPercentage(borehole_index * 100 / len(boreholes))

            b = b.strip()

            # Get amount and dates for compound and boreholes
            amount, dt = db.get_timeserie(b, compound, datefrom, dateto)
            if amount is None:
                not_found.append(b)
                if len(boreholes) == 1:
                    return False, None
                else:
                    continue

            # Convert datetime to matplot numbers
            dt = dates.date2num(dt)
            plt.plot_date(dt,
                          amount,
                          linestyle='-',
                          markersize=3,
                          label=b,
                          picker=5)

        plt.xticks(rotation='vertical')
        plt.title('Tidsserie')
        plt.legend(bbox_to_anchor=(1.02, 1),
                   loc=2,
                   borderaxespad=0.,
                   shadow=True)

        plt.show()

        return True, not_found
Пример #15
0
 def getIcon(self):
     """Load icon """
     return QIcon(os.path.join(JupiterAux.pluginpath(), 'pix', 'jupiter_red.png'))
Пример #16
0
    def add_maplayer(self,
                     progress,
                     pglayername,
                     output,
                     extent,
                     selectionLayername=None,
                     rowid=None,
                     where_sql2=None):
        """Adds a postgis layer to map
        :type progress: Processing progressbar and info
        :type pglayername: string name of pglayer to select from Jupiter
        :param output: processing.core.outputs.OutputVector object
        :type extent: Bounding box of query, if none use selected geom(s) as bound
        :type selectionLayername: string name of layer with selected geom to use as border in query
        :type rowid: needed for qgis to open views
        :where_sql: additional sql, not only bound search ... update doc

        WARNING: Do not use semicolon after where sql at uri.setDataSource
        """

        # import sys
        # sys.path.append(r'C:\Program Files\JetBrains\PyCharm 2017.2.3\debug-eggs\pycharm-debug.egg')
        # import pydevd
        # pydevd.settrace('localhost', port=53100, stdoutToServer=True, stderrToServer=True)

        JupiterAux.log_info('add_maplayer: {}'.format(pglayername), progress)

        db = JupiterDb()
        uri = db.getUri()

        where_sql = ''
        # https://gis.stackexchange.com/questions/239601/sqlqueries-in-postgis-database-layer-using-python-and-qgis/239682#239682
        if extent == "0,0,0,0":
            ''' Query by geometry of selection in a layer '''

            wkt = self.selectedFeatureToWKT(selectionLayername)

            if not where_sql2:
                where_sql = "ST_WITHIN(geom , ST_GeomFromText('{}', 25832))".format(
                    wkt)
            else:
                where_sql = "ST_WITHIN(geom , ST_GeomFromText('{}', 25832) ) AND {}".format(
                    wkt, where_sql2)
        else:
            ''' Query by entered extent '''
            bbox = self.extentToBoundingbox(extent)

            if not where_sql2:
                where_sql = "geom && ST_MakeEnvelope({}, {}, {}, {}, 25832)". \
                    format(bbox.xMinimum(), bbox.yMinimum(), bbox.xMaximum(), bbox.yMaximum())
            else:
                where_sql = "geom && ST_MakeEnvelope({}, {}, {}, {}, 25832) AND {}" \
                    .format(bbox.xMinimum(), bbox.yMinimum(), bbox.xMaximum(), bbox.yMaximum(), where_sql2)

        uri.setDataSource("jupiter", pglayername, "geom", where_sql)

        JupiterAux.log_info(
            'Loading layer: "{}" from URI with where clause: "{}"'.format(
                pglayername, where_sql2),
            progress=progress)

        # Views must have defined a rowid
        if rowid:
            uri.setKeyColumn(rowid)

        ok, pglayer = self.getQgsVectorLayerFromUri(uri, pglayername)
        if not ok:
            return False

        if not self.writeOutputVector(progress, pglayer, output):
            return False

        #if not self.addStyle(pglayername, vlayer, uri):
        #return False

        # TODO  layer is not add to map until end of table_geoalgorithm.processAlgorithm
        # TODO  therefor is the showFeatureCount below not working
        # self.showFeatureCount(vlayer.name())

        return True
Пример #17
0
    def __init__(self):
        AlgorithmProvider.__init__(self)

        ## Try to clear the message log
        # from PyQt4.QtGui import QDockWidget
        # from qgis.utils import iface
        # consoleWidget = iface.mainWindow().findChild(QDockWidget, 'PythonConsole')
        # consoleWidget.console.shellOut.clearConsole()
        # MessageLog = iface.mainWindow().findChild(QDockWidget, 'MessageLog')

        # for child in iface.mainWindow().children():
        #    JupiterAux.log_info(child.objectName())

        ## Explained: Debugger between QGIS and pyCharm
        ## For the debugger to run the four lines below must be enabled - disable for qgis startup
        ## Enable the lines - run the debugger from pyCharm - and refresh plugin in QGIS

        if 1 == 2:
            import sys
            sys.path.append(r'C:\Program Files\JetBrains\PyCharm 2017.3.2\debug-eggs\pycharm-debug.egg')
            import pydevd
            pydevd.settrace('localhost', port=53100, stdoutToServer=True, stderrToServer=True)

        # Deactivate provider by default
        #self.activate = False

        JupiterAux.log_info('\n------------ Qupiter ------------')

        # Write out status information
        db = JupiterDb()
        #JupiterAux.log_info(u'Test DB connection: {}'.format(db.test_connection()))
        JupiterAux.log_info(u'{} version:\t\t{}'.format(JupiterAux.JUPITER, JupiterAux.get_meta_version()))
        JupiterAux.log_info(u'Sidste komplette restore:\t\t{} dage'.format(db.database_geus_export_time_in_days()))
        JupiterAux.log_info(u'Sidste DbSync synkronisation:\t{} dage'.format(db.database_dbsync_success_in_days()))
        JupiterAux.log_info(u'Yngste sample insert i databasen:\t{} dage'.format(db.database_youngest_insert_in_days()))

        #JupiterAux.log_info('Host: {} -- Database: {} -- User: {}'.format(

        #JupiterAux.enable_qgis_log()
        #JupiterAux.log_info('Global QGIS log enabled!')

        self.createAlgsList()
Пример #18
0
 def getIcon(self):
     """Load jupiter icon.
     """
     iconpath = os.path.join(JupiterAux.pluginpath(), 'pix', 'jupiter.png')
     return QIcon(iconpath)
Пример #19
0
    def processAlgorithm(self, progress):
        """Here is where the processing itself takes place
        """
        progress.setInfo(u'Start querying "{}" in PCJupiterXL...'.format(
            self.name))
        progress.setPercentage(10)

        # Get user input
        extent = self.getParameterValue(self.EXTENT)
        maplayerselection = self.getParameterValue(self.VECTOR_SELECTION)

        output = self.getOutputFromName(
            self.OUTPUT)  #<class 'processing.core.outputs.OutputVector'>

        rowid = None  # rowid on view is compulsory
        where_sql = None  # Time interval query

        if self.dktablename == u'Åbn boringstabellen':
            output.description = u'Boringer'
            pgtablename = u'borehole'
        elif self.dktablename == u'Åbn miljøboringer':
            output.description = u'Miljoeboringer'
            pgtablename = u'borehole'
            where_sql = "(geom is not null) and (use = 'L' or purpose = 'L')"
        elif self.dktablename == u'Åbn sløjfede boringer':
            output.description = u'Sloejfede boringer'
            rowid = 'objectid'
            pgtablename = u'mstmvw_boring_canceled'
        elif self.dktablename == u'Åbn GRUMO boringer':
            output.description = u'GRUMO boringer'
            rowid = 'row_id1'
            pgtablename = u'mstmvw_grumo_boringer'
        elif self.dktablename == u'Åbn anlægstabellen':
            output.description = u'Anlaeg'
            pgtablename = u'drwplant'
        elif self.dktablename == u'Åbn vandforsyningsboringer':
            output.description = u'Vandforsyningsboringer'
            rowid = 'row_id1'
            pgtablename = u'mstmvw_vandforsyningsboringer'
        elif self.dktablename == u'Åbn pejlinger':
            output.description = u'Pejlinger'
            rowid = 'row_id'
            pgtablename = u'mstmvw_waterlevel_all_dates'
        else:
            raise Exception(
                u'Tabel eller view: {} findes ikke i metoden_geoalgorithm.processAlgotithm'
                .format(self.dktablename))

        JupiterAux.log_info(
            u'Valgt tabel eller view: {} med pgtablename: {}\n'.format(
                self.dktablename, pgtablename))

        qgis = JupiterQGIS()
        ok_add_map = qgis.add_maplayer(progress,
                                       pgtablename,
                                       output,
                                       extent,
                                       selectionLayername=maplayerselection,
                                       rowid=rowid,
                                       where_sql2=where_sql)

        progress.setPercentage(100)

        if ok_add_map:
            progress.setInfo(u'End querying "{}" in PCJupiterXL...'.format(
                self.name))

            progress.setText(u'<br><b>RESULTAT:</b>')
            progress.setText(
                u'<br><b>Tabel med databasenavn: {} er åbnet som: {}</b>'.
                format(pgtablename, output.description))
        else:
            progress.setText(u'<br><b>Fejl i udtræk. Se log:</b>')
Пример #20
0
    def processAlgorithm(self, progress):
        """Here is where the processing itself takes place
        """
        progress.setInfo(u'Start querying "{}" in PCJupiterXL...'.format(self.name))
        progress.setPercentage(10)

        # Get user input
        extent = self.getParameterValue(self.EXTENT)
        maplayerselection = self.getParameterValue(self.VECTOR_SELECTION)
        date_to = self.getParameterValue(self.DATE_TO)
        date_from = self.getParameterValue(self.DATE_FROM)
        onlyload_latest = self.getParameterValue(self.LOAD_ONLY_LATEST)
        output = self.getOutputFromName(self.OUTPUT)  #<class 'processing.core.outputs.OutputVector'>

        where_sql = None        # Time interval query

        if self.dktablename == u'Beregn vandtype':
            output.description = u'Vandtype'
            if onlyload_latest:
                pgtablename = u'mstmvw_watertype4_latestdate'
            else:
                pgtablename = u'mstmvw_watertype4_alldates'
                where_sql = u"sampledate > to_date('{}', 'YYYY-MM-DD') AND sampledate < to_date('{}', 'YYYY-MM-DD')".format(date_from, date_to)
        elif self.dktablename == u'Beregn ionbalance':
            output.description = u'Ionbalance'
            if onlyload_latest:
                pgtablename = u'mstmvw_ionbalance_latest_dates'
            else:
                pgtablename = u'mstmvw_ionbalance_all_dates'
                where_sql = u"sampledate > to_date('{}', 'YYYY-MM-DD') AND sampledate < to_date('{}', 'YYYY-MM-DD')".format(date_from, date_to)
        elif self.dktablename == u'Hent uorganiske stoffer':
            output.description = u'Uorganiske stoffer'
            if onlyload_latest:
                pgtablename = u'mstmvw_inorganic_compound_latest_dates'
            else:
                pgtablename = u'mstmvw_inorganic_compound_all_dates'
                where_sql = u"sampledate > to_date('{}', 'YYYY-MM-DD') AND sampledate < to_date('{}', 'YYYY-MM-DD')".format(date_from, date_to)
        elif self.dktablename == u'Åbn pejlinger':
            output.description = u'Pejlinger'
            if onlyload_latest:
                pgtablename = u'mstmvw_waterlevel_latest_dates'
            else:
                pgtablename = u'mstmvw_waterlevel_all_dates'
                where_sql = u"pejledato > to_date('{}', 'YYYY-MM-DD') AND pejledato < to_date('{}', 'YYYY-MM-DD')".format(date_from, date_to)
        elif self.dktablename == u'Kombineret kemiskudtræk':
            output.description = u'Kemi'
            if onlyload_latest:
                pgtablename = u'mstmvw_combined_chemestry_latestdates'
            else:
                pgtablename = u'mstmvw_combined_chemestry_alldates'
                where_sql = u"sampledate > to_date('{}', 'YYYY-MM-DD') AND sampledate < to_date('{}', 'YYYY-MM-DD')".format(
                        date_from, date_to)
        else:
            raise Exception(u'Fejl. tabel eller view: {} findes ikke'.format(self.dktablename))

        JupiterAux.log_info(u'Valgt tabel eller view: {} med pgtablename: {}\n'.format(self.dktablename, pgtablename))

        jq = JupiterQGIS()
        ok_add_map = jq.add_maplayer(
            progress,
            pgtablename,
            output,
            extent,
            selectionLayername=maplayerselection,
            rowid='row_id',
            where_sql2=where_sql)

        progress.setPercentage(100)

        if ok_add_map:
            progress.setInfo(u'End querying "{}" in PCJupiterXL...'.format(self.name))

            progress.setText(u'<br><b>RESULTAT:</b>')
            progress.setText(u'<br><b>Tabel med databasenavn: {} er åbnet som: {}</b>'.format(pgtablename, output.description))
        else:
            progress.setText(u'<br><b>Fejl i udtræk. Se log:</b>')
Пример #21
0
    def scatterplot(self,
                    extent_or_wkt,
                    compoundname_x,
                    compoundname_y,
                    datefrom,
                    dateto,
                    extent_layer=None,
                    x_marker=None,
                    y_marker=None,
                    showannotations=False):
        """
        Create a scatter plot Either from boreholes in bbox or wkt selected geometries
        :param extent_or_wkt: Either a extent string or a wkt geometry
        :param compoundname_x: Compound name for x axe
        :param compoundname_y: Compound name for y axe
        :param datefrom: Query from date
        :param dateto: Query to date
        :param extent_layer: layername with selection. Only relevant if WKT bound.
        :param x_marker: marker line for given value
        :param y_marker: marker line for given value
        :return: True if no error
        :param showannotations: Show boreholeno label for each scatter point
        """
        def onpick(event):
            # Warning matplotlib fails in silence - https://matplotlib.org/examples/event_handling/pick_event_demo.html
            index = event.ind
            borehole_arr_pick = np.take(boreholenos, index)
            #JupiterAux.msg_box('onpick scatter: {}'.format(borehole_arr_pick))

            qgis = JupiterQGIS()
            for j, b in enumerate(borehole_arr_pick):
                if j == 0:
                    qgis.add_vertexmarker_borehole(b)
                else:
                    qgis.add_vertexmarker_borehole(b, keepExistingMarkers=True)

        db = JupiterDb()
        compoundno_x = db.compoundname_to_no(compoundname_x)
        compoundno_y = db.compoundname_to_no(compoundname_y)

        unit_x = db.get_unit_quess(compoundno_x)
        unit_y = db.get_unit_quess(compoundno_y)

        if compoundno_x is None or compoundno_y is None:
            JupiterAux.msg_box(
                'Et af de to indtastede stoffer: "{}, {}" findes ikke i PCJupiterXL'
                .format(compoundname1, compoundname2))
            return

        qgis = JupiterQGIS()
        qgis.remove_canvas_items()  # Remove marker from a previous plot

        boreholenos = []
        if extent_or_wkt != '0,0,0,0':
            bbox = qgis.extentToBoundingbox(extent_or_wkt)
            x, y, boreholenos = db.get_scatter_array_bbox(
                compoundno_x, compoundno_y, bbox, datefrom, dateto,
                compoundname_x, compoundname_y)
        else:
            wkt = qgis.selectedFeatureToWKT(extent_layer)
            x, y, boreholenos = db.get_scatter_array_wkt(
                compoundno_x, compoundno_y, wkt, datefrom, dateto,
                compoundname_x, compoundname_y)

        # General Figure
        plt.figure(1)
        fig = plt.figure(1)

        # Connect pick event on plot
        cid = fig.canvas.mpl_connect('pick_event', onpick)

        plt.scatter(
            x, y, alpha=0.8,
            picker=True)  # plt.scatter(x, y, s=area, c=colors, alpha=0.5)

        ax = fig.add_subplot(1, 1, 1)
        ax.set_xlabel('{} [{}]'.format(compoundname_x, unit_x))
        ax.set_ylabel('{} [{}]'.format(compoundname_y, unit_y))

        ax.xaxis.grid()
        ax.yaxis.grid()

        # label points in scatter plot
        if showannotations:
            for i, txt in enumerate(boreholenos):
                ax.annotate(str(txt), (x[i], y[i]))

        plt.axhline(y=y_marker)
        plt.axvline(x=x_marker)
        plt.title('Scatterplot')

        plt.show()

        return True
Пример #22
0
 def onclick(event):
     JupiterAux.msg_box(
         '%s click: button=%d, x=%d, y=%d, xdata=%f, ydata=%f' %
         ('double' if event.dblclick else 'single', event.button,
          event.x, event.y, event.xdata, event.ydata))
    def processAlgorithm(self, progress):
        """Here is where the processing itself takes place."""
        progress.setInfo(u'Start querying "{}" in PCJupiterXL...'.format(
            self.name))
        progress.setPercentage(50)

        extent = self.getParameterValue(self.EXTENT)
        extent_layer = self.getParameterValue(self.VECTOR_SELECTION)
        compoundname = unicode(self.getParameterValue(self.COMPOUNDNAME))
        compoundlimit = self.getParameterValue(self.COMPOUNDLIMIT)
        date_from = self.getParameterValue(self.DATE_FROM)
        date_to = self.getParameterValue(self.DATE_TO)
        onlyload_latest = self.getParameterValue(self.LOAD_ONLY_LATEST)
        output = self.getOutputFromName(self.OUTPUT)

        where_sql = None

        db = JupiterDb()
        compoundno = db.compoundname_to_no(compoundname)
        if compoundno is None:
            JupiterAux.msg_box(
                u'Stoffet: "{}" findes ikke i PCJupiterXL'.format(
                    compoundname))
            progress.setPercentage(100)
            return

        JupiterAux.log_info(u'\nprocessAlgorithm: {}'.format(self.tablename))

        output.description = compoundname

        if self.tablename == u'Søg et stof fra grundvand (boring)':
            if onlyload_latest:
                pgtablename = u'mstvw_bulk_grwchem_latestdates'
                where_sql = u"compoundno = {} AND amount > {} AND geom IS NOT NULL".format(
                    compoundno, compoundlimit)
            else:
                pgtablename = u'mstvw_bulk_grwchem'  #is alldates
                where_sql = u"sampledate > to_date('{}', 'YYYY-MM-DD') AND sampledate < to_date('{}', 'YYYY-MM-DD') AND compoundno = {} AND amount > {} AND geom IS NOT NULL".\
                    format(date_from, date_to, compoundno, compoundlimit)
        elif self.tablename == u'Søg et stof fra vandværk (anlæg)':
            if onlyload_latest:
                pgtablename = u'mstmvw_bulk_pltchem_latestdates'
                where_sql = u"compoundno = {} AND amount > {} AND geom IS NOT NULL".format(
                    compoundno, compoundlimit)
            else:
                pgtablename = u'mstmvw_bulk_pltchem_alldates'
                where_sql = u"sampledate > to_date('{}', 'YYYY-MM-DD') AND sampledate < to_date('{}', 'YYYY-MM-DD') AND compoundno = {} AND amount > {} AND geom IS NOT NULL".\
                    format(date_from, date_to, compoundno, compoundlimit)
        else:
            raise Exception(u'Fejl: Tabel eller view: "{}" findes ikke'.format(
                self.tablename))

        jq = JupiterQGIS()
        ok_add_map = jq.add_maplayer(progress,
                                     pgtablename,
                                     output,
                                     extent,
                                     selectionLayername=extent_layer,
                                     rowid='row_id',
                                     where_sql2=where_sql)

        if ok_add_map:
            progress.setInfo(u'End querying "{}" in PCJupiterXL...'.format(
                self.name))

            progress.setText(u'<br><b>RESULTAT:</b>')
            progress.setText(
                u'<br><b>Tabel {} er åbnet med navnet {}</b>'.format(
                    self.tablename, compoundname))
        else:
            progress.setInfo(u'Der er sket en fejl i "{}"'.format(self.name))