Beispiel #1
0
    def write(self, directory, name=None, session=None, replaceParamFile=None):
        """
        Index Map Write to File Method
        """

        # Initiate file
        if name != None:
            filename = '%s.%s' % (name, self.fileExtension)
            filePath = os.path.join(directory, filename)
        else:
            filePath = os.path.join(directory, self.filename)

        # If the raster field is not empty, write from this field
        if type(self.raster) != type(None):
            # Configure RasterConverter
            converter = RasterConverter(session)

            # Use MapKit RasterConverter to retrieve the raster as a GRASS ASCII Grid
            grassAsciiGrid = converter.getAsGrassAsciiRaster(
                rasterFieldName='raster',
                tableName=self.__tablename__,
                rasterIdFieldName='id',
                rasterId=self.id)

            # Write to file
            with open(filePath, 'w') as mapFile:
                mapFile.write(grassAsciiGrid)

        else:
            if self.rasterText is not None:
                # Open file and write, raster_text only
                with open(filePath, 'w') as mapFile:
                    mapFile.write(self.rasterText)
Beispiel #2
0
    def write(self, directory, name=None, session=None, replaceParamFile=None):
        """
        Index Map Write to File Method
        """

        # Initiate file
        if name != None:
            filename = '%s.%s' % (name, self.fileExtension)
            filePath = os.path.join(directory, filename)
        else:
            filePath = os.path.join(directory, self.filename)

        # If the raster field is not empty, write from this field
        if type(self.raster) != type(None):
            # Configure RasterConverter
            converter = RasterConverter(session)

            # Use MapKit RasterConverter to retrieve the raster as a GRASS ASCII Grid
            grassAsciiGrid = converter.getAsGrassAsciiRaster(rasterFieldName='raster',
                                                             tableName=self.__tablename__,
                                                             rasterIdFieldName='id',
                                                             rasterId=self.id)

            # Write to file
            with open(filePath, 'w') as mapFile:
                mapFile.write(grassAsciiGrid)

        else:
            if self.rasterText is not None:
                # Open file and write, raster_text only
                with open(filePath, 'w') as mapFile:
                    mapFile.write(self.rasterText)
Beispiel #3
0
    def getAsGrassAsciiGrid(self, session):
        """
        Retrieve the raster in the GRASS ASCII Grid format.

        Args:
            session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database.

        Returns:
            str: GRASS ASCII string.
        """
        if type(self.raster) != type(None):
            # Make sure the raster field is valid
            converter = RasterConverter(sqlAlchemyEngineOrSession=session)

            return converter.getAsGrassAsciiRaster(tableName=self.tableName,
                                                   rasterIdFieldName='id',
                                                   rasterId=self.id,
                                                   rasterFieldName=self.rasterColumnName)
Beispiel #4
0
    def getAsGrassAsciiGrid(self, session):
        """
        Retrieve the raster in the GRASS ASCII Grid format.

        Args:
            session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database.

        Returns:
            str: GRASS ASCII string.
        """  # noqa: E501
        if self.raster is not None:
            # Make sure the raster field is valid
            converter = RasterConverter(sqlAlchemyEngineOrSession=session)

            return converter.getAsGrassAsciiRaster(
                tableName=self.tableName,
                rasterIdFieldName='id',
                rasterId=self.id,
                rasterFieldName=self.rasterColumnName)
Beispiel #5
0
    def _write(self, session, openFile, replaceParamFile):
        """
        Raster Map File Write to File Method
        """
        # If the raster field is not empty, write from this field
        if self.raster is not None:
            # Configure RasterConverter
            converter = RasterConverter(session)

            # Use MapKit RasterConverter to retrieve the raster as a GRASS ASCII Grid
            grassAsciiGrid = converter.getAsGrassAsciiRaster(rasterFieldName='raster',
                                                             tableName=self.__tablename__,
                                                             rasterIdFieldName='id',
                                                             rasterId=self.id)
            # Write to file
            openFile.write(grassAsciiGrid)

        elif self.rasterText is not None:
            # Write file
            openFile.write(self.rasterText)
