Example #1
0
    def gera_vertice(self):
        prog = 0.0
        sobra = 0.0
        resto = 0.0
        estaca = 0
        cosa = 0.0
        cosb = 0.0
        crs = int(self.getCRS())
        sem_internet = False
        for elemento in self.layer.getFeatures():
            for i, (seg_start,
                    seg_end) in enumerate(pairs(elemento, self.estaca)):
                ponto_inicial = QgsPoint(seg_start)
                ponto_final = QgsPoint(seg_end)
                tamanho_da_linha = length(ponto_final, ponto_inicial)
                ponto = diff(ponto_final, ponto_inicial)
                cosa, cosb = dircos(ponto)
                az = azimuth(
                    ponto_inicial,
                    QgsPoint(ponto_inicial.x() + ((self.distancia) * cosa),
                             ponto_inicial.y() + ((self.distancia) * cosb)))
                estacas_inteiras = int(
                    math.floor((tamanho_da_linha - sobra) / self.distancia))
                estacas_inteiras_sobra = estacas_inteiras + 1 if sobra > 0 else estacas_inteiras
                if not sem_internet:
                    cota = getElevation(
                        crs,
                        QgsPoint(float(ponto_inicial.x()),
                                 float(ponto_inicial.y())))
                    if cota == 0:
                        sem_internet = True
                else:
                    cota = 0.0

                yield [
                    '%d+%f' % (estaca, resto) if resto != 0 else '%d' %
                    (estaca),
                    'v%d' % i, prog,
                    ponto_inicial.y(),
                    ponto_inicial.x(), cota, az
                ], ponto_inicial, estacas_inteiras, prog, az, sobra, tamanho_da_linha, cosa, cosb

                prog += tamanho_da_linha
                resto = (tamanho_da_linha - sobra) - (self.distancia *
                                                      estacas_inteiras)
                sobra = self.distancia - resto
                estaca += estacas_inteiras_sobra
            cota = getElevation(
                crs, QgsPoint(float(ponto_final.x()), float(ponto_final.y())))
            yield [
                '%d+%f' % (estaca, resto),
                'v%d' % i, prog,
                ponto_final.y(),
                ponto_final.x(), cota, az
            ], ponto_final, 0, tamanho_da_linha, az, sobra, tamanho_da_linha, cosa, cosb
    def criticalLocate(self):
        point = None
        try:
            point = QgsPoint(float(self.ui.txtCriticalX.text()), float(self.ui.txtCriticalY.text()))
        except:
            return
        if define._units == QGis.Meters:
            extent = QgsRectangle(point.x() - 350, point.y() - 350, point.x() + 350, point.y() + 350)
        else:
            extent = QgsRectangle(point.x() - 0.005, point.y() - 0.005, point.x() + 0.005, point.y() + 0.005)

        if extent is None:
            return

        QgisHelper.zoomExtent(point, extent, 2)
Example #3
0
    def gera_estaca_intermediaria(self,
                                  estaca,
                                  anterior,
                                  prog,
                                  az,
                                  cosa,
                                  cosb,
                                  sobra=0.0):
        dist = sobra if sobra > 0 else self.distancia

        p = QgsPoint(anterior.x() + (dist * cosa),
                     anterior.y() + (dist * cosb))
        prog += dist
        return [estaca, '', prog, p.y(), p.x(), 0.0, az], prog, p
