def exportRaster(parameters):
    # Open layer from inputFile
    inputFile = 'Ugrid:' + '"' + parameters['INPUT_LAYER'] + '"'
    meshfile = inputFile.strip().split('/')[-1]
    meshlayer = meshfile.split('.')[0]
    layer = QgsMeshLayer(inputFile, meshlayer, 'mdal')

    # Check if layer is valid
    if layer.isValid() is True:
        # Get parameters for processing
        dataset = parameters['INPUT_GROUP']
        timestep = parameters['INPUT_TIMESTEP']
        mupp = parameters['MAP_UNITS_PER_PIXEL']
        extent = layer.extent()
        output_layer = parameters['OUTPUT_RASTER']
        width = extent.width() / mupp
        height = extent.height() / mupp
        crs = layer.crs()
        crs.createFromSrid(4326)
        transform_context = QgsProject.instance().transformContext()
        output_format = QgsRasterFileWriter.driverForExtension(
            os.path.splitext(output_layer)[1])

        # Open output file for writing
        rfw = QgsRasterFileWriter(output_layer)
        rfw.setOutputProviderKey('gdal')
        rfw.setOutputFormat(output_format)

        # Create one band raster
        rdp = rfw.createOneBandRaster(Qgis.Float64, width, height, extent, crs)

        # Get dataset index
        dataset_index = QgsMeshDatasetIndex(dataset, timestep)

        # Regred mesh layer to raster
        block = QgsMeshUtils.exportRasterBlock(layer, dataset_index, crs,
                                               transform_context, mupp, extent)

        # Write raster to GeoTiff file
        rdp.writeBlock(block, 1)
        rdp.setNoDataValue(1, block.noDataValue())
        rdp.setEditable(False)

        logger.info('Regridded mesh data in ' + meshfile.split('"')[0] +
                    ' to float64 grid, and saved to tiff (' +
                    output_layer.split('/')[-1] + ') file.')

        return (output_layer)

    if layer.isValid() is False:
        raise Exception('Invalid mesh')
Пример #2
0
    def testStepSize(self):
        ml = QgsMeshLayer(
            os.path.join(unitTestDataPath(), '3d', 'elev_mesh.2dm'), 'mdal',
            'mdal')
        self.assertTrue(ml.isValid())
        ml.setCrs(QgsCoordinateReferenceSystem('EPSG:27700'))

        curve = QgsLineString()
        curve.fromWkt(
            'LineString (-348095.18706532847136259 6633687.0235139261931181, -347271.57799367723055184 6633093.13086318597197533, -346140.60267287614988163 6632697.89590711053460836, -345777.013075890194159 6631575.50219972990453243)'
        )
        req = QgsProfileRequest(curve)
        # set a smaller step size then would be automatically calculated
        req.setStepDistance(10)

        # set correct crs for linestring and re-try
        req.setCrs(QgsCoordinateReferenceSystem('EPSG:3857'))
        generator = ml.createProfileGenerator(req)
        self.assertTrue(generator.generateProfile())

        r = generator.takeResults()
        results = r.distanceToHeightMap()
        self.assertEqual(len(results), 216)
        first_point = min(results.keys())
        last_point = max(results.keys())
        self.assertAlmostEqual(results[first_point], 152.87405434310168, 0)
        self.assertAlmostEqual(results[last_point], 98.78085001573021, 0)

        self.assertAlmostEqual(r.zRange().lower(), 80, 2)
        self.assertAlmostEqual(r.zRange().upper(), 152.874, 0)