Beispiel #6
0
    def _write(self, session, openFile, replaceParamFile):
        """
        Raster Map File Write to File Method
        """
        # If the raster field is not empty, write from this field
        if self.raster is not None:
            # Configure RasterConverter
            converter = RasterConverter(session)

            # Use MapKit RasterConverter to retrieve the raster as a GRASS ASCII Grid
            grassAsciiGrid = converter.getAsGrassAsciiRaster(
                rasterFieldName='raster',
                tableName=self.__tablename__,
                rasterIdFieldName='id',
                rasterId=self.id)
            # Write to file
            openFile.write(grassAsciiGrid)

        elif self.rasterText is not None:
            # Write file
            openFile.write(self.rasterText)
Beispiel #7
0
    def getAsKmlClusters(self, session, path=None, documentName=None, colorRamp=ColorRampEnum.COLOR_RAMP_HUE, alpha=1.0,
                         noDataValue=None):
        """
        Retrieve the raster as a KML document with adjacent cells with the same value aggregated into vector polygons.
        The result is a vector representation cells clustered together. Cells with the no data value are excluded.

        Args:
            session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database.
            path (str, optional): Path to file where KML file will be written. Defaults to None.
            documentName (str, optional): Name of the KML document. This will be the name that appears in the legend.
                Defaults to 'Stream Network'.
            colorRamp (:mod:`mapkit.ColorRampGenerator.ColorRampEnum` or dict, optional): Use ColorRampEnum to select a
                default color ramp or a dictionary with keys 'colors' and 'interpolatedPoints' to specify a custom color
                ramp. The 'colors' key must be a list of RGB integer tuples (e.g.: (255, 0, 0)) and the
                'interpolatedPoints' must be an integer representing the number of points to interpolate between each
                color given in the colors list.
            alpha (float, optional): Set transparency of visualization. Value between 0.0 and 1.0 where 1.0 is 100%
                opaque and 0.0 is 100% transparent. Defaults to 1.0.
            noDataValue (float, optional): The value to treat as no data when generating visualizations of rasters.
                Defaults to 0.0.

        Returns:
            str: KML string
        """
        if type(self.raster) != type(None):
            # Set Document Name
            if documentName is None:
                try:
                    documentName = self.filename
                except AttributeError:
                    documentName = 'default'

            # Set no data value to default
            if noDataValue is None:
                noDataValue = self.defaultNoDataValue

            # Make sure the raster field is valid
            converter = RasterConverter(sqlAlchemyEngineOrSession=session)

            # Configure color ramp
            if isinstance(colorRamp, dict):
                converter.setCustomColorRamp(colorRamp['colors'], colorRamp['interpolatedPoints'])
            else:
                converter.setDefaultColorRamp(colorRamp)

            kmlString = converter.getAsKmlClusters(tableName=self.tableName,
                                                   rasterId=self.id,
                                                   rasterIdFieldName='id',
                                                   rasterFieldName=self.rasterColumnName,
                                                   documentName=documentName,
                                                   alpha=alpha,
                                                   noDataValue=noDataValue,
                                                   discreet=self.discreet)

            if path:
                with open(path, 'w') as f:
                    f.write(kmlString)

            return kmlString
