コード例 #1
0
ファイル: QgsManager.py プロジェクト: lvanoni/QGISFMV
    def AddFileRowToManager(self,
                            name,
                            filename,
                            load_id=None,
                            islocal=False,
                            klv_folder=None):
        ''' Add file Video to new Row '''
        # We limit the number of videos due to the buffer
        if self.VManager.rowCount() > 5:
            qgsu.showUserAndLogMessage(
                QCoreApplication.translate(
                    "ManagerDock",
                    "You must delete some video from the list before adding a new one"
                ))
            return

        self.islocal = islocal
        self.klv_folder = klv_folder
        self.isStreaming = False
        w = QWidget()
        layout = QVBoxLayout()
        pbar = QProgressBar()
        layout.addWidget(pbar)
        w.setLayout(layout)
        rowPosition = self.VManager.rowCount()

        pbar.setGeometry(0, 0, 300, 30)
        pbar.setValue(0)
        pbar.setMaximumHeight(30)

        if load_id is None:
            row_id = 0
            if rowPosition != 0:
                row_id = int(self.VManager.item(rowPosition - 1, 0).text()) + 1
        else:
            row_id = load_id

        self.VManager.insertRow(rowPosition)

        self.VManager.setItem(rowPosition, 0, QTableWidgetItem(str(row_id)))

        self.VManager.setItem(rowPosition, 1, QTableWidgetItem(name))
        self.VManager.setItem(
            rowPosition, 2,
            QTableWidgetItem(
                QCoreApplication.translate("ManagerDock", "Loading")))
        self.VManager.setItem(rowPosition, 3, QTableWidgetItem(filename))
        self.VManager.setItem(rowPosition, 4, QTableWidgetItem("-"))
        self.VManager.setCellWidget(rowPosition, 5, w)

        self.VManager.setVisible(False)
        self.VManager.horizontalHeader().setStretchLastSection(True)
        self.VManager.setVisible(True)

        # resolve if it is a stream
        if "://" in filename:
            self.isStreaming = True

        if not self.isStreaming:
            # Disable row if not exist video file
            if not os.path.exists(filename):
                self.ToggleActiveRow(rowPosition, value="Missing source file")
                for j in range(self.VManager.columnCount()):
                    try:
                        self.VManager.item(rowPosition,
                                           j).setFlags(Qt.NoItemFlags
                                                       | Qt.ItemIsEnabled)
                        self.VManager.item(rowPosition, j).setBackground(
                            QColor(211, 211, 211))
                    except Exception:
                        self.VManager.cellWidget(rowPosition, j).setStyleSheet(
                            "background-color:rgb(211,211,211);")
                        pass
                return

            pbar.setValue(30)
            info = FFMpeg().probe(filename)
            if info is None:
                qgsu.showUserAndLogMessage(
                    QCoreApplication.translate("ManagerDock",
                                               "Failed loading FFMPEG ! "))
                return
            info.format.duration
            # init non-blocking metadata buffered reader
            self.meta_reader[str(rowPosition)] = BufferedMetaReader(
                filename, pass_time=self.pass_time)
            qgsu.showUserAndLogMessage(
                "",
                "buffered non-blocking metadata reader initialized.",
                onlyLog=True)

            pbar.setValue(60)
            try:
                # init point we can center the video on
                self.initialPt[str(rowPosition)] = getVideoLocationInfo(
                    filename, islocal, klv_folder)
                if not self.initialPt[str(rowPosition)]:
                    self.VManager.setItem(
                        rowPosition, 4,
                        QTableWidgetItem(
                            QCoreApplication.translate(
                                "ManagerDock",
                                "Start location not available.")))
                    self.ToggleActiveRow(rowPosition, value="Not MISB")
                    pbar.setValue(99)
                    return
                else:
                    self.VManager.setItem(
                        rowPosition, 4,
                        QTableWidgetItem(self.initialPt[str(rowPosition)][2]))
            except Exception:
                qgsu.showUserAndLogMessage(
                    QCoreApplication.translate(
                        "ManagerDock", "This video don't have Metadata ! "))
                pbar.setValue(99)
                self.ToggleActiveRow(rowPosition, value="Not MISB")
                return

            pbar.setValue(90)

            dtm_path = parser['GENERAL']['DTM_file']
            if self.initialPt[str(rowPosition)] and dtm_path != '':
                try:
                    initElevationModel(self.initialPt[str(rowPosition)][0],
                                       self.initialPt[str(rowPosition)][1],
                                       dtm_path)
                    qgsu.showUserAndLogMessage("",
                                               "Elevation model initialized.",
                                               onlyLog=True)
                except Exception:
                    None
        else:
            self.meta_reader[str(rowPosition)] = StreamMetaReader(filename)
            qgsu.showUserAndLogMessage("",
                                       "StreamMetaReader initialized.",
                                       onlyLog=True)
            self.initialPt[str(rowPosition)] = None

        pbar.setValue(100)
        if islocal:
            self.ToggleActiveRow(rowPosition, value="Ready Local")
        else:
            self.ToggleActiveRow(rowPosition, value="Ready")
        # Add video to settings list
        AddVideoToSettings(str(row_id), filename)