Пример #3
0
    def testMeshProvider(self):
        """
        Test QgsMeshTerrainProvider
        """
        provider = QgsMeshTerrainProvider()
        self.assertEqual(provider.type(), 'mesh')

        # without layer assigned
        self.assertFalse(provider.crs().isValid())
        self.assertTrue(math.isnan(provider.heightAt(1, 2)))

        # add mesh layer to project
        p = QgsProject()
        mesh_layer = QgsMeshLayer(
            os.path.join(unitTestDataPath(), 'mesh', 'quad_flower.2dm'),
            'mesh', 'mdal')
        self.assertTrue(mesh_layer.isValid())
        p.addMapLayer(mesh_layer)

        provider.setLayer(mesh_layer)
        self.assertEqual(provider.layer(), mesh_layer)

        # not implemented yet
        # self.assertEqual(provider.heightAt(1,2), 0)
        # self.assertEqual(provider.heightAt(106.4105,-6.6341), 11.0)

        provider.setOffset(5)
        self.assertEqual(provider.offset(), 5)
        provider.setScale(3)
        self.assertEqual(provider.scale(), 3)

        clone = provider.clone()
        self.assertIsInstance(clone, QgsMeshTerrainProvider)
        self.assertEqual(clone.layer(), mesh_layer)
        self.assertEqual(clone.offset(), 5)
        self.assertEqual(clone.scale(), 3)

        # via xml
        doc = QDomDocument("testdoc")

        context = QgsReadWriteContext()
        parent_elem = doc.createElement('test')
        element = provider.writeXml(doc, context)
        parent_elem.appendChild(element)

        from_xml = QgsMeshTerrainProvider()
        self.assertTrue(from_xml.readXml(parent_elem, context))

        self.assertEqual(from_xml.offset(), 5)
        self.assertEqual(from_xml.scale(), 3)

        # layer won't be resolved till we resolve references from project
        self.assertFalse(from_xml.layer())
        from_xml.resolveReferences(p)
        self.assertEqual(from_xml.layer(), mesh_layer)
    def testSnapping(self):
        ml = QgsMeshLayer(os.path.join(unitTestDataPath(), '3d', 'elev_mesh.2dm'), 'mdal', 'mdal')
        self.assertTrue(ml.isValid())
        ml.setCrs(QgsCoordinateReferenceSystem('EPSG:27700'))

        curve = QgsLineString()
        curve.fromWkt('LineString (321621.3770066662109457 129734.87810317709227093, 321894.21278918092139065 129858.49142702402605209)')
        req = QgsProfileRequest(curve)

        generator = ml.createProfileGenerator(req)
        self.assertTrue(generator.generateProfile())

        r = generator.takeResults()

        # try snapping some points
        context = QgsProfileSnapContext()
        res = r.snapPoint(QgsProfilePoint(-10, -10), context)
        self.assertFalse(res.isValid())

        context.maximumSurfaceDistanceDelta = 0
        context.maximumSurfaceElevationDelta = 3
        context.maximumPointDistanceDelta = 0
        context.maximumPointElevationDelta = 0
        res = r.snapPoint(QgsProfilePoint(0, 70), context)
        self.assertTrue(res.isValid())
        self.assertEqual(res.snappedPoint.distance(), 0)
        self.assertAlmostEqual(res.snappedPoint.elevation(), 71.8, 0)

        context.maximumSurfaceDistanceDelta = 0
        context.maximumSurfaceElevationDelta = 5
        res = r.snapPoint(QgsProfilePoint(200, 79), context)
        self.assertTrue(res.isValid())
        self.assertEqual(res.snappedPoint.distance(), 200)
        self.assertAlmostEqual(res.snappedPoint.elevation(), 75.841, 1)

        res = r.snapPoint(QgsProfilePoint(200, 85), context)
        self.assertFalse(res.isValid())
    def testIdentify(self):
        ml = QgsMeshLayer(os.path.join(unitTestDataPath(), '3d', 'elev_mesh.2dm'), 'mdal', 'mdal')
        self.assertTrue(ml.isValid())
        ml.setCrs(QgsCoordinateReferenceSystem('EPSG:27700'))

        curve = QgsLineString()
        curve.fromWkt('LineString (321621.3770066662109457 129734.87810317709227093, 321894.21278918092139065 129858.49142702402605209)')
        req = QgsProfileRequest(curve)

        generator = ml.createProfileGenerator(req)
        self.assertTrue(generator.generateProfile())

        r = generator.takeResults()

        # try identifying
        context = QgsProfileIdentifyContext()
        res = r.identify(QgsProfilePoint(-10, -10), context)
        self.assertFalse(res)

        context.maximumSurfaceDistanceDelta = 0
        context.maximumSurfaceElevationDelta = 3
        context.maximumPointDistanceDelta = 0
        context.maximumPointElevationDelta = 0
        res = r.identify(QgsProfilePoint(0, 70), context)
        self.assertEqual(len(res), 1)
        self.assertEqual(res[0].layer(), ml)
        self.assertEqual(res[0].results(), [{'distance': 0.0, 'elevation': 71.8236528075051}])

        context.maximumSurfaceDistanceDelta = 0
        context.maximumSurfaceElevationDelta = 5
        res = r.identify(QgsProfilePoint(200, 79), context)
        self.assertEqual(len(res), 1)
        self.assertEqual(res[0].layer(), ml)
        self.assertEqual(res[0].results(), [{'distance': 200.0, 'elevation': 75.84131736154015}])

        res = r.identify(QgsProfilePoint(200, 85), context)
        self.assertFalse(res)