Beispiel #8
0
    def getAsKmlPng(self,
                    session,
                    path=None,
                    documentName=None,
                    colorRamp=ColorRampEnum.COLOR_RAMP_HUE,
                    alpha=1.0,
                    noDataValue=None,
                    drawOrder=0,
                    cellSize=None,
                    resampleMethod='NearestNeighbour'):
        """
        Retrieve the raster as a PNG image ground overlay KML format. Coarse grid resolutions must be resampled to
        smaller cell/pixel sizes to avoid a "fuzzy" look. Cells with the no data value are excluded.

        Args:
            session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database.
            path (str, optional): Path to file where KML file will be written. Defaults to None.
            documentName (str, optional): Name of the KML document. This will be the name that appears in the legend.
                Defaults to 'Stream Network'.
            colorRamp (:mod:`mapkit.ColorRampGenerator.ColorRampEnum` or dict, optional): Use ColorRampEnum to select a
                default color ramp or a dictionary with keys 'colors' and 'interpolatedPoints' to specify a custom color
                ramp. The 'colors' key must be a list of RGB integer tuples (e.g.: (255, 0, 0)) and the
                'interpolatedPoints' must be an integer representing the number of points to interpolate between each
                color given in the colors list.
            alpha (float, optional): Set transparency of visualization. Value between 0.0 and 1.0 where 1.0 is 100%
                opaque and 0.0 is 100% transparent. Defaults to 1.0.
            noDataValue (float, optional): The value to treat as no data when generating visualizations of rasters.
                Defaults to 0.0.
            drawOrder (int, optional): Set the draw order of the images. Defaults to 0.
            cellSize (float, optional): Define the cell size in the units of the project projection at which to resample
                the raster to generate the PNG. Defaults to None which will cause the PNG to be generated with the
                original raster cell size. It is generally better to set this to a size smaller than the original cell
                size to obtain a higher resolution image. However, computation time increases exponentially as the cell
                size is decreased.
            resampleMethod (str, optional): If cellSize is set, this method will be used to resample the raster. Valid
                values include: NearestNeighbour, Bilinear, Cubic, CubicSpline, and Lanczos. Defaults to
                NearestNeighbour.

        Returns:
            (str, list): Returns a KML string and a list of binary strings that are the PNG images.
        """  # noqa: E501
        if self.raster is not None:
            # Set Document Name
            if documentName is None:
                try:
                    documentName = self.filename
                except AttributeError:
                    documentName = 'default'

            # Set no data value to default
            if noDataValue is None:
                noDataValue = self.defaultNoDataValue

            # Make sure the raster field is valid
            converter = RasterConverter(sqlAlchemyEngineOrSession=session)

            # Configure color ramp
            if isinstance(colorRamp, dict):
                converter.setCustomColorRamp(colorRamp['colors'],
                                             colorRamp['interpolatedPoints'])
            else:
                converter.setDefaultColorRamp(colorRamp)

            kmlString, binaryPngString = converter.getAsKmlPng(
                tableName=self.tableName,
                rasterId=self.id,
                rasterIdFieldName='id',
                rasterFieldName=self.rasterColumnName,
                documentName=documentName,
                alpha=alpha,
                drawOrder=drawOrder,
                noDataValue=noDataValue,
                cellSize=cellSize,
                resampleMethod=resampleMethod,
                discreet=self.discreet)
            if path:
                directory = os.path.dirname(path)
                archiveName = (os.path.split(path)[1]).split('.')[0]
                kmzPath = os.path.join(directory, (archiveName + '.kmz'))

                with ZipFile(kmzPath, 'w') as kmz:
                    kmz.writestr(archiveName + '.kml', kmlString)
                    kmz.writestr('raster.png', binaryPngString)

            return kmlString, binaryPngString
Beispiel #9
0
from mapkit.RasterConverter import RasterConverter
from sqlalchemy import create_engine

# Setup SQLAlchemy connection
engine = create_engine('postgresql://*****:*****@ter@localhost:5432/gsshapy_postgis')

tableName = 'map_kit_rasters'
rasterId = 5
path = '/Users/swainn/projects/post_gis/map_kit_rasters/soil_cluster.kml'

# Get supported gdal raster formats
gdalFormats = RasterConverter.supportedGdalRasterFormats(engine)

for key, value in gdalFormats.items():
    print key, value

# Configure raster converter
converter = RasterConverter(engine)

# Convert PostGIS raster to GDAL format
result = converter.getAsGdalRaster(rasterFieldName='raster',
                                   tableName=tableName,
                                   rasterIdFieldName='id',
                                   rasterId=rasterId,
                                   gdalFormat='JPEG',
                                   QUALITY=50)