コード例 #2
0
    def AddFileRowToManager(self,
                            name,
                            filename,
                            load_id=None,
                            islocal=False,
                            klv_folder=None):
        ''' Add file Video to new Row '''
        # We limit the number of videos due to the buffer
        self.loading = True
        if self.VManager.rowCount() > 5:
            qgsu.showUserAndLogMessage(QCoreApplication.translate(
                "ManagerDock",
                "You must delete some video from the list before adding a new one"
            ),
                                       level=QGis.Warning)
            self.loading = False
            return

        self.islocal = islocal
        self.klv_folder = klv_folder
        w = QWidget()
        layout = QVBoxLayout()
        pbar = QProgressBar()
        layout.addWidget(pbar)
        w.setLayout(layout)
        rowPosition = self.VManager.rowCount()
        self.videoPlayable.append(False)

        pbar.setGeometry(0, 0, 300, 30)
        pbar.setValue(0)
        pbar.setMaximumHeight(30)

        if load_id is None:
            row_id = 0
            if rowPosition != 0:
                row_id = int(self.VManager.item(rowPosition - 1, 0).text()) + 1
        else:
            row_id = load_id

        self.VManager.insertRow(rowPosition)

        self.VManager.setItem(rowPosition, 0, QTableWidgetItem(str(row_id)))

        self.VManager.setItem(rowPosition, 1, QTableWidgetItem(name))
        self.VManager.setItem(
            rowPosition, 2,
            QTableWidgetItem(
                QCoreApplication.translate("ManagerDock", "Loading")))
        self.VManager.setItem(rowPosition, 3, QTableWidgetItem(filename))
        self.VManager.setItem(rowPosition, 4, QTableWidgetItem("-"))
        self.VManager.setCellWidget(rowPosition, 5, w)

        self.VManager.setVisible(False)
        self.VManager.horizontalHeader().setStretchLastSection(True)
        self.VManager.setVisible(True)

        # resolve if it is a stream
        if "://" in filename:
            self.videoIsStreaming.append(True)
        else:
            self.videoIsStreaming.append(False)

        if not self.videoIsStreaming[-1]:
            # Disable row if not exist video file
            if not os.path.exists(filename):
                self.ToggleActiveRow(rowPosition, value="Missing source file")
                for j in range(self.VManager.columnCount()):
                    try:
                        self.VManager.item(rowPosition,
                                           j).setFlags(Qt.NoItemFlags
                                                       | Qt.ItemIsEnabled)
                        self.VManager.item(rowPosition, j).setBackground(
                            QColor(211, 211, 211))
                    except Exception:
                        self.VManager.cellWidget(rowPosition, j).setStyleSheet(
                            "background-color:rgb(211,211,211);")
                        pass
                self.loading = False
                return

            pbar.setValue(30)
            info = FFMpeg().probe(filename)
            if info is None:
                qgsu.showUserAndLogMessage(
                    QCoreApplication.translate("ManagerDock",
                                               "Failed loading FFMPEG ! "))

            klvIdx = getKlvStreamIndex(filename, islocal)

            # init non-blocking metadata buffered reader
            self.meta_reader.append(
                BufferedMetaReader(filename,
                                   klv_index=klvIdx,
                                   pass_time=self.pass_time,
                                   interval=self.buf_interval))

            pbar.setValue(60)
            try:
                # init point we can center the video on
                self.initialPt.append(
                    getVideoLocationInfo(filename, islocal, klv_folder))
                if not self.initialPt[rowPosition]:
                    self.VManager.setItem(
                        rowPosition, 4,
                        QTableWidgetItem(
                            QCoreApplication.translate(
                                "ManagerDock",
                                "Start location not available.")))
                    self.ToggleActiveRow(rowPosition,
                                         value="Video not applicable")
                    pbar.setValue(100)

                else:
                    self.VManager.setItem(
                        rowPosition, 4,
                        QTableWidgetItem(self.initialPt[rowPosition][2]))
                    pbar.setValue(90)
                    self.videoPlayable[rowPosition] = True
            except Exception:
                qgsu.showUserAndLogMessage(
                    QCoreApplication.translate(
                        "ManagerDock", "This video doesn't have Metadata ! "))
                pbar.setValue(100)
                self.ToggleActiveRow(rowPosition, value="Video not applicable")

        else:
            self.meta_reader.append(StreamMetaReader(filename))
            qgsu.showUserAndLogMessage("",
                                       "StreamMetaReader initialized.",
                                       onlyLog=True)
            self.initialPt.append(None)
            self.videoPlayable[rowPosition] = True

        url = ""
        if self.videoIsStreaming[-1]:
            # show video from splitter (port +1)
            oldPort = filename.split(":")[2]
            newPort = str(int(oldPort) + 10)
            proto = filename.split(":")[0]
            url = QUrl(proto + "://127.0.0.1:" + newPort)
        else:
            url = QUrl.fromLocalFile(filename)

        self.playlist.addMedia(QMediaContent(url))

        if self.videoPlayable[rowPosition]:
            pbar.setValue(100)
            if islocal:
                self.ToggleActiveRow(rowPosition, value="Ready Local")
            else:
                self.ToggleActiveRow(rowPosition, value="Ready")
            # Add video to settings list
            AddVideoToSettings(str(row_id), filename)

        self.loading = False
コード例 #3
0
ファイル: form.py プロジェクト: caiohamamura/kuwaharafilter
class Ui_form1(object):
    def setupUi(self, form1):
        form1.setObjectName(_fromUtf8("form1"))
        form1.resize(400, 253)
        form1.setFocusPolicy(QtCore.Qt.TabFocus)
        form1.setWindowTitle(_fromUtf8("Kuwahara filter"))
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/qgis.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        form1.setWindowIcon(icon)
        self.label = QLabel(form1)
        self.label.setGeometry(QtCore.QRect(21, 10, 111, 20))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.label.setFont(font)
        self.label.setToolTip(_fromUtf8(""))
        self.label.setObjectName(_fromUtf8("label"))
        self.outputb = QPushButton(form1)
        self.outputb.setGeometry(QtCore.QRect(320, 47, 31, 23))
        self.outputb.setObjectName(_fromUtf8("outputb"))
        self.label_2 = QLabel(form1)
        self.label_2.setGeometry(QtCore.QRect(22, 49, 101, 20))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.label_2.setFont(font)
        self.label_2.setToolTip(_fromUtf8(""))
        self.label_2.setObjectName(_fromUtf8("label_2"))
        self.progressBar = QProgressBar(form1)
        self.progressBar.setGeometry(QtCore.QRect(19, 220, 361, 23))
        self.progressBar.setProperty(_fromUtf8("value"), 24)
        self.progressBar.setObjectName(_fromUtf8("progressBar"))
        self.label_3 = QLabel(form1)
        self.label_3.setGeometry(QtCore.QRect(22, 88, 131, 20))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.label_3.setFont(font)
        self.label_3.setObjectName(_fromUtf8("label_3"))
        self.label_4 = QLabel(form1)
        self.label_4.setGeometry(QtCore.QRect(21, 125, 181, 20))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.label_4.setFont(font)
        self.label_4.setObjectName(_fromUtf8("label_4"))
        self.run = QPushButton(form1)
        self.run.setGeometry(QtCore.QRect(139, 185, 101, 23))
        self.run.setObjectName(_fromUtf8("run"))
        self.inputbox = QgsMapLayerComboBox(form1)
        self.inputbox.setGeometry(QtCore.QRect(141, 10, 170, 22))
        self.inputbox.setObjectName(_fromUtf8("input"))
        self.output = QLineEdit(form1)
        self.output.setGeometry(QtCore.QRect(149, 45, 160, 28))
        self.output.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
        self.output.setObjectName(_fromUtf8("output"))
        self.refb = QLineEdit(form1)
        self.refb.setGeometry(QtCore.QRect(149, 82, 160, 28))
        self.refb.setObjectName(_fromUtf8("refb"))
        self.mem = QLineEdit(form1)
        self.mem.setGeometry(QtCore.QRect(208, 120, 101, 28))
        self.mem.setObjectName(_fromUtf8("mem"))
        self.addout = QCheckBox(form1)
        self.addout.setGeometry(QtCore.QRect(100, 158, 171, 17))
        self.addout.setChecked(True)
        self.addout.setObjectName(_fromUtf8("checkBox"))
        self.inputb = QPushButton(form1)
        self.inputb.setGeometry(QtCore.QRect(320, 10, 31, 23))
        self.inputb.setObjectName(_fromUtf8("inputb"))
        self.retranslateUi(form1)
        self.setWindowFlags(QtCore.Qt.WindowFlags(QtCore.Qt.WindowMinimizeButtonHint | QtCore.Qt.WindowMaximizeButtonHint | QtCore.Qt.WindowCloseButtonHint))
        QtCore.QMetaObject.connectSlotsByName(form1)
    def retranslateUi(self, form1):
        self.label.setText(QtCore.QCoreApplication.translate("form1", "Input raster"))
        self.outputb.setText("...")
        self.label_2.setText(QApplication.translate("form1", "Output raster"))
        self.label_3.setToolTip(QApplication.translate("form1", "Reference band from which variances will be calculated to choose subwindow mean."))
        self.label_3.setText(QApplication.translate("form1", "Reference band"))
        self.label_4.setToolTip(QApplication.translate("form1", "Maximum memory usage in megabytes (it is an approximated value, since algorithm will only choose how many lines will be read at once)."))
        self.label_4.setText(QApplication.translate("form1", "Max memory usage (MB)"))
        self.run.setText(QApplication.translate("form1", "Run"))
        self.output.setPlaceholderText(QApplication.translate("form1", "<temporary file>"))
        self.refb.setToolTip(QApplication.translate("form1", "Reference band from which variances will be calculated to choose subwindow mean."))
        self.refb.setText("1")
        self.mem.setToolTip(QApplication.translate("form1", "Maximum memory usage in MeB (it is an approximated value, since algorithm will only choose how many lines will be read at once)."))
        self.mem.setText("100")
        self.addout.setText(QApplication.translate("form1", "Add results to project"))
        self.inputb.setText("...")