Пример #6
0
    def testMeshProvider(self):
        """
        Test QgsMeshTerrainProvider
        """
        provider = QgsMeshTerrainProvider()
        self.assertEqual(provider.type(), 'mesh')

        # without layer assigned
        self.assertFalse(provider.crs().isValid())
        self.assertTrue(math.isnan(provider.heightAt(1, 2)))

        # add mesh layer to project
        p = QgsProject()
        mesh_layer = QgsMeshLayer(
            os.path.join(unitTestDataPath(), '3d', 'elev_mesh.2dm'), 'mdal',
            'mdal')
        mesh_layer.setCrs(QgsCoordinateReferenceSystem('EPSG:27700'))
        self.assertTrue(mesh_layer.isValid())
        p.addMapLayer(mesh_layer)

        provider.setLayer(mesh_layer)
        self.assertEqual(provider.layer(), mesh_layer)
        self.assertEqual(provider.crs().authid(), 'EPSG:27700')

        self.assertTrue(math.isnan(provider.heightAt(1, 2)))
        self.assertAlmostEqual(provider.heightAt(321695.2, 129990.5),
                               89.49743150684921, 5)

        provider.setOffset(5)
        self.assertEqual(provider.offset(), 5)
        provider.setScale(3)
        self.assertEqual(provider.scale(), 3)

        clone = provider.clone()
        self.assertIsInstance(clone, QgsMeshTerrainProvider)
        self.assertEqual(clone.layer(), mesh_layer)
        self.assertEqual(clone.offset(), 5)
        self.assertEqual(clone.scale(), 3)

        # via xml
        doc = QDomDocument("testdoc")

        context = QgsReadWriteContext()
        parent_elem = doc.createElement('test')
        element = provider.writeXml(doc, context)
        parent_elem.appendChild(element)

        from_xml = QgsMeshTerrainProvider()
        self.assertTrue(from_xml.readXml(parent_elem, context))

        self.assertEqual(from_xml.offset(), 5)
        self.assertEqual(from_xml.scale(), 3)

        # layer won't be resolved till we resolve references from project
        self.assertFalse(from_xml.layer())
        from_xml.resolveReferences(p)
        self.assertEqual(from_xml.layer(), mesh_layer)

        # test equals
        provider1 = QgsMeshTerrainProvider()
        provider2 = QgsMeshTerrainProvider()
        self.assertTrue(provider1.equals(provider2))
        self.assertFalse(provider1.equals(QgsFlatTerrainProvider()))
        provider1.setOffset(1)
        self.assertFalse(provider1.equals(provider2))
        provider2.setOffset(1)
        self.assertTrue(provider1.equals(provider2))
        provider1.setScale(11)
        self.assertFalse(provider1.equals(provider2))
        provider2.setScale(11)
        self.assertTrue(provider1.equals(provider2))
        provider1.setLayer(mesh_layer)
        self.assertFalse(provider1.equals(provider2))
        provider2.setLayer(mesh_layer)
        self.assertTrue(provider1.equals(provider2))