Example #4
0
    def create_estacas_old(self):
        estacas = []
        k = 0
        prog = 0.0
        dist = 0.0
        p = self.get_features()[self.estaca]
        az = 0.0
        lab = 0
        for elem in self.layer.getFeatures():
            for i, (seg_start, seg_end) in enumerate(pairs(elem, self.estaca)):
                estaca = []
                line_start = QgsPoint(seg_start)
                line_end = QgsPoint(seg_end)
                if k != 0:
                    # lab = 1
                    pass
                else:

                    lab = 0

                # mid point = vector coordinates [x2-x1,y2-y1]
                pointm = diff(line_end, line_start)
                # direction cosines of the segment
                cosa, cosb = dircos(pointm)
                # length of the segment
                lg = length(line_end, line_start)
                az = azimuth(
                    line_start,
                    QgsPoint(line_start.x() + ((prog + self.distancia) * cosa),
                             line_start.y() +
                             ((prog + self.distancia) * cosb)))

                geo = line_start
                prop = self.distancia - (
                    (prog + self.distancia) - dist) if prog > 0 else prog
                txtId = "%d+%f" % (
                    lab, prop) if prog > 0 or prop > 0 else "%d" % lab
                estaca.extend(
                    [txtId, 'v%d' % i, dist,
                     geo.y(),
                     geo.x(), 0.0, az])
                estacas.append(estaca)
                '''
                    ------------------------------------------------
                    Definição das estacas intermediarias.
                    ------------------------------------------------
                '''
                prog = 0.0 if (prog == 0) else prog
                dist = dist + lg
                p = line_start
                nprog = 0.0
                while nprog + self.distancia < lg:
                    estaca = []
                    lab += 1
                    k += 1
                    pa = p
                    p = QgsPoint(p.x() + ((self.distancia - prop) * cosa),
                                 p.y() + ((self.distancia - prop) * cosb))

                    az = azimuth(seg_start, p)
                    prog += self.distancia
                    nprog += self.distancia
                    prop = 0
                    estaca.extend([str(lab), '', prog, p.y(), p.x(), 0.0, az])
                    estacas.append(estaca)

        estaca = []
        ultimo = self.get_features()[-1]
        lg = prog + length(p, ultimo)
        prop = self.distancia - (prog - lg) if prog > 0 else prog
        txtId = "%d+%f" % (lab, prop) if prog > 0 or prop > 0 else "%d" % lab

        # az = self.azimuth(p,QgsPoint(ultimo.x(), ultimo.y()))

        estaca.extend(
            [txtId, 'vf', lg,
             ultimo.y(),
             ultimo.x(),
             ultimo.x(), az])
        estacas.append(estaca)
        return estacas
    def matrix_dem_build(self, dem_dataset, height, width, scale, spacing_mm,
                         roi_x_max, roi_x_min, roi_y_min, h_base, z_scale,
                         projected):

        # Calculate DEM parameters
        dem_col = dem_dataset.RasterXSize
        dem_row = dem_dataset.RasterYSize
        geotransform = dem_dataset.GetGeoTransform()
        dem_x_min = geotransform[0]
        dem_y_max = geotransform[3]
        dem_y_min = dem_y_max + dem_row * geotransform[5]
        dem_x_max = dem_x_min + dem_col * geotransform[1]

        if not projected:
            spacing_deg = spacing_mm * (roi_x_max - roi_x_min) / width

        row_stl = int(math.ceil(height / spacing_mm) + 1)
        col_stl = int(math.ceil(width / spacing_mm) + 1)
        matrix_dem = [range(col_stl) for i in range(row_stl)]

        var_y = height
        for i in range(row_stl):
            self.updateProgress.emit()
            QApplication.processEvents()
            var_x = 0
            for j in range(col_stl):
                # Model coordinate x(mm), y(mm)
                x_model = round(var_x, 2)
                y_model = round(var_y, 2)

                # Model maps geo_coordinates
                if projected:
                    x = x_model * scale / 1000 + roi_x_min
                    y = y_model * scale / 1000 + roi_y_min
                else:
                    x = x_model * spacing_deg / spacing_mm + roi_x_min
                    y = y_model * spacing_deg / spacing_mm + roi_y_min

                # Model layer geo_coordinates to query z value
                point = QgsPoint(x, y)
                source = self.parameters["crs_map"]
                target = self.parameters["crs_layer"]
                if source != target:
                    transform = QgsCoordinateTransform(source, target)
                    point = transform.transform(point)
                    x = point.x()
                    y = point.y()

                # From x(m) get Column in DEM file
                col_dem = (x - dem_x_min) * dem_col / (dem_x_max - dem_x_min)
                col_dem = int(math.floor(col_dem))
                if col_dem == dem_col:
                    col_dem -= 1
                # From y(m) get Row in DEM file
                row_dem = (dem_y_max - y) * dem_row / (dem_y_max - dem_y_min)
                row_dem = int(math.floor(row_dem))
                if row_dem == dem_row:
                    row_dem -= 1

                # Model coordinate z(mm)
                if col_dem < 0 or row_dem < 0:
                    z_model = 2
                elif self.get_dem_z(dem_dataset, col_dem, row_dem, 1,
                                    1)[0] <= h_base:
                    z_model = 2
                elif math.isnan(
                        self.get_dem_z(dem_dataset, col_dem, row_dem, 1,
                                       1)[0]):
                    z_model = 2
                else:
                    z_model = round(
                        (self.get_dem_z(dem_dataset, col_dem, row_dem, 1, 1)[0]
                         - h_base) / scale * 1000 * z_scale, 2) + 2

                matrix_dem[i][j] = self.pto(x=x_model, y=y_model, z=z_model)

                var_x += spacing_mm
                if var_x > width:
                    var_x = width
            var_y = spacing_mm * (row_stl - (i + 2))
            if self.quit:
                return 0
        return matrix_dem