コード例 #4
0
class IDESCaliWebServices:
    def __init__(self, iFace):
        self.iFace = iFace
        self.plugin_dir = os.path.dirname(__file__)
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'IDESCaliWebServices_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        self.dlg = IDESCaliWebServicesDialog()
        self.dlginfo = InfoDialog()
        self.generatedService = None
        self.bar = QProgressBar()
        self.bar.setRange(0, 0)
        self.bar.setGeometry(950, 500, 200, 25)
        self.actions = []
        self.menu = self.tr(u'&Servicios WMS - Geoportal IDESC')
        self.first_start = None

    def tr(self, message):
        return QCoreApplication.translate('IDESCaliWebServices', message)

    def add_action(self,
                   icon_path,
                   text,
                   callback,
                   enabled_flag=True,
                   add_to_menu=True,
                   add_to_toolbar=True,
                   status_tip=None,
                   whats_this=None,
                   parent=None):

        icon = QIcon(icon_path)
        action = QAction(icon, text, parent)
        action.triggered.connect(callback)
        action.setEnabled(enabled_flag)

        if status_tip is not None:
            action.setStatusTip(status_tip)

        if whats_this is not None:
            action.setWhatsThis(whats_this)

        if add_to_toolbar:
            self.iFace.addToolBarIcon(action)

        if add_to_menu:
            self.iFace.addPluginToWebMenu(self.menu, action)

        self.actions.append(action)

        return action

    def initGui(self):
        self.add_all_action()
        self.dlg.table_widget.itemSelectionChanged.connect(self.updateDesc)
        self.dlg.help_button.clicked.connect(self.openDlgInfo)
        self.dlg.close_button.clicked.connect(self.closeDlg)
        self.dlg.search_box.textEdited.connect(self.search)
        self.dlg.add_button.released.connect(self.loadWebService)
        self.dlginfo.ok_dialog.released.connect(self.closeAbout)
        self.first_start = True

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iFace.removePluginWebMenu(
                self.tr(u'&Servicios WMS - Geoportal IDESC'), action)
            self.iFace.removeToolBarIcon(action)

    def run(self):
        if self.generatedService.web_map_service is not None:
            self.dlg.search_box.clear()
            self.fill_table(self.generatedService.web_map_service.contents)
            self.dlg.show()
            result = self.dlg.exec_()
            if result:
                pass

    def run_0(self):
        self.loadServiceList(Service.IDESCaliDataset.value)
        self.run()

    def add_all_action(self):
        icon_path = ':/plugins/idescali_ws/icon.png'

        self.add_action(icon_path,
                        text=self.tr(
                            service_text_map[Service.IDESCaliDataset.value]),
                        callback=self.run_0,
                        whats_this=str(Service.IDESCaliDataset.value),
                        parent=self.iFace.mainWindow())

    def loadServiceList(self, service_id: int):
        self.generatedService = WebMapServiceClass(service_id)
        url = self.generatedService.service_url
        self.bar.show()
        if self.generatedService.service_type == ServiceType.WebMapService.value:
            try:
                wms = WebMapService(url)
                self.generatedService.setWebMapService(wms)
            except Exception as e:
                QMessageBox.information(
                    None, "ERROR:",
                    'No se puede cargar este servicio en este momento.' +
                    str(e))
        elif self.generatedService.service_type == ServiceType.WebMapTileService.value:
            try:
                wmts = WebMapTileService(url)
                self.generatedService.setWebMapService(wmts)
            except Exception as e:
                QMessageBox.information(
                    None, "ERROR:",
                    'No se puede acceder a este servicio en este momento.' +
                    str(e))
        self.bar.close()

    def openDlgInfo(self):
        self.dlginfo.show()

    def closeDlg(self):
        self.generatedService = None
        self.dlg.search_box.clear()
        self.dlg.table_widget.setRowCount(0)
        self.dlg.table_widget.setColumnCount(0)
        self.dlg.layer_name_box.clear()
        self.dlg.close()
        if self.dlginfo:
            self.dlginfo.close()

    def closeAbout(self):
        if self.dlginfo:
            self.dlginfo.close()

    def fill_table(self, contentOrderedDict):
        self.dlg.table_widget.setRowCount(0)
        count = self.dlg.table_widget.rowCount()
        self.dlg.table_widget.setColumnCount(4)

        for content in contentOrderedDict:
            index = count
            name = contentOrderedDict[content].name
            title = contentOrderedDict[content].title
            abstract = contentOrderedDict[content].abstract
            self.dlg.table_widget.insertRow(index)
            self.dlg.table_widget.setItem(index, 1,
                                          QTableWidgetItem(str(name)))
            self.dlg.table_widget.setItem(index, 2,
                                          QTableWidgetItem(str(title)))
            self.dlg.table_widget.setItem(index, 3,
                                          QTableWidgetItem(str(abstract)))

        self.dlg.table_widget.setHorizontalHeaderLabels(
            ["ID", "Capa", "Nombre", "Resumen"])
        self.dlg.label_conteo.setText("Capas disponibles: " +
                                      str(len(contentOrderedDict)))
        self.setTableWidgetBehaviour()

    def setTableWidgetBehaviour(self):
        self.dlg.table_widget.setColumnWidth(0, 0)
        self.dlg.table_widget.setColumnWidth(1, 200)
        self.dlg.table_widget.setColumnWidth(2, 200)
        self.dlg.table_widget.setColumnWidth(3, 200)
        self.dlg.table_widget.horizontalHeader().setSectionResizeMode(
            QHeaderView.Fixed)
        self.dlg.table_widget.verticalHeader().setSectionResizeMode(
            QHeaderView.Fixed)

        self.dlg.table_widget.setSelectionBehavior(
            QAbstractItemView.SelectRows)
        self.dlg.table_widget.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.dlg.table_widget.setSelectionMode(
            QAbstractItemView.ExtendedSelection)

    def search(self):
        criteria = self.dlg.search_box.text()
        criteria = criteria.lower()
        wms_filtered_contents = OrderedDict()
        contents = self.generatedService.web_map_service.contents
        for content in contents:
            name = contents[content].name
            if criteria in name:
                wms_filtered_contents[content] = contents[content]
        self.fill_table(wms_filtered_contents)

    def getSelectedItemsFromTable(self):
        rowNames = []
        selected = self.dlg.table_widget.selectedItems()
        if len(selected) > 0:
            for i in range(0, len(selected), 4):
                row = self.dlg.table_widget.row(selected[i])
                name = self.dlg.table_widget.item(row, 1).text()
                rowNames.append(name)

        selectedServices = OrderedDict()
        contents = self.generatedService.web_map_service.contents
        for rowName in rowNames:
            for content in contents:
                name_itr = contents[content].name
                if name_itr == rowName:
                    selectedServices[content] = contents[content]

        return selectedServices

    def updateDesc(self):
        try:
            selectedServices = self.getSelectedItemsFromTable()
            self.dlg.layer_name_box.clear()
            names = ''
            for selectedService in selectedServices:
                name_itr = selectedServices[selectedService].name
                names += name_itr + ','
            names = names[:-1]
            self.dlg.layer_name_box.setText(names)
            self.dlg.layer_name_box.setReadOnly(True)
        except:
            QgsMessageLog.logMessage(
                "No selecciono ninguna capa WMS para cargar")

    def loadWebService(self):
        # get selected items and add to the map
        self.bar.show()
        EPSG_CODE_4326 = 'EPSG:4326'
        selectedServices = self.getSelectedItemsFromTable()
        web_map_service = self.generatedService.web_map_service
        for selectedService in selectedServices:
            if self.generatedService.service_url is not None:
                layer_name = selectedServices[selectedService].name
                url = 'contextualWMSLegend=0'
                if hasattr(web_map_service[layer_name], 'crsOptions'):
                    if len(web_map_service[layer_name].crsOptions) > 0:
                        if EPSG_CODE_4326 in web_map_service[
                                layer_name].crsOptions:
                            url += '&crs=' + EPSG_CODE_4326
                            if self.generatedService.service_type == ServiceType.WebMapTileService.value:
                                url += '&tileMatrixSet=' + EPSG_CODE_4326
                        else:
                            url += '&crs=' + web_map_service[
                                layer_name].crsOptions[0]
                            if self.generatedService.service_type == ServiceType.WebMapTileService.value:
                                url += '&tileMatrixSet=' + web_map_service[
                                    layer_name].crsOptions[0]
                else:
                    url += '&crs=' + EPSG_CODE_4326
                    if self.generatedService.service_type == ServiceType.WebMapTileService.value:
                        url += '&tileMatrixSet=' + EPSG_CODE_4326
                url += '&dpiMode=7&featureCount=10&format=image/png&styles' + \
                       '&layers=' + layer_name + \
                       '&url=' + str(self.generatedService.service_url)
                rlayer = QgsRasterLayer(
                    url, selectedServices[selectedService].title, 'wms')
                if not rlayer.isValid():
                    QMessageBox.information(
                        None, "ERROR:", 'Imposible cargar las capas ' +
                        selectedServices[selectedService].title +
                        ' en este momento.')
                else:
                    QgsProject.instance().addMapLayer(rlayer)
                    self.iFace.messageBar().pushMessage(
                        "Mensaje:",
                        "Fueron cargadas las capas WMS con exito",
                        level=Qgis.Success,
                        duration=3)
            else:
                QMessageBox.information(
                    None, "ERROR:",
                    'No selecciono ninguna capa WMS para cargar')
        self.bar.close()
