Exemplo n.º 1
0
    def print_selected_features(self):
        """ Returns a list of obsid as unicode

            thelayer is an optional argument, if not given then activelayer is used
        """

        activelayer = utils.get_active_layer()
        if activelayer is not self.activelayer:
            self.reload_combobox()
            utils.MessagebarAndLog.warning(
                bar_msg=ru(QCoreApplication.translate('ValuesFromSelectedFeaturesGui', 'Column list reloaded. Select column and press Ok.')))
            return None

        self.selected_column = self.columns.currentText()

        selected_values = utils.getselectedobjectnames(thelayer=self.activelayer, column_name=self.selected_column)
        if not selected_values:
            utils.MessagebarAndLog.info(bar_msg=ru(QCoreApplication.translate('ValuesFromSelectedFeaturesGui',
                                                                              'No features selected!')))
        else:
            if self.unique_sorted_list_checkbox.isChecked():
                selected_values = sorted(set(selected_values))
            nr = len(selected_values)
            utils.MessagebarAndLog.info(bar_msg=ru(
                QCoreApplication.translate('ValuesFromSelectedFeaturesGui',
                                           'List of %s selected %s written to log'))%(str(nr), self.selected_column),
                                        log_msg='{} IN ({})'.format(self.selected_column,
                                            ', '.join(["'{}'".format(value) if value is not None else 'NULL'
                                                        for value in selected_values])))
            self.close()
    def calcselected(self):
        obsar = utils.getselectedobjectnames(self.layer)
        observations = obsar
        i=0
        for obs in obsar:
                observations[i] = obs.encode('utf-8') #turn into a list of python byte strings
                i += 1        
        fr_d_t = self.FromDateTime.dateTime().toPyDateTime()
        to_d_t = self.ToDateTime.dateTime().toPyDateTime()

        sanity1 = utils.sql_load_fr_db("""SELECT obs_points.h_toc FROM obs_points LEFT JOIN w_levels WHERE w_levels.obsid = obs_points.obsid AND obs_points.obsid IN """ + (str(observations)).encode('utf-8').replace('[','(').replace(']',')'))[1]
        sanity2 = utils.sql_load_fr_db("""SELECT obs_points.h_toc FROM obs_points LEFT JOIN w_levels WHERE w_levels.obsid = obs_points.obsid AND obs_points.h_toc NOT NULL  AND obs_points.obsid IN """ + (str(observations)).encode('utf-8').replace('[','(').replace(']',')'))[1]

        if len(sanity1) == len(sanity2): #only if h_toc exists for all objects
            sql1 = """UPDATE OR IGNORE w_levels SET h_toc = (SELECT obs_points.h_toc FROM obs_points WHERE w_levels.obsid = obs_points.obsid) WHERE obsid IN """
            sql1 += str(observations)
            sql1 += """ AND date_time >= '"""
            sql1 += str(fr_d_t)
            sql1 += """' AND date_time <= '"""
            sql1 += str(to_d_t)
            sql1 += """' """   
            utils.sql_alter_db(sql1.replace("[","(").replace("]",")"))
            sql2 = """UPDATE OR IGNORE w_levels SET level_masl = h_toc - meas WHERE obsid IN """
            sql2 += str(observations)
            sql2 += """ AND date_time >= '"""
            sql2 += str(fr_d_t)
            sql2 += """' AND date_time <= '"""
            sql2 += str(to_d_t)
            sql2 += """' """        
            utils.sql_alter_db(sql2.replace("[","(").replace("]",")"))
            self.close()        
        else:
            utils.pop_up_info('Calculation aborted! There seems to be NULL values in your table obs_points, column h_toc.','Error')
            self.close()
 def drillreport(self):
     general_metadata = [x for x in self.general_metadata.toPlainText().split('\n') if x]
     geo_metadata = [x for x in self.geo_metadata.toPlainText().split('\n') if x]
     strat_columns = [x for x in self.strat_columns.toPlainText().split('\n') if x]
     header_in_table = self.header_in_table.isChecked()
     skip_empty = self.skip_empty.isChecked()
     include_comments = self.include_comments.isChecked()
     obsids = sorted(utils.getselectedobjectnames(qgis.utils.iface.activeLayer()))  # selected obs_point is now found in obsid[0]
     general_metadata_header = self.general_metadata_header.text()
     geo_metadata_header = self.geo_metadata_header.text()
     strat_columns_header = self.strat_columns_header.text()
     comment_header = self.comment_header.text()
     empty_row_between_obsids = self.empty_row_between_obsids.isChecked()
     topleft_topright_colwidths = self.topleft_topright_colwidths.text().split(';')
     general_colwidth = self.general_colwidth.text().split(';')
     geo_colwidth = self.geo_colwidth.text().split(';')
     decimal_separator = self.decimal_separator.text()
     if not obsids:
         utils.MessagebarAndLog.critical(bar_msg=ru(QCoreApplication.translate('DrillreportUi', 'Must select at least 1 obsid in selected layer')))
         raise utils.UsageError()
     self.save_stored_settings()
     drillrep = Drillreport(obsids, self.ms, general_metadata, geo_metadata, strat_columns, header_in_table,
                            skip_empty, include_comments, general_metadata_header, geo_metadata_header, strat_columns_header,
                            comment_header, empty_row_between_obsids, topleft_topright_colwidths, general_colwidth,
                            geo_colwidth, decimal_separator)
