Beispiel #1
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
    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))
    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
 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 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
    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))