コード例 #5
0
class BhuvanWebServices:

    def __init__(self, iFace):
        # Save reference to the QGIS interface
        self.iFace = iFace
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'BhuvanWebServices_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        self.dlg = BhuvanWebServicesDialog()
        self.dlginfo = InfoDialog()
        self.generatedService = None
        self.bar = QProgressBar()
        self.bar.setRange(0, 0)
        self.bar.setGeometry(950, 500, 200, 25)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Bhuvan Web Services')

        # Check if plugin was started the first time in current QGIS session
        # Must be set in initGui() to survive plugin reloads
        self.first_start = None

    # noinspection PyMethodMayBeStatic
    def tr(self, message):
        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate('BhuvanWebServices', message)

    def add_action(
            self,
            icon_path,
            text,
            callback,
            enabled_flag=True,
            add_to_menu=True,
            add_to_toolbar=True,
            status_tip=None,
            whats_this=None,
            parent=None):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        icon = QIcon(icon_path)
        action = QAction(icon, text, parent)
        action.triggered.connect(callback)
        action.setEnabled(enabled_flag)

        if status_tip is not None:
            action.setStatusTip(status_tip)

        if whats_this is not None:
            action.setWhatsThis(whats_this)

        if add_to_toolbar:
            # Adds plugin icon to Plugins toolbar
            self.iFace.addToolBarIcon(action)

        if add_to_menu:
            self.iFace.addPluginToWebMenu(
                self.menu,
                action)

        self.actions.append(action)

        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        self.add_all_action()
        self.dlg.table_widget.itemSelectionChanged.connect(self.updateDesc)
        self.dlg.help_button.clicked.connect(self.openDlgInfo)
        self.dlg.close_button.clicked.connect(self.closeDlg)
        self.dlg.search_box.textEdited.connect(self.search)
        self.dlg.add_button.released.connect(self.loadWebService)

        # will be set False in run()
        self.first_start = True

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iFace.removePluginWebMenu(
                self.tr(u'&Bhuvan Web Services'),
                action)
            self.iFace.removeToolBarIcon(action)

    def run(self):
        if self.generatedService.web_map_service is not None:
            self.dlg.search_box.clear()
            self.fill_table(self.generatedService.web_map_service.contents)
            self.dlg.show()
            result = self.dlg.exec_()
            if result:
                pass

    def run_0(self):
        self.loadServiceList(Service.BhuvanPanchayat.value)
        self.run()

    def run_1(self):
        self.loadServiceList(Service.LULC205KDataset.value)
        self.run()

    def run_2(self):
        self.loadServiceList(Service.BhuvanV1WMS.value)
        self.run()

    def run_3(self):
        self.loadServiceList(Service.BhuvanV2WMS.value)
        self.run()

    def run_4(self):
        self.loadServiceList(Service.BhuvanV1WMTS.value)
        self.run()

    def run_5(self):
        self.loadServiceList(Service.BhuvanV2WMTS.value)
        self.run()

    def add_all_action(self):
        icon_path = ':/plugins/bhuvan_web_services/icon.png'

        self.add_action(icon_path,
                        text=self.tr(service_text_map[Service.BhuvanPanchayat.value]),
                        callback=self.run_0,
                        whats_this=str(Service.BhuvanPanchayat.value),
                        parent=self.iFace.mainWindow())

        self.add_action(icon_path,
                        text=self.tr(service_text_map[Service.LULC205KDataset.value]),
                        callback=self.run_1,
                        whats_this=str(Service.LULC205KDataset.value),
                        parent=self.iFace.mainWindow())

        self.add_action(icon_path,
                        text=self.tr(service_text_map[Service.BhuvanV1WMS.value]),
                        callback=self.run_2,
                        whats_this=str(Service.BhuvanV1WMS.value),
                        parent=self.iFace.mainWindow())

        self.add_action(icon_path,
                        text=self.tr(service_text_map[Service.BhuvanV2WMS.value]),
                        callback=self.run_3,
                        whats_this=str(Service.BhuvanV2WMS.value),
                        parent=self.iFace.mainWindow())

        self.add_action(icon_path,
                        text=self.tr(service_text_map[Service.BhuvanV1WMTS.value]),
                        callback=self.run_4,
                        whats_this=str(Service.BhuvanV1WMTS.value),
                        parent=self.iFace.mainWindow())

        self.add_action(icon_path,
                        text=self.tr(service_text_map[Service.BhuvanV2WMTS.value]),
                        callback=self.run_5,
                        whats_this=str(Service.BhuvanV2WMTS.value),
                        parent=self.iFace.mainWindow())


    def loadServiceList(self, service_id: int):
        self.iFace.messageBar().pushMessage('Info: ', 'Please wait loading layers ... ', level=Qgis.Info)
        self.bar.show()
        self.iFace.mainWindow().repaint()
        self.generatedService = WebMapServiceClass(service_id)
        url = self.generatedService.service_url
        if self.generatedService.service_type == ServiceType.WebMapService.value:
            try:
                wms = WebMapService(url)
                self.generatedService.setWebMapService(wms)
            except Exception as e:
                QMessageBox.information(None, "ERROR:", 'Unable to load this service now.' + str(e))
        elif self.generatedService.service_type == ServiceType.WebMapTileService.value:
            try:
                wmts = WebMapTileService(url)
                self.generatedService.setWebMapService(wmts)
            except Exception as e:
                QMessageBox.information(None, "ERROR:", 'Unable to load this service now.' + str(e))
        self.bar.close()

    def openDlgInfo(self):
        self.dlginfo.show()

    def closeDlg(self):
        self.generatedService = None
        self.dlg.search_box.clear()
        self.dlg.table_widget.setRowCount(0)
        self.dlg.table_widget.setColumnCount(0)
        self.dlg.layer_name_box.clear()
        self.dlg.close()
        if self.dlginfo:
            self.dlginfo.close()

    def fill_table(self, contentOrderedDict):
        self.dlg.table_widget.setRowCount(0)
        count = self.dlg.table_widget.rowCount()
        self.dlg.table_widget.setColumnCount(4)

        for content in contentOrderedDict:
            index = count
            # id_int = int(contentOrderedDict[content].index[2:])
            name = contentOrderedDict[content].name
            title = contentOrderedDict[content].title
            abstract = contentOrderedDict[content].abstract
            self.dlg.table_widget.insertRow(index)  # inserts a blank row
            # lets fill that row:
            # self.dlg.table_widget.setItem(index, 0, QTableWidgetItem(str(id_int)))  # fills in with the ID
            self.dlg.table_widget.setItem(index, 1, QTableWidgetItem(str(name)))  # fills in with the Name
            self.dlg.table_widget.setItem(index, 2, QTableWidgetItem(str(title)))  # fills in with the Title
            self.dlg.table_widget.setItem(index, 3, QTableWidgetItem(str(abstract)))  # fills in with Abstract

        self.dlg.table_widget.setHorizontalHeaderLabels(["ID", "Name", "Title", "Abstract"])
        self.setTableWidgetBehaviour()

    def setTableWidgetBehaviour(self):
        # set row and column sizes and lock them
        self.dlg.table_widget.setColumnWidth(0, 0)
        self.dlg.table_widget.setColumnWidth(1, 200)
        self.dlg.table_widget.setColumnWidth(2, 200)
        self.dlg.table_widget.setColumnWidth(3, 200)
        self.dlg.table_widget.horizontalHeader().setSectionResizeMode(QHeaderView.Fixed)
        self.dlg.table_widget.verticalHeader().setSectionResizeMode(QHeaderView.Fixed)

        self.dlg.table_widget.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.dlg.table_widget.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.dlg.table_widget.setSelectionMode(QAbstractItemView.ExtendedSelection)

    def search(self):
        criteria = self.dlg.search_box.text()
        criteria = criteria.lower()
        wms_filtered_contents = OrderedDict()
        contents = self.generatedService.web_map_service.contents
        for content in contents:
            name = contents[content].name
            if criteria in name:
                wms_filtered_contents[content] = contents[content]
        self.fill_table(wms_filtered_contents)

    def getSelectedItemsFromTable(self):
        rowNames = []
        selected = self.dlg.table_widget.selectedItems()
        if len(selected) > 0:
            for i in range(0, len(selected), 4):
                row = self.dlg.table_widget.row(selected[i])
                name = self.dlg.table_widget.item(row, 1).text()
                rowNames.append(name)

        selectedServices = OrderedDict()
        contents = self.generatedService.web_map_service.contents
        for rowName in rowNames:
            for content in contents:
                name_itr = contents[content].name
                if name_itr == rowName:
                    selectedServices[content] = contents[content]

        return selectedServices

    def updateDesc(self):
        selectedServices = self.getSelectedItemsFromTable()
        self.dlg.layer_name_box.clear()
        names = ''
        for selectedService in selectedServices:
            name_itr = selectedServices[selectedService].name
            names += name_itr + ','
        names = names[:-1]
        self.dlg.layer_name_box.setText(names)
        self.dlg.layer_name_box.setReadOnly(True)

    def loadWebService(self):
        # get selected items and add to the map
        self.bar.show()
        EPSG_CODE_4326 = 'EPSG:4326'
        selectedServices = self.getSelectedItemsFromTable()
        web_map_service = self.generatedService.web_map_service
        for selectedService in selectedServices:
            if self.generatedService.service_url is not None:
                layer_name = selectedServices[selectedService].name
                url = 'contextualWMSLegend=0'
                if hasattr(web_map_service[layer_name], 'crsOptions'):
                    if len(web_map_service[layer_name].crsOptions) > 0:
                        if EPSG_CODE_4326 in web_map_service[layer_name].crsOptions:
                            url += '&crs=' + EPSG_CODE_4326
                            if self.generatedService.service_type == ServiceType.WebMapTileService.value:
                                    url += '&tileMatrixSet=' + EPSG_CODE_4326
                        else:
                            url += '&crs=' + web_map_service[layer_name].crsOptions[0]
                            if self.generatedService.service_type == ServiceType.WebMapTileService.value:
                                    url += '&tileMatrixSet=' + web_map_service[layer_name].crsOptions[0]
                else:
                    url += '&crs=' + EPSG_CODE_4326
                    if self.generatedService.service_type == ServiceType.WebMapTileService.value:
                        url += '&tileMatrixSet=' + EPSG_CODE_4326
                url += '&dpiMode=7&featureCount=10&format=image/png&styles' + \
                       '&layers=' + layer_name + \
                       '&url=' + str(self.generatedService.service_url)
                rlayer = QgsRasterLayer(url, selectedServices[selectedService].title, 'wms')
                if not rlayer.isValid():
                    QMessageBox.information(None, "ERROR:", 'Unable to load ' +
                                            selectedServices[selectedService].title +
                                            ' this layer now.')
                else:
                    QgsProject.instance().addMapLayer(rlayer)
            else:
                QMessageBox.information(None, "ERROR:", 'Service url is None')
        self.bar.close()