Exemplo n.º 4
0
 def get_selected_observations(self):
     obsar = utils.getselectedobjectnames(self.activelayer)
     observations = obsar
     i=0
     for obs in obsar:
             observations[i] = obs.encode('utf-8') #turn into a list of python byte strings
             i += 1 
     self.observations=observations#A list with selected obsid
 def calcselected(self):
     obsids = ru(utils.getselectedobjectnames(self.layer), keep_containers=True)
     if not obsids:
         utils.pop_up_info(ru(QCoreApplication.translate('Calclvl',
                                                         'Adjustment aborted! No obsids selected.')),
                           ru(QCoreApplication.translate('Calclvl', 'Error')))
     else:
         self.calc(obsids)
Exemplo n.º 6
0
 def get_selected_observations(self):
     obsar = utils.getselectedobjectnames(self.activelayer)
     observations = obsar
     i = 0
     for obs in obsar:
         observations[i] = obs.encode(
             'utf-8')  #turn into a list of python byte strings
         i += 1
     self.observations = observations  #A list with selected obsid
 def drillreport(self):
     general_metadata = [
         x for x in self.general_metadata.toPlainText().split('\n') if x
     ]
     geo_metadata = [
         x for x in self.geo_metadata.toPlainText().split('\n') if x
     ]
     strat_columns = [
         x for x in self.strat_columns.toPlainText().split('\n') if x
     ]
     header_in_table = self.header_in_table.isChecked()
     skip_empty = self.skip_empty.isChecked()
     include_comments = self.include_comments.isChecked()
     obsids = sorted(
         utils.getselectedobjectnames(qgis.utils.iface.activeLayer())
     )  # selected obs_point is now found in obsid[0]
     general_metadata_header = self.general_metadata_header.text()
     geo_metadata_header = self.geo_metadata_header.text()
     strat_columns_header = self.strat_columns_header.text()
     comment_header = self.comment_header.text()
     empty_row_between_obsids = self.empty_row_between_obsids.isChecked()
     topleft_topright_colwidths = self.topleft_topright_colwidths.text(
     ).split(';')
     general_colwidth = self.general_colwidth.text().split(';')
     geo_colwidth = self.geo_colwidth.text().split(';')
     decimal_separator = self.decimal_separator.text()
     if not obsids:
         utils.MessagebarAndLog.critical(bar_msg=ru(
             QCoreApplication.translate(
                 'DrillreportUi',
                 'Must select at least 1 obsid in selected layer')))
         raise utils.UsageError()
     self.save_stored_settings()
     drillrep = Drillreport(obsids, self.ms, general_metadata, geo_metadata,
                            strat_columns, header_in_table, skip_empty,
                            include_comments, general_metadata_header,
                            geo_metadata_header, strat_columns_header,
                            comment_header, empty_row_between_obsids,
                            topleft_topright_colwidths, general_colwidth,
                            geo_colwidth, decimal_separator)
Exemplo n.º 8
0
 def get_selected_observations(self):
     self.observations = utils.getselectedobjectnames(self.activelayer)
    def __init__(self, settingsdict, num_data_cols, rowheader_colwidth_percent,
                 empty_row_between_tables, page_break_between_tables,
                 from_active_layer, sql_table):
        #show the user this may take a long time...
        utils.start_waiting_cursor()

        self.nr_header_rows = 3

        reportfolder = os.path.join(QDir.tempPath(), 'midvatten_reports')
        if not os.path.exists(reportfolder):
            os.makedirs(reportfolder)
        reportpath = os.path.join(reportfolder, "w_qual_report.html")
        f = codecs.open(reportpath, "wb", "utf-8")

        #write some initiating html
        rpt = r"""<head><title>%s</title></head>""" % ru(
            QCoreApplication.translate(
                'Wqualreport',
                'water quality report from Midvatten plugin for QGIS'))
        rpt += r""" <meta http-equiv="content-type" content="text/html; charset=utf-8" />"""  #NOTE, all report data must be in 'utf-8'
        rpt += "<html><body>"
        f.write(rpt)

        if from_active_layer:
            utils.pop_up_info(
                ru(
                    QCoreApplication.translate(
                        'CompactWqualReport',
                        'Check that exported number of rows are identical to expected number of rows!\nFeatures in layers from sql queries can be invalid and then excluded from the report!'
                    )), 'Warning!')
            w_qual_lab_layer = qgis.utils.iface.activeLayer()
            if w_qual_lab_layer is None:
                raise utils.UsageError(
                    ru(
                        QCoreApplication.translate('CompactWqualReport',
                                                   'Must select a layer!')))
            if not w_qual_lab_layer.selectedFeatureCount():
                w_qual_lab_layer.selectAll()
            data = self.get_data_from_qgislayer(w_qual_lab_layer)
        else:
            data = self.get_data_from_sql(sql_table,
                                          utils.getselectedobjectnames())

        report_data, num_data = self.data_to_printlist(data)
        utils.MessagebarAndLog.info(bar_msg=ru(
            QCoreApplication.translate(
                'CompactWqualReport',
                'Created report from %s number of rows.')) % str(num_data))

        for startcol in range(1, len(report_data[0]), num_data_cols):
            printlist = [[row[0]] for row in report_data]
            for rownr, row in enumerate(report_data):
                printlist[rownr].extend(
                    row[startcol:min(startcol + num_data_cols, len(row))])

            filtered = [row for row in printlist if any(row[1:])]

            self.htmlcols = len(filtered[0])
            self.WriteHTMLReport(
                filtered,
                f,
                rowheader_colwidth_percent,
                empty_row_between_tables=empty_row_between_tables,
                page_break_between_tables=page_break_between_tables)

        # write some finishing html and close the file
        f.write("\n</body></html>")
        f.close()

        utils.stop_waiting_cursor(
        )  # now this long process is done and the cursor is back as normal

        if report_data:
            QDesktopServices.openUrl(QUrl.fromLocalFile(reportpath))