Example #6
0
    def matrix_dem_build(self, dem_dataset, height, width, scale, spacing_mm,
                         roi_x_max, roi_x_min, roi_y_min, h_base, z_scale, projected):

        # Calculate DEM parameters
        dem_col = dem_dataset.RasterXSize
        dem_row = dem_dataset.RasterYSize
        geotransform = dem_dataset.GetGeoTransform()
        dem_x_min = geotransform[0]
        dem_y_max = geotransform[3]
        dem_y_min = dem_y_max + dem_row * geotransform[5]
        dem_x_max = dem_x_min + dem_col * geotransform[1]

        if not projected:
            spacing_deg = spacing_mm * (roi_x_max - roi_x_min) / width

        row_stl = int(math.ceil(height / spacing_mm) + 1)
        col_stl = int(math.ceil(width / spacing_mm) + 1)
        matrix_dem = [range(col_stl) for i in range(row_stl)]

        var_y = height
        for i in range(row_stl):
            self.updateProgress.emit()
            QApplication.processEvents()
            var_x = 0
            for j in range(col_stl):
                # Model coordinate x(mm), y(mm)
                x_model = round(var_x, 2)
                y_model = round(var_y, 2)

                # Model maps geo_coordinates
                if projected:
                    x = x_model * scale / 1000 + roi_x_min
                    y = y_model * scale / 1000 + roi_y_min
                else:
                    x = x_model * spacing_deg / spacing_mm + roi_x_min
                    y = y_model * spacing_deg / spacing_mm + roi_y_min

                # Model layer geo_coordinates to query z value
                point = QgsPoint(x, y)
                source = self.parameters["crs_map"]
                target = self.parameters["crs_layer"]
                if source != target:
                    transform = QgsCoordinateTransform(source, target)
                    point = transform.transform(point)
                    x = point.x()
                    y = point.y()

                # From x(m) get Column in DEM file
                col_dem = (x - dem_x_min) * dem_col / (dem_x_max - dem_x_min)
                col_dem = int(math.floor(col_dem))
                if col_dem == dem_col:
                    col_dem -= 1
                # From y(m) get Row in DEM file
                row_dem = (dem_y_max - y) * dem_row / (dem_y_max - dem_y_min)
                row_dem = int(math.floor(row_dem))
                if row_dem == dem_row:
                    row_dem -= 1

                # Model coordinate z(mm)
                if col_dem < 0 or row_dem < 0:
                    z_model = 2
                elif self.get_dem_z(dem_dataset, col_dem, row_dem, 1, 1)[0] <= h_base:
                    z_model = 2
                elif math.isnan(self.get_dem_z(dem_dataset, col_dem, row_dem, 1, 1)[0]):
                    z_model = 2
                else:
                    z_model = round((self.get_dem_z(dem_dataset, col_dem, row_dem, 1, 1)[0] - h_base) /
                                    scale * 1000 * z_scale, 2) + 2

                matrix_dem[i][j] = self.pto(x=x_model, y=y_model, z=z_model)

                var_x += spacing_mm
                if var_x > width:
                    var_x = width
            var_y = spacing_mm * (row_stl - (i + 2))
            if self.quit:
                return 0
        return matrix_dem