# Convert PostGIS raster to GRASS ASCII Grid format
result = converter.getAsGrassAsciiRaster(rasterFieldName='raster',
                                         tableName=tableName,
                                         rasterIdFieldName='id',
Beispiel #10
0
    def getAsKmlPngAnimation(self,
                             session,
                             projectFile=None,
                             path=None,
                             documentName=None,
                             colorRamp=None,
                             alpha=1.0,
                             noDataValue=0,
                             drawOrder=0,
                             cellSize=None,
                             resampleMethod='NearestNeighbour'):
        """
        Retrieve the WMS dataset as a PNG time stamped KMZ

        Args:
            session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database.
            projectFile(:class:`gsshapy.orm.ProjectFile`): Project file object for the GSSHA project to which the WMS dataset belongs.
            path (str, optional): Path to file where KML file will be written. Defaults to None.
            documentName (str, optional): Name of the KML document. This will be the name that appears in the legend.
                Defaults to 'Stream Network'.
            colorRamp (:mod:`mapkit.ColorRampGenerator.ColorRampEnum` or dict, optional): Use ColorRampEnum to select a
                default color ramp or a dictionary with keys 'colors' and 'interpolatedPoints' to specify a custom color
                ramp. The 'colors' key must be a list of RGB integer tuples (e.g.: (255, 0, 0)) and the
                'interpolatedPoints' must be an integer representing the number of points to interpolate between each
                color given in the colors list.
            alpha (float, optional): Set transparency of visualization. Value between 0.0 and 1.0 where 1.0 is 100%
                opaque and 0.0 is 100% transparent. Defaults to 1.0.
            noDataValue (float, optional): The value to treat as no data when generating visualizations of rasters.
                Defaults to 0.0.
            drawOrder (int, optional): Set the draw order of the images. Defaults to 0.
            cellSize (float, optional): Define the cell size in the units of the project projection at which to resample
                the raster to generate the PNG. Defaults to None which will cause the PNG to be generated with the
                original raster cell size. It is generally better to set this to a size smaller than the original cell
                size to obtain a higher resolution image. However, computation time increases exponentially as the cell
                size is decreased.
            resampleMethod (str, optional): If cellSize is set, this method will be used to resample the raster. Valid
                values include: NearestNeighbour, Bilinear, Cubic, CubicSpline, and Lanczos. Defaults to
                NearestNeighbour.

        Returns:
            (str, list): Returns a KML string and a list of binary strings that are the PNG images.
        """  # noqa:E501
        # Prepare rasters
        timeStampedRasters = self._assembleRasterParams(
            projectFile, self.rasters)

        # Make sure the raster field is valid
        converter = RasterConverter(sqlAlchemyEngineOrSession=session)

        # Configure color ramp
        if isinstance(colorRamp, dict):
            converter.setCustomColorRamp(colorRamp['colors'],
                                         colorRamp['interpolatedPoints'])
        else:
            converter.setDefaultColorRamp(colorRamp)

        if documentName is None:
            documentName = self.fileExtension

        kmlString, binaryPngStrings = converter.getAsKmlPngAnimation(
            tableName=WMSDatasetRaster.tableName,
            timeStampedRasters=timeStampedRasters,
            rasterIdFieldName='id',
            rasterFieldName='raster',
            documentName=documentName,
            alpha=alpha,
            drawOrder=drawOrder,
            cellSize=cellSize,
            noDataValue=noDataValue,
            resampleMethod=resampleMethod)

        if path:
            directory = os.path.dirname(path)
            archiveName = (os.path.split(path)[1]).split('.')[0]
            kmzPath = os.path.join(directory, (archiveName + '.kmz'))

            with ZipFile(kmzPath, 'w') as kmz:
                kmz.writestr(archiveName + '.kml', kmlString)

                for index, binaryPngString in enumerate(binaryPngStrings):
                    kmz.writestr('raster{0}.png'.format(index),
                                 binaryPngString)

        return kmlString, binaryPngStrings
Beispiel #11
0
    def getAsKmlGridAnimation(self,
                              session,
                              projectFile=None,
                              path=None,
                              documentName=None,
                              colorRamp=None,
                              alpha=1.0,
                              noDataValue=0.0):
        """
        Retrieve the WMS dataset as a gridded time stamped KML string.

        Args:
            session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database.
            projectFile(:class:`gsshapy.orm.ProjectFile`): Project file object for the GSSHA project to which the WMS dataset belongs.
            path (str, optional): Path to file where KML file will be written. Defaults to None.
            documentName (str, optional): Name of the KML document. This will be the name that appears in the legend.
                Defaults to 'Stream Network'.
            colorRamp (:mod:`mapkit.ColorRampGenerator.ColorRampEnum` or dict, optional): Use ColorRampEnum to select a
                default color ramp or a dictionary with keys 'colors' and 'interpolatedPoints' to specify a custom color
                ramp. The 'colors' key must be a list of RGB integer tuples (e.g.: (255, 0, 0)) and the
                'interpolatedPoints' must be an integer representing the number of points to interpolate between each
                color given in the colors list.
            alpha (float, optional): Set transparency of visualization. Value between 0.0 and 1.0 where 1.0 is 100%
                opaque and 0.0 is 100% transparent. Defaults to 1.0.
            noDataValue (float, optional): The value to treat as no data when generating visualizations of rasters.
                Defaults to 0.0.

        Returns:
            str: KML string
        """  # noqa:E501
        # Prepare rasters
        timeStampedRasters = self._assembleRasterParams(
            projectFile, self.rasters)

        # Create a raster converter
        converter = RasterConverter(sqlAlchemyEngineOrSession=session)

        # Configure color ramp
        if isinstance(colorRamp, dict):
            converter.setCustomColorRamp(colorRamp['colors'],
                                         colorRamp['interpolatedPoints'])
        else:
            converter.setDefaultColorRamp(colorRamp)

        if documentName is None:
            documentName = self.fileExtension

        kmlString = converter.getAsKmlGridAnimation(
            tableName=WMSDatasetRaster.tableName,
            timeStampedRasters=timeStampedRasters,
            rasterIdFieldName='id',
            rasterFieldName='raster',
            documentName=documentName,
            alpha=alpha,
            noDataValue=noDataValue)

        if path:
            with open(path, 'w') as f:
                f.write(kmlString)

        return kmlString
# For pretty print functionality for debugging
# not recommended for production
# import xml.dom.minidom
import time

# Setup SQLAlchemy connection
engine = create_engine('postgresql://*****:*****@ter@localhost:5432/raster_test')

tableName = 'map_kit_rasters'
rasterId = 3
name = 'Texas Groundwater Elevation Clusters'
path = '/Users/swainn/projects/post_gis/large_rasters/waterelev_cluster.kml'

# Initialize raster converter
converter = RasterConverter(sqlAlchemyEngineOrSession=engine)

# Configure RasterConverter instance with custom color ramp
colors = [(255, 0, 0), (0, 120, 120), (0, 255, 0), (0, 0, 255)]
converter.setCustomColorRamp(colors, 3)
# converter.setDefaultColorRamp(RasterConverter.COLOR_RAMP_HUE)

# Start timer
start = time.time()

kmlString = converter.getAsKmlClusters(tableName=tableName, 
                                              rasterId=rasterId,
                                              documentName=name)

with open(path, 'w') as f:
#     pretty = xml.dom.minidom.parseString(kmlString)
Beispiel #13
0
# import xml.dom.minidom
import time, os
from zipfile import ZipFile

# Setup SQLAlchemy connection
engine = create_engine(
    'postgresql://*****:*****@ter@localhost:5432/raster_test')

tableName = 'map_kit_rasters'
rasterId = 4
documentName = 'Texas Elevation PNG'
directory = '/Users/swainn/projects/post_gis/large_rasters'
archiveName = 'texas_elev_png'

# Initialize raster converter
converter = RasterConverter(sqlAlchemyEngineOrSession=engine)

# Configure RasterConverter instance
# colors = [(255, 0, 0),(0, 255, 0),(0, 0, 255)]
# converter.setCustomColorRamp(colors, 2)
converter.setDefaultColorRamp(RasterConverter.COLOR_RAMP_AQUA)

# Start timer
start = time.time()

kmlString, binaryPngString = converter.getAsKmlPng(tableName=tableName,
                                                   rasterId=rasterId,
                                                   documentName=documentName)

# Create kmz (zip) archive
kmzPath = os.path.join(directory, (archiveName + '.kmz'))
Beispiel #14
0
# not recommended for production
# import xml.dom.minidom
import time, os
from zipfile import ZipFile

# Setup SQLAlchemy connection
engine = create_engine('postgresql://*****:*****@ter@localhost:5432/gsshapy_postgis')

tableName = 'map_kit_rasters'
rasterId = 5
documentName = 'Soils Index Map PNG'
directory = '/Users/swainn/projects/post_gis/map_kit_rasters'
archiveName = 'soil_index_png'

# Initialize raster converter
converter = RasterConverter(sqlAlchemyEngine=engine)

# Configure RasterConverter instance
colors = [(255, 0, 0),(0, 255, 0),(0, 0, 255)]
converter.setCustomColorRamp(colors, 2)
# converter.setDefaultColorRamp(RasterConverter.COLOR_RAMP_HUE)

# Start timer
start = time.time()

kmlString, binaryPngString = converter.getAsKmlPng(tableName=tableName, 
                                                   rasterId=rasterId,
                                                   documentName=documentName)


# Create kmz (zip) archive
Beispiel #15
0
# For pretty print functionality for debugging
# not recommended for production
# import xml.dom.minidom
import time

# Setup SQLAlchemy connection
engine = create_engine(
    'postgresql://*****:*****@ter@localhost:5432/raster_test')

tableName = 'map_kit_rasters'
rasterId = 3
name = 'Texas Groundwater Elevation Gridded'
path = '/Users/swainn/projects/post_gis/large_rasters/waterelev_gridded.kml'

# Initialize raster converter
converter = RasterConverter(sqlAlchemyEngineOrSession=engine)
# colors = [(255, 0, 0),(0, 255, 0),(0, 0, 255)]
# converter.setCustomColorRamp(colors, 10)
converter.setDefaultColorRamp(RasterConverter.COLOR_RAMP_TERRAIN)

# Start timer
start = time.time()

kmlString = converter.getAsKmlGrid(tableName=tableName,
                                   rasterId=rasterId,
                                   documentName=name)

with open(path, 'w') as f:
    #     pretty = xml.dom.minidom.parseString(kmlString)
    #     f.write(pretty.toprettyxml())
    f.write(kmlString)
Beispiel #16
0
# For pretty print functionality for debugging
# not recommended for production
# import xml.dom.minidom
import time

# Setup SQLAlchemy connection
engine = create_engine('postgresql://*****:*****@ter@localhost:5432/gsshapy_postgis')

tableName = 'map_kit_rasters'
rasterId = 5
name = 'Soils Index Map Clusters'
path = '/Users/swainn/projects/post_gis/map_kit_rasters/soil_cluster.kml'

# Initialize raster converter
converter = RasterConverter(sqlAlchemyEngine=engine)

# Configure RasterConverter instance with custom color ramp
colors = [(255, 0, 0),(0, 255, 0),(0, 0, 255)]
converter.setCustomColorRamp(colors, 10)

# Start timer
start = time.time()

kmlString = converter.getAsKmlClusters(tableName=tableName, 
                                              rasterId=rasterId,
                                              documentName=name)

with open(path, 'w') as f:
#     pretty = xml.dom.minidom.parseString(kmlString)
#     f.write(pretty.toprettyxml())
Beispiel #17
0
    def getAsKmlClusters(self,
                         session,
                         path=None,
                         documentName=None,
                         colorRamp=ColorRampEnum.COLOR_RAMP_HUE,
                         alpha=1.0,
                         noDataValue=None):
        """
        Retrieve the raster as a KML document with adjacent cells with the same value aggregated into vector polygons.
        The result is a vector representation cells clustered together. Cells with the no data value are excluded.

        Args:
            session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database.
            path (str, optional): Path to file where KML file will be written. Defaults to None.
            documentName (str, optional): Name of the KML document. This will be the name that appears in the legend.
                Defaults to 'Stream Network'.
            colorRamp (:mod:`mapkit.ColorRampGenerator.ColorRampEnum` or dict, optional): Use ColorRampEnum to select a
                default color ramp or a dictionary with keys 'colors' and 'interpolatedPoints' to specify a custom color
                ramp. The 'colors' key must be a list of RGB integer tuples (e.g.: (255, 0, 0)) and the
                'interpolatedPoints' must be an integer representing the number of points to interpolate between each
                color given in the colors list.
            alpha (float, optional): Set transparency of visualization. Value between 0.0 and 1.0 where 1.0 is 100%
                opaque and 0.0 is 100% transparent. Defaults to 1.0.
            noDataValue (float, optional): The value to treat as no data when generating visualizations of rasters.
                Defaults to 0.0.

        Returns:
            str: KML string
        """  # noqa: E501
        if self.raster is not None:
            # Set Document Name
            if documentName is None:
                try:
                    documentName = self.filename
                except AttributeError:
                    documentName = 'default'

            # Set no data value to default
            if noDataValue is None:
                noDataValue = self.defaultNoDataValue

            # Make sure the raster field is valid
            converter = RasterConverter(sqlAlchemyEngineOrSession=session)

            # Configure color ramp
            if isinstance(colorRamp, dict):
                converter.setCustomColorRamp(colorRamp['colors'],
                                             colorRamp['interpolatedPoints'])
            else:
                converter.setDefaultColorRamp(colorRamp)

            kmlString = converter.getAsKmlClusters(
                tableName=self.tableName,
                rasterId=self.id,
                rasterIdFieldName='id',
                rasterFieldName=self.rasterColumnName,
                documentName=documentName,
                alpha=alpha,
                noDataValue=noDataValue,
                discreet=self.discreet)

            if path:
                with open(path, 'w') as f:
                    f.write(kmlString)

            return kmlString
Beispiel #18
0
    def getAsKmlPng(self, session, path=None, documentName=None, colorRamp=ColorRampEnum.COLOR_RAMP_HUE, alpha=1.0,
                    noDataValue=None, drawOrder=0, cellSize=None, resampleMethod='NearestNeighbour'):
        """
        Retrieve the raster as a PNG image ground overlay KML format. Coarse grid resolutions must be resampled to
        smaller cell/pixel sizes to avoid a "fuzzy" look. Cells with the no data value are excluded.

        Args:
            session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database.
            path (str, optional): Path to file where KML file will be written. Defaults to None.
            documentName (str, optional): Name of the KML document. This will be the name that appears in the legend.
                Defaults to 'Stream Network'.
            colorRamp (:mod:`mapkit.ColorRampGenerator.ColorRampEnum` or dict, optional): Use ColorRampEnum to select a
                default color ramp or a dictionary with keys 'colors' and 'interpolatedPoints' to specify a custom color
                ramp. The 'colors' key must be a list of RGB integer tuples (e.g.: (255, 0, 0)) and the
                'interpolatedPoints' must be an integer representing the number of points to interpolate between each
                color given in the colors list.
            alpha (float, optional): Set transparency of visualization. Value between 0.0 and 1.0 where 1.0 is 100%
                opaque and 0.0 is 100% transparent. Defaults to 1.0.
            noDataValue (float, optional): The value to treat as no data when generating visualizations of rasters.
                Defaults to 0.0.
            drawOrder (int, optional): Set the draw order of the images. Defaults to 0.
            cellSize (float, optional): Define the cell size in the units of the project projection at which to resample
                the raster to generate the PNG. Defaults to None which will cause the PNG to be generated with the
                original raster cell size. It is generally better to set this to a size smaller than the original cell
                size to obtain a higher resolution image. However, computation time increases exponentially as the cell
                size is decreased.
            resampleMethod (str, optional): If cellSize is set, this method will be used to resample the raster. Valid
                values include: NearestNeighbour, Bilinear, Cubic, CubicSpline, and Lanczos. Defaults to
                NearestNeighbour.

        Returns:
            (str, list): Returns a KML string and a list of binary strings that are the PNG images.
        """
        if type(self.raster) != type(None):
            # Set Document Name
            if documentName is None:
                try:
                    documentName = self.filename
                except AttributeError:
                    documentName = 'default'

            # Set no data value to default
            if noDataValue is None:
                noDataValue = self.defaultNoDataValue

            # Make sure the raster field is valid
            converter = RasterConverter(sqlAlchemyEngineOrSession=session)

            # Configure color ramp
            if isinstance(colorRamp, dict):
                converter.setCustomColorRamp(colorRamp['colors'], colorRamp['interpolatedPoints'])
            else:
                converter.setDefaultColorRamp(colorRamp)

            kmlString, binaryPngString = converter.getAsKmlPng(tableName=self.tableName,
                                                               rasterId=self.id,
                                                               rasterIdFieldName='id',
                                                               rasterFieldName=self.rasterColumnName,
                                                               documentName=documentName,
                                                               alpha=alpha,
                                                               drawOrder=drawOrder,
                                                               noDataValue=noDataValue,
                                                               cellSize=cellSize,
                                                               resampleMethod=resampleMethod,
                                                               discreet=self.discreet)
            if path:
                directory = os.path.dirname(path)
                archiveName = (os.path.split(path)[1]).split('.')[0]
                kmzPath = os.path.join(directory, (archiveName + '.kmz'))

                with ZipFile(kmzPath, 'w') as kmz:
                    kmz.writestr(archiveName + '.kml', kmlString)
                    kmz.writestr('raster.png', binaryPngString)

            return kmlString, binaryPngString