コード例 #6
0
class Ui_Dialog(object):
    """
    def __init__(self, iface):
        self.iface = iface
    """
    def setupUi(self, Dialog):
        self.iface = iface
        Dialog.setObjectName("Dialog")
        Dialog.resize(
            QtCore.QSize(QtCore.QRect(0, 0, 350, 250).size()).expandedTo(
                Dialog.minimumSizeHint()))
        Dialog.setWindowTitle("GroupPointsWithinDistance")

        # QLabel lancer recherche
        self.label10 = QLabel(Dialog)
        self.label10.setGeometry(QtCore.QRect(15, 15, 320, 18))
        self.label10.setObjectName("label10")
        self.label10.setText("Select a layer with points to regroup:  ")

        ListeCouchesPoint = [""]
        NbCouches = self.iface.mapCanvas().layerCount()
        if NbCouches == 0:
            QMessageBox.information(None, "information:", "No layers ! ")
        else:
            for i in range(0, NbCouches):
                couche = self.iface.mapCanvas().layer(i)
                # 0 pour point
                if couche.geometryType() == 0 or couche.geometryType() == 3:
                    if couche.isValid():
                        ListeCouchesPoint.append(couche.name())
                    else:
                        QMessageBox.information(None, "information:",
                                                "No layers with points ! ")
                        return None
        self.ComboBoxPoints = QComboBox(Dialog)
        self.ComboBoxPoints.setMinimumSize(QtCore.QSize(320, 25))
        self.ComboBoxPoints.setMaximumSize(QtCore.QSize(320, 25))
        self.ComboBoxPoints.setGeometry(QtCore.QRect(10, 35, 320, 25))
        self.ComboBoxPoints.setObjectName("ComboBoxPoints")
        for i in range(len(ListeCouchesPoint)):
            self.ComboBoxPoints.addItem(ListeCouchesPoint[i])

        # QLabel entrer Enter distance of recherch
        self.labelResearchDistance = QLabel(Dialog)
        self.labelResearchDistance.setGeometry(QtCore.QRect(15, 80, 240, 23))
        self.labelResearchDistance.setObjectName(" ResearchDistance")
        self.labelResearchDistance.setText("Enter distance of research :")

        #Exemple de QDoubleSpinBox
        self.dsbResearchDistance = QDoubleSpinBox(Dialog)
        self.dsbResearchDistance.setMinimumSize(QtCore.QSize(70, 23))
        self.dsbResearchDistance.setMaximumSize(QtCore.QSize(70, 23))
        self.dsbResearchDistance.setGeometry(QtCore.QRect(180, 80, 70, 23))
        self.dsbResearchDistance.setObjectName("dsb")
        #self.dsbResearchDistance.setValue(10.0)
        self.dsbResearchDistance.setDecimals(1)
        self.dsbResearchDistance.setSingleStep(10.0)
        self.dsbResearchDistance.setRange(0, 1000000)
        self.dsbResearchDistance.setProperty("value", 100.0)

        #self.dsbResearchDistance.valueChanged.connect(self.onValueChanged)

        #Exemple de QPushButton
        self.DoButton = QPushButton(Dialog)
        self.DoButton.setMinimumSize(QtCore.QSize(280, 20))
        self.DoButton.setMaximumSize(QtCore.QSize(280, 20))
        self.DoButton.setGeometry(QtCore.QRect(15, 120, 280, 20))
        self.DoButton.setObjectName("DoButton")
        self.DoButton.setText(" Let's make aggregates - being patient !")

        #Exemple de QLCDNumber
        self.progressBar = QProgressBar(Dialog)
        self.progressBar.setProperty("value", 0)
        self.progressBar.setMinimumSize(QtCore.QSize(260, 15))
        self.progressBar.setMaximumSize(QtCore.QSize(260, 15))
        self.progressBar.setGeometry(QtCore.QRect(30, 155, 260, 15))
        self.progressBar.setAlignment(QtCore.Qt.AlignCenter)
        self.progressBar.setTextVisible(True)
        self.progressBar.setObjectName("progressBar")
        self.progressBar.setStyleSheet(
            """QProgressBar {border: 2px solid grey; border-radius: 5px; text-align: center;}"""
            """QProgressBar::chunk {background-color: #6C96C6; width: 20px;}"""
        )
        #Pose a minima une valeur de la barre de progression / slide contrôle
        self.progressBar.setValue(0)

        #Exemple de QPushButton
        self.aboutButton = QPushButton(Dialog)
        self.aboutButton.setMinimumSize(QtCore.QSize(70, 20))
        self.aboutButton.setMaximumSize(QtCore.QSize(70, 20))
        self.aboutButton.setGeometry(QtCore.QRect(30, 195, 70, 23))
        self.aboutButton.setObjectName("aboutButton")
        self.aboutButton.setText(" Read me ")

        self.PushButton = QPushButton(Dialog)
        self.PushButton.setMinimumSize(QtCore.QSize(100, 20))
        self.PushButton.setMaximumSize(QtCore.QSize(100, 20))
        self.PushButton.setGeometry(QtCore.QRect(185, 195, 100, 20))
        self.PushButton.setObjectName("PushButton")
        self.PushButton.setText("Close")

        self.PushButton.clicked.connect(Dialog.reject)
        self.ComboBoxPoints.activated[str].connect(self.onComboP)
        self.aboutButton.clicked.connect(self.doAbout)
        self.DoButton.clicked.connect(self.Run)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def onComboP(self):
        global SelectionP
        SelectionP = self.ComboBoxPoints.currentText()

    def doAbout(self):
        d = doAboutGroupPointsWithinDistance.Dialog()
        d.exec_()

    def Run(self):
        D = 0.0
        D = self.dsbResearchDistance.value()
        #QMessageBox.information(None,"information:"," D : "+str(D))
        DicoP1 = {}
        DicoA = {}
        counterProgess = 0
        compteur_pt = 0
        layerP = fonctionsGPWD.getVectorLayerByName(SelectionP)
        # on parcourt la couche de points et on stocke dans les dictionnaire DicoP1  les points
        # the points of the point laye are put into a dictionnary
        for featP in layerP.getFeatures():
            Point_id = featP.id()
            geomP1 = featP.geometry()
            Point1 = geomP1.asPoint()
            DicoP1[Point_id] = [Point1]
            compteur_pt += 1

        if D == 0:
            QMessageBox.information(None, "information:",
                                    "Zero is not a value for D !")

        #zdim est le compteur de la progress bar
        zDim = compteur_pt
        counterProgess = 0
        cpt_agg = 1
        nb = 0
        liste_id = []
        liste_pt = []
        liste_aggreg_pt = []
        DicoSegments = {}
        firstDicoSegments = True
        T = True
        while len(DicoP1) != 0:
            first = True
            zPercent = int(100 * counterProgess / zDim)
            self.progressBar.setValue(zPercent)
            nb = 0
            for keyD1 in list(DicoP1.keys()):
                P1 = DicoP1[keyD1][0]
            if first:
                # we pick a first point and delete it from the dictionnary we point are stored
                T = True
                first = False
                nb += 1
                liste_id = [keyD1]
                liste_pt = [P1]
                counterProgess += 1
                del DicoP1[keyD1]
            while T:
                # We are generating an aggregates and making it grows
                # by adding points at distance from the point it contains
                # and repeating the research all over again as soon a poitn is added
                # untill none are added
                for pt in liste_pt:
                    compteur_corresP = 0
                    for keyD1 in list(DicoP1.keys()):
                        P1 = DicoP1[keyD1][0]
                        if fonctionsGPWD.mag(fonctionsGPWD.vect(
                                pt, P1)) < D:  # one point at distance found
                            compteur_corresId = 0
                            for idp in liste_id:
                                if keyD1 == idp:  # is this point already added in the aggregate
                                    compteur_corresId += 1
                            if compteur_corresId == 0:  # if not let s add it
                                nb += 1
                                liste_id.append(keyD1)
                                liste_pt.append(P1)
                                compteur_corresP += 1
                                counterProgess += 1
                                # boucle des segments
                                # interpoint line loop
                                idseg = ''  # a segment as an id made of the points id order ordered id: smallerid-biggerid
                                idseg = str(keyD1) + '-' + str(idp)
                                idseg_reverse = str(idp) + '-' + str(keyD1)
                                if firstDicoSegments:
                                    firstDicoSegments = False
                                    if int(keyD1) > int(idp):
                                        idseg = idseg_reverse
                                        DicoSegments[idseg] = [[pt, P1], idp,
                                                               keyD1, cpt_agg]
                                    else:
                                        DicoSegments[idseg] = [[P1, pt], keyD1,
                                                               idp, cpt_agg]
                                else:
                                    for idseg_cheack in list(
                                            DicoSegments.keys()):
                                        if idseg == idseg_cheack or idseg_reverse == idseg_cheack:
                                            pass
                                        else:
                                            if int(keyD1) > int(idp):
                                                idseg = idseg_reverse
                                                DicoSegments[idseg] = [[
                                                    pt, P1
                                                ], idp, keyD1, cpt_agg]
                                            else:
                                                DicoSegments[idseg] = [[
                                                    P1, pt
                                                ], keyD1, idp, cpt_agg]

                if compteur_corresP == 0:  # if no more points are find then we are over with the previous aggregate
                    T = False

                    DicoA[cpt_agg] = [nb, liste_id, liste_pt, DicoSegments]
                    cpt_agg += 1
                    for id in liste_id:
                        for keyD1 in list(DicoP1.keys()):
                            if id == keyD1:
                                del DicoP1[keyD1]

        # on fabrique un polygone buffer de D/100
        # du convexHull de tous les points de l'agregat
        # pour les operateur Pyqgis
        # voir http://www.qgis.org/api/classQgsGeometry.html#a1699b205d01c365a50ead2d0bf2bbcfb
        DicoP4 = {}

        for key2 in list(DicoA.keys()):
            list_pt = []
            list_pt = DicoA[key2][2]
            nb_pt = 0
            nb_pt = DicoA[key2][0]
            Liste_id = []
            Liste_id = DicoA[key2][1]
            buff = 0.0
            first = True
            for pt in list_pt:
                if first:
                    first = False
                    #https://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/geometry.html
                    g0 = QgsGeometry().fromPointXY(pt)
                else:
                    g0 = QgsGeometry().fromPointXY(pt).combine(
                        g0)  # combine pour union car union reserve C++
            buff = D / 100
            P = g0.convexHull()
            B = P.buffer(buff, 5)
            DicoP4[key2] = [B, Liste_id, nb_pt]

        zPercent = int(100 * counterProgess / zDim)
        self.progressBar.setValue(zPercent)
        self.iface.mapCanvas().refresh()

        STATIONS = QgsVectorLayer(
            "MultiPolygon", "Polygons_under_AGGREGATES_D" + str(D) + "_OF_" +
            str(layerP.name()), "memory")
        QgsProject.instance().addMapLayer(STATIONS)
        prSTATIONS = STATIONS.dataProvider()
        listFieldsS = []
        listFieldsS.append(QgsField("NumAggreg", QVariant.String))
        listFieldsS.append(QgsField("List_Pts", QVariant.String))
        listFieldsS.append(QgsField("Nb_Pts", QVariant.Int))
        prSTATIONS.addAttributes(listFieldsS)

        STATIONS.startEditing()
        newfeatSTATIONS = QgsFeature()
        for keyP4 in DicoP4.keys():
            GeomPoly = DicoP4[keyP4][0]
            newfeatSTATIONS = QgsFeature()
            newfeatSTATIONS.setGeometry(GeomPoly)
            toto = ''
            first = True
            for t in DicoP4[keyP4][1]:
                if first:
                    first = False
                    toto = str(t)
                else:
                    toto = toto + ' - ' + str(t)
            NbObs = DicoP4[keyP4][2]
            ValuesSTATIONS = [keyP4]
            ValuesSTATIONS.append(toto)
            ValuesSTATIONS.append(NbObs)
            newfeatSTATIONS.setAttributes(ValuesSTATIONS)
            prSTATIONS.addFeatures([newfeatSTATIONS])
        STATIONS.commitChanges()
        iface.mapCanvas().refresh()

        SEGMENTS = QgsVectorLayer(
            "MultiLineString",
            "Lines_from_" + str(layerP.name()) + "_Aggregates_with_D" + str(D),
            "memory")
        QgsProject.instance().addMapLayer(SEGMENTS)
        prSEGMENTS = SEGMENTS.dataProvider()
        listFields = []
        listFields.append(QgsField("NumAgregat", QVariant.String))
        listFields.append(QgsField("Nb_Pts", QVariant.Int))
        prSEGMENTS.addAttributes(listFields)
        SEGMENTS.startEditing()
        newfeatSEGMENTS = QgsFeature()
        attributs = []
        for keyA in DicoA.keys():
            DicoSeg = DicoA[keyA][3]
            NbObs = DicoA[keyA][0]
            firstSEG = True
            MultiLine = []
            GeomLine = QgsGeometry
            for keyPair in DicoSeg.keys():
                if DicoSeg[keyPair][3] == keyA:
                    if firstSEG:
                        firstSEG = False
                        MultiLine = []
                        MultiLine = [DicoSeg[keyPair][0]]
                    else:
                        MultiLine.append(DicoSeg[keyPair][0])

            GeomLine = QgsGeometry.fromMultiPolylineXY(MultiLine)
            NumAg = keyA
            newfeatSEGMENTS = QgsFeature()
            newfeatSEGMENTS.setGeometry(GeomLine)
            ValuesSEGMENTS = [NumAg]
            ValuesSEGMENTS.append(NbObs)
            newfeatSEGMENTS.setAttributes(ValuesSEGMENTS)
            prSEGMENTS.addFeatures([newfeatSEGMENTS])
        SEGMENTS.commitChanges()
        iface.mapCanvas().refresh()

        # modification de la table de point initiale pour ajout d un numero d agregat
        # making of the modified point layer with aggregates code
        AGGREGATS = QgsVectorLayer(
            "Point",
            str(layerP.name()) + "_aggregated_with_D" + str(D), "memory")
        QgsProject.instance().addMapLayer(AGGREGATS)
        prAGGREGATS = AGGREGATS.dataProvider()
        fieldsP = layerP.fields()
        listFields = []
        for f in fieldsP:
            znameField = f.name()
            Type = str(f.typeName())
            if Type == 'Integer':
                listFields.append(QgsField(znameField, QVariant.Int))
            if Type == 'Real':
                listFields.append(QgsField(znameField, QVariant.Double))
            if Type == 'String':
                listFields.append(QgsField(znameField, QVariant.String))
            else:
                listFields.append(QgsField(znameField, QVariant.String))
        listFields.append(QgsField("Point_id", QVariant.String))
        listFields.append(QgsField("NumAggreg", QVariant.String))
        listFields.append(QgsField("Nb_Pts", QVariant.Int))
        listFields.append(QgsField("List_Pts", QVariant.String))
        prAGGREGATS.addAttributes(listFields)
        AGGREGATS.startEditing()
        newfeatAGGREGATS = QgsFeature()
        attributs = []
        for featP in layerP.getFeatures():
            attributs = featP.attributes()
            Point_id = featP.id()
            geomP1 = featP.geometry()
            NbObs = 1
            NumAgregat = 0
            for keyP4 in DicoP4.keys():
                #GeomPoly=DicoP4[keyP4][0]
                #if geomP1.intersects(GeomPoly):
                for ptid in DicoP4[keyP4][1]:
                    if Point_id == ptid:
                        NbObs = DicoP4[keyP4][2]
                        toto = ''
                        first = True
                        for t in DicoP4[keyP4][1]:
                            if first:
                                first = False
                                toto = str(t)
                            else:
                                toto = toto + ' - ' + str(t)
                        list_id = toto
                        NumAgregat = keyP4
            newfeatAGGREGATS = QgsFeature()
            newfeatAGGREGATS.setGeometry(geomP1)
            ValuesAGGREGATS = attributs
            ValuesAGGREGATS.append(Point_id)
            ValuesAGGREGATS.append(NumAgregat)
            ValuesAGGREGATS.append(NbObs)
            ValuesAGGREGATS.append(list_id)
            newfeatAGGREGATS.setAttributes(ValuesAGGREGATS)
            prAGGREGATS.addFeatures([newfeatAGGREGATS])
        AGGREGATS.commitChanges()
        iface.mapCanvas().refresh()