Example #7
0
class EstacasUI(QtGui.QDialog, FORMESTACA1_CLASS):
    def __init__(self, iface):
        super(EstacasUI, self).__init__(None)
        self.iface = iface
        self.setupUi(self)
        self.setupUi2(self)
        self.points = []
        self.crs = 1
        self.edit = False
        self.dialog = QtGui.QDialog(None)
        self.actual_point = None

    def error(self, msg):
        msgBox = QtGui.QMessageBox(QtGui.QMessageBox.Warning, "AVISO",
                                   u"%s" % msg, QtGui.QMessageBox.NoButton,
                                   None)
        msgBox.addButton("OK", QtGui.QMessageBox.AcceptRole)
        # msgBox.addButton("&Continue", QtGui.QMessageBox.RejectRole)
        msgBox.exec_()

    def openCSV(self):
        filename = QtGui.QFileDialog.getOpenFileName()
        if filename in ["", None]: return None
        fileDB, ok = QtGui.QInputDialog.getText(
            None, "Nome do arquivo",
            u"Nome do arquivo a ser salvo no projeto:")
        if not ok:
            return None
        return filename, fileDB

    def new(self, recalcular=False, layerName=None):
        mapCanvas = self.iface.mapCanvas()
        itens = []
        for i in range(mapCanvas.layerCount() - 1, -1, -1):
            try:
                layer = mapCanvas.layer(i)
                layerName = layer.name()
                itens.append(layerName)
            except:
                pass
        if len(itens) == 0: return None
        if not recalcular:
            filename, ok = QtGui.QInputDialog.getText(None, "Nome do arquivo",
                                                      u"Nome do arquivo:")
            if not ok:
                return None
        else:
            filename = ''

        if layerName is None:
            layerList = QgsMapLayerRegistry.instance().mapLayersByName(
                layerName)
            layer = None
            if layerList:
                layer = layerList[-1]
        else:
            itens = []
            for i in range(mapCanvas.layerCount() - 1, -1, -1):
                try:
                    layer = mapCanvas.layer(i)
                    layerName = layer.name()
                    itens.append(layerName)
                except:
                    pass
            item, ok = QtGui.QInputDialog.getItem(
                None, "Camada com tracado",
                u"Selecione a camada com o traçado:", itens, 0, False)
            if not (ok) or not (item):
                return None
            else:
                layerList = QgsMapLayerRegistry.instance().mapLayersByName(
                    item)
                layer = None
                if layerList:
                    layer = layerList[0]

        dist, ok = QtGui.QInputDialog.getDouble(None, "Distancia",
                                                u"Distancia entre estacas:",
                                                20.0, -10000, 10000, 2)
        if not ok or dist <= 0:
            return None
        estaca, ok = QtGui.QInputDialog.getInteger(None, "Estaca Inicial",
                                                   u"Estaca Inicial:", 0,
                                                   -10000, 10000, 2)

        if not ok:
            return None
        return filename, layer, dist, estaca

    def fill_table_index(self, files):
        self.tableEstacas.setRowCount(0)
        self.tableEstacas.clearContents()
        for i, f in enumerate(files):
            self.tableEstacas.insertRow(self.tableEstacas.rowCount())
            for j, f2 in enumerate(f):
                self.tableEstacas.setItem(i, j,
                                          QtGui.QTableWidgetItem(u"%s" % f2))

    def create_line(self, p1, p2, name):
        layer = QgsVectorLayer('LineString?crs=%s' % int(self.crs), name,
                               "memory")
        mycrs = QgsCoordinateReferenceSystem(int(self.crs), 0)
        self.reprojectgeographic = QgsCoordinateTransform(
            self.iface.mapCanvas().mapRenderer().destinationCrs(), mycrs)
        pr = layer.dataProvider()
        line = QgsFeature()
        line.setGeometry(
            QgsGeometry.fromPolyline([
                self.reprojectgeographic.transform(p1),
                self.reprojectgeographic.transform(p2)
            ]))
        pr.addFeatures([line])
        #layer.setCrs(QgsCoordinateReferenceSystem(int(self.crs), 0))
        layer.updateExtents()

        QgsMapLayerRegistry.instance().addMapLayer(layer)

        return p1, p2

    def create_point(self, p1, name):
        layer = QgsVectorLayer('Point?crs=%s' % int(self.crs), name, "memory")
        mycrs = QgsCoordinateReferenceSystem(int(self.crs), 0)
        self.reprojectgeographic = QgsCoordinateTransform(
            self.iface.mapCanvas().mapRenderer().destinationCrs(), mycrs)
        pr = layer.dataProvider()
        point = QgsFeature()
        point.setGeometry(
            QgsGeometry.fromPoint(self.reprojectgeographic.transform(p1)))
        pr.addFeatures([point])
        #layer.setCrs(QgsCoordinateReferenceSystem(int(self.crs), 0))
        layer.updateExtents()

        QgsMapLayerRegistry.instance().addMapLayer(layer)

        return p1

    def get_click_coordenate(self, point, mouse):
        self.actual_point = QgsPoint(point)
        if self.tracado_dlg.txtNorthStart.text().strip() == '':
            self.tracado_dlg.txtNorthStart.setText("%f" %
                                                   self.actual_point.y())
            self.tracado_dlg.txtEsteStart.setText("%f" % self.actual_point.x())
        elif self.tracado_dlg.txtNorthEnd.text().strip() == '':
            self.tracado_dlg.txtNorthEnd.setText("%f" % self.actual_point.y())
            self.tracado_dlg.txtEsteEnd.setText("%f" % self.actual_point.x())

    def gera_tracado_pontos(self,
                            inicial=False,
                            final=False,
                            callback_inst=None,
                            callback_method=None,
                            crs=None):
        if (not (inicial) and not (final)):
            self.callback = eval('callback_inst.%s' % callback_method)
            self.crs = crs
            self.tracado_dlg_inicial = GeraTracadoUI(self.iface)
            self.tracado_dlg_inicial.lblName.setText("Ponto Inicial")
            self.tracado_dlg_inicial.btnCapture.clicked.connect(
                self.capture_point_inicial)
            self.tracado_dlg_final = GeraTracadoUI(self.iface)
            self.tracado_dlg_final.lblName.setText("Ponto Final")
            self.tracado_dlg_final.btnCapture.clicked.connect(
                self.capture_point_final)
        if (not (inicial) and not (final)) or not (final):
            ok = self.tracado_dlg_inicial.exec_()
            if not (ok):
                return None
            else:
                pn = float(
                    self.tracado_dlg_inicial.txtNorth.text().strip().replace(
                        ",", "."))
                pe = float(
                    self.tracado_dlg_inicial.txtEste.text().strip().replace(
                        ",", "."))
                self.gera_tracado_ponto_inicial(QgsPoint(pe, pn))

        if (not (inicial) and not (final)) or not (inicial):
            ok = self.tracado_dlg_final.exec_()
            if not (ok):
                return None
            else:
                pn = float(
                    self.tracado_dlg_final.txtNorth.text().strip().replace(
                        ",", "."))
                pe = float(
                    self.tracado_dlg_final.txtEste.text().strip().replace(
                        ",", "."))
                self.gera_tracado_ponto_final(QgsPoint(pe, pn))

        if inicial and final:
            p1n = float(
                self.tracado_dlg_inicial.txtNorth.text().strip().replace(
                    ",", "."))
            p1e = float(
                self.tracado_dlg_inicial.txtEste.text().strip().replace(
                    ",", "."))
            p2n = float(self.tracado_dlg_final.txtNorth.text().strip().replace(
                ",", "."))
            p2e = float(self.tracado_dlg_final.txtEste.text().strip().replace(
                ",", "."))
            self.iface.mapCanvas().setMapTool(None)
            self.callback(pontos=self.create_line(QgsPoint(p1e, p1n),
                                                  QgsPoint(p2e, p2n),
                                                  "Diretriz"),
                          parte=1)

    def gera_tracado_ponto_inicial(self, point):
        self.tracado_dlg_inicial.txtNorth.setText("%f" % point.y())
        self.tracado_dlg_inicial.txtEste.setText("%f" % point.x())
        ok = self.tracado_dlg_inicial.exec_()
        if not (ok):
            return None
        else:
            pn = float(
                self.tracado_dlg_inicial.txtNorth.text().strip().replace(
                    ",", "."))
            pe = float(self.tracado_dlg_inicial.txtEste.text().strip().replace(
                ",", "."))
            self.gera_tracado_ponto_final(QgsPoint(pe, pn))

        #self.gera_tracado_pontos(inicial=True)
        self.gera_tracado_pontos(final=True)

    def gera_tracado_ponto_final(self, point):
        self.tracado_dlg_final.txtNorth.setText("%f" % point.y())
        self.tracado_dlg_final.txtEste.setText("%f" % point.x())
        ok = self.tracado_dlg_final.exec_()
        if not (ok):
            return None
        else:
            pn = float(self.tracado_dlg_final.txtNorth.text().strip().replace(
                ",", "."))
            pe = float(self.tracado_dlg_final.txtEste.text().strip().replace(
                ",", "."))
            #self.gera_tracado_ponto_final(QgsPoint(pe, pn))

        #self.gera_tracado_pontos(final=True)
        self.gera_tracado_pontos(inicial=True, final=True)

    def capture_point_inicial(self):
        tool = PointTool(self.iface.mapCanvas(), self,
                         'gera_tracado_ponto_inicial')
        self.iface.mapCanvas().setMapTool(tool)

    def capture_point_final(self):
        tool = PointTool(self.iface.mapCanvas(), self,
                         'gera_tracado_ponto_final')
        self.iface.mapCanvas().setMapTool(tool)

    def exit_dialog(self, points, crs):
        self.dialog.close()

        layer = QgsVectorLayer('LineString', self.name_tracado, "memory")
        pr = layer.dataProvider()
        print points
        anterior = QgsPoint(points[0])
        fets = []
        for p in points[1:]:
            fet = QgsFeature(layer.pendingFields())
            fet.setGeometry(QgsGeometry.fromPolyline([anterior, QgsPoint(p)]))
            fets.append(fet)
            anterior = QgsPoint(p)
        pr.addFeatures(fets)
        self.crs = crs
        layer.setCrs(QgsCoordinateReferenceSystem(int(crs), 0))
        layer.updateExtents()

        QgsMapLayerRegistry.instance().addMapLayer(layer)

    def gera_tracado_vertices(self, pointerEmitter):
        self.iface.mapCanvas().setMapTool(pointerEmitter)
        self.name_tracado = "TracadoNovo"
        self.dialog.resize(200, 100)
        self.dialog.setWindowTitle(u"Traçado")
        self.dialog.btnClose = QtGui.QPushButton("Terminar", self.dialog)
        self.dialog.show()
        return self.name_tracado

    def setupUi2(self, Form):
        Form.setObjectName(_fromUtf8(u"Traçado Horizontal"))
        self.tableEstacas.setColumnCount(3)
        self.tableEstacas.setRowCount(0)
        self.tableEstacas.setColumnWidth(0, 54)
        self.tableEstacas.setColumnWidth(1, 254)
        self.tableEstacas.setColumnWidth(2, 154)
        self.tableEstacas.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.tableEstacas.setHorizontalHeaderLabels(
            (u"ID", u"Arquivo", u"Data criação"))