Exemplo n.º 10
0
 def get_selected_observations(self):
     self.observations = utils.getselectedobjectnames(self.activelayer)
    def __init__(self, settingsdict, num_data_cols, rowheader_colwidth_percent,
                 empty_row_between_tables, page_break_between_tables,
                 from_active_layer, sql_table, sort_parameters_alphabetically,
                 sort_by_obsid, date_time_as_columns, date_time_format, method,
                 data_column):
        #show the user this may take a long time...

        reportfolder = os.path.join(QDir.tempPath(), 'midvatten_reports')
        if not os.path.exists(reportfolder):
            os.makedirs(reportfolder)
        reportpath = os.path.join(reportfolder, "w_qual_report.html")
        f = codecs.open(reportpath, "wb", "utf-8")

        #write some initiating html
        rpt = r"""<head><title>%s</title></head>""" % ru(
            QCoreApplication.translate(
                'Wqualreport',
                'water quality report from Midvatten plugin for QGIS'))
        rpt += r""" <meta http-equiv="content-type" content="text/html; charset=utf-8" />"""  #NOTE, all report data must be in 'utf-8'
        rpt += "<html><body>"
        f.write(rpt)

        if date_time_as_columns:
            data_columns = [
                'obsid', 'date_time', 'report', 'parameter', 'unit',
                data_column
            ]
        else:
            data_columns = [
                'obsid', 'date_time', 'parameter', 'unit', data_column
            ]

        if from_active_layer:
            w_qual_lab_layer = qgis.utils.iface.activeLayer()
            if w_qual_lab_layer is None:
                raise utils.UsageError(
                    ru(
                        QCoreApplication.translate('CompactWqualReport',
                                                   'Must select a layer!')))
            if not w_qual_lab_layer.selectedFeatureCount():
                w_qual_lab_layer.selectAll()
            df = self.get_data_from_qgislayer(w_qual_lab_layer, data_columns)
        else:
            df = self.get_data_from_sql(sql_table,
                                        utils.getselectedobjectnames(),
                                        data_columns)

        if date_time_as_columns:
            columns = ['obsid', 'date_time', 'report']
            rows = ['parunit']
            values = [data_column]
            report_data = self.data_to_printlist(
                df, list(columns), list(rows), values,
                sort_parameters_alphabetically, sort_by_obsid, method,
                date_time_format)
        else:
            columns = ['obsid']
            rows = ['parunit', 'date_time']
            values = [data_column]
            report_data = self.data_to_printlist(
                df, list(columns), list(rows), values,
                sort_parameters_alphabetically, sort_by_obsid, method,
                date_time_format)

        # Split the data into separate tables with the specified number of columns
        for startcol in range(len(rows), len(report_data[0]), num_data_cols):
            printlist = [row[:len(rows)] for row in report_data]
            for rownr, row in enumerate(report_data):
                printlist[rownr].extend(
                    row[startcol:min(startcol + num_data_cols, len(row))])

            filtered = [row for row in printlist if any(row[len(rows):])]

            self.htmlcols = len(filtered[0])
            self.write_html_table(
                filtered,
                f,
                rowheader_colwidth_percent,
                empty_row_between_tables=empty_row_between_tables,
                page_break_between_tables=page_break_between_tables,
                nr_header_rows=len(columns),
                nr_row_header_columns=len(rows))

        # write some finishing html and close the file
        f.write("\n</body></html>")
        f.close()

        if report_data:
            QDesktopServices.openUrl(QUrl.fromLocalFile(reportpath))