Exemplo n.º 1
0
def has_geos():
    pnt1 = ogr.CreateGeometryFromWkt('POINT(10 20)')
    pnt2 = ogr.CreateGeometryFromWkt('POINT(30 20)')
    ogrex = ogr.GetUseExceptions()
    gdalex = gdal.GetUseExceptions()
    gdal.DontUseExceptions()
    ogr.DontUseExceptions()
    hasgeos = pnt1.Union(pnt2) is not None
    if ogrex:
        ogr.UseExceptions()
    if gdalex:
        gdal.UseExceptions()
    return hasgeos
Exemplo n.º 2
0
def test_basic_test_17_part_2():

    # For some odd reason, this fails on the Travis CI targets after unrelated
    # changes (https://travis-ci.com/github/OSGeo/gdal/jobs/501940381)
    if gdaltest.skip_on_travis():
        pytest.skip()

    from osgeo import ogr

    for _ in range(2):
        ogr.UseExceptions()
        gdal.UseExceptions()
        flag = False
        try:
            ogr.DontUseExceptions()
            gdal.DontUseExceptions()
            flag = True
        except:
            gdal.DontUseExceptions()
            ogr.DontUseExceptions()
        assert not flag, 'expected failure'
        assert not gdal.GetUseExceptions()
        assert not ogr.GetUseExceptions()
Exemplo n.º 3
0
def test_ogr_basic_11():

    if not ogrtest.have_geos():
        pytest.skip()

    used_exceptions_before = ogr.GetUseExceptions()
    for _ in range(2):
        ogr.UseExceptions()
        geom = ogr.CreateGeometryFromWkt(
            'POLYGON ((-65 0, -30 -30, -30 0, -65 -30, -65 0))')
        with gdaltest.error_handler():
            geom.IsValid()
    if used_exceptions_before == 0:
        ogr.DontUseExceptions()
def has_spatialite():
    """Determine if the current GDAL is built with SpatiaLite support."""
    use_exceptions = ogr.GetUseExceptions()
    ogr.UseExceptions()
    try:
        ds = ogr.GetDriverByName("Memory").CreateDataSource("memory")
        sql = '''SELECT sqlite_version(), spatialite_version()'''
        lyr = ds.ExecuteSQL(sql, dialect="SQLite")
        return True
    except Exception as e:
        return False
    finally:
        if not use_exceptions:
            ogr.DontUseExceptions()
Exemplo n.º 5
0
def ogr_basic_11():

    if not ogrtest.have_geos():
        return 'skip'

    used_exceptions_before = ogr.GetUseExceptions()
    for i in range(2):
        ogr.UseExceptions()
        geom = ogr.CreateGeometryFromWkt('POLYGON ((-65 0, -30 -30, -30 0, -65 -30, -65 0))')
        geom.IsValid()
    if used_exceptions_before == 0:
        ogr.DontUseExceptions()

    return 'success'
Exemplo n.º 6
0
def opensAsVector(filename):
    """
    Return True if filename opens as an OGR vector, False otherwise
    """
    usingExceptions = False
    if hasattr(ogr, 'GetUseExceptions'):
        usingExceptions = ogr.GetUseExceptions()
    ogr.UseExceptions()
    try:
        ds = ogr.Open(filename)
    except Exception:
        ds = None
    opensOK = (ds is not None)

    if not usingExceptions:
        ogr.DontUseExceptions()
    return opensOK
Exemplo n.º 7
0
def test_basic_test_17():

    from osgeo import ogr

    for _ in range(2):
        ogr.UseExceptions()
        gdal.UseExceptions()
        flag = False
        try:
            gdal.Open('do_not_exist')
            flag = True
        except RuntimeError:
            pass
        assert not flag, 'expected failure'
        gdal.DontUseExceptions()
        ogr.DontUseExceptions()
        assert not gdal.GetUseExceptions()
        assert not ogr.GetUseExceptions()
Exemplo n.º 8
0
def test_ogr_basic_15():

    ds = ogr.Open('data/poly.shp')
    lyr = ds.GetLayer(0)

    used_exceptions_before = ogr.GetUseExceptions()
    ogr.UseExceptions()
    try:
        lyr.CreateFeature(ogr.Feature(lyr.GetLayerDefn()))
    except RuntimeError as e:
        ok = str(e).find('CreateFeature : unsupported operation on a read-only datasource') >= 0
        assert ok, ('Got: %s' + str(e))
        return
    finally:
        if used_exceptions_before == 0:
            ogr.DontUseExceptions()

    pytest.fail('Expected exception')
Exemplo n.º 9
0
    def __init__(self):
        """
        Constructor.
        """
        super(InventoryThread, self).__init__()

        self.messenger = InventoryMessages(self)
        self.files = list()
        gdal.DontUseExceptions()
        ogr.DontUseExceptions()
        self.layer_attributes = [
            QgsField('filename', QVariant.String),
            QgsField('date', QVariant.String),
            QgsField('size', QVariant.String),
            QgsField('extension', QVariant.String)
        ]
        self.qgsattr = QgsFields()
        for i in self.layer_attributes:
            self.qgsattr.append(i)
    def ISOCase(filepath):
        """Method for extracting the boundingbox of an ISO19xxx standardized file

        @param filepath Full path to the ISO19xxx standardized file
        @returns a boundingbox as an array in a tuple in WGS84, formated like ([minLong, minLat, maxLong, maxLat], None)
        @see https://gis.stackexchange.com/questions/39080/using-ogr2ogr-to-convert-gml-to-shapefile-in-python
        """
        try:  # in case GDAL works
            ogr.UseExceptions()
            isofile = ogr.CreateGeometryFromGML(filepath)
            crs = isofile.GetSpatialRef()
            if crs.IsProjected() == 1:
                crs = int(crs.GetAttrValue("PROJCS|AUTHORITY", 1))
            elif crs.IsGeographic() == 1:
                crs = int(crs.GetAttrValue("GEOGCS|AUTHORITY", 1))
            else:
                return (None, "CRS is missing!")
            bbox = isofile.GetEnvelope()
            result = CRSTransform(bbox[1], bbox[0], crs)
            result.extend(CRSTransform(bbox[3], bbox[2], crs))
            ogr.DontUseExceptions()
            return (result, None)
        except:
            try:
                # convert the gml file to a GeoJSON file
                with tempfile.TemporaryDirectory() as tmpdirname:
                    curDir = os.getcwd()
                    os.chdir(tmpdirname)
                    ogr2ogr.main(
                        ["", "-f", "GeoJSON", "output.json", filepath])
                    # get boundingbox from generated GeoJSON file
                    result = ogr2ogrCase("output.json")
                    os.chdir(curDir)
                # delete generated GeoJSON file
                return result
            # errors
            except:
                return (None,
                        "file not found or your gml/xml/kml data is not valid")
Exemplo n.º 11
0
class ShapeWriter:
    '''A class for writing geometry and fields to ESRI shapefile format'''
    def __init__(self, shapefile, fields={}, srs_wkt=None, update=False):
        ''' Open the shapefile for writing or appending.

            @type shapefile:  C{gdal.Dataset}
            @param shapefile: Dataset object
            @type fields:     C{dict}
            @param fields:    L{Fields dict<formats.fields>}
            @type srs_wkt:    C{str}
            @param srs_wkt:   Spatial reference system WKT
            @type update:     C{boolean}
            @param update:    Update or overwrite existing shapefile

            @note: Field names can only be <= 10 characters long. Longer names will be silently truncated. This may result in non-unique column names, which will definitely cause problems later.
                   Field names can not contain spaces or special characters, except underscores.
                   Starting with version 1.7, the OGR Shapefile driver tries to generate unique field names. Successive duplicate field names, including those created by truncation to 10 characters, will be truncated to 8 characters and appended with a serial number from 1 to 99.

            @see: U{http://www.gdal.org/ogr/drv_shapefile.html}
        '''
        gdal.ErrorReset()
        ogr.UseExceptions()
        self._driver = ogr.GetDriverByName('ESRI Shapefile')
        self._srs = osr.SpatialReference()
        self._filename = shapefile
        self._fields = fields
        self._srs_wkt = srs_wkt
        self.fields = {
        }  #Dict to map full names to truncated names if name >10 chars
        try:
            if update and os.path.exists(shapefile):
                self._shape = self.__openshapefile__()
            else:
                self._shape = self.__createshapefile__()
        except Exception, err:
            self.__error__(err)
        ogr.DontUseExceptions()
Exemplo n.º 12
0
 def _create_base_map(self,):
     '''
     Deal with different types way to define the AOI, if none is specified, then the image bound is used.
     '''
     gdal.UseExceptions()
     ogr.UseExceptions() 
     if self.aoi is not None:
         if os.path.exists(self.aoi):
             try:     
                 g = gdal.Open(self.aoi)
                 #subprocess.call(['gdaltindex', '-f', 'GeoJSON',  '-t_srs', 'EPSG:4326', self.toa_dir + '/AOI.json', self.aoi])
                 geojson = get_boundary(self.aoi)[0]
                 with open(self.toa_dir + '/AOI.json', 'wb') as f:
                     f.write(geojson.encode())
             except:  
                 try: 
                     gr = ogr.Open(self.aoi)
                     l = gr.GetLayer(0)
                     f = l.GetFeature(0)
                     g = f.GetGeometryRef()                                                                                                
                 except:
                     raise IOError('AOI file cannot be opened by gdal, please check it or transform into format can be opened by gdal')
         else:        
             try:     
                 g = ogr.CreateGeometryFromJson(self.aoi)
             except:  
                 try: 
                     g = ogr.CreateGeometryFromGML(self.aoi)
                 except:
                     try:
                         g = ogr.CreateGeometryFromWkt(self.aoi)
                     except:
                         try:
                             g = ogr.CreateGeometryFromWkb(self.aoi)
                         except:
                             raise IOError('The AOI has to be one of GeoJSON, GML, Wkt or Wkb.')
         gjson_str = '''{"type":"FeatureCollection","features":[{"type":"Feature","properties":{},"geometry":%s}]}'''% g.ExportToJson()
         with open(self.toa_dir + '/AOI.json', 'wb') as f:
             f.write(gjson_str.encode())
     ogr.DontUseExceptions() 
     gdal.DontUseExceptions()
     if not os.path.exists(self.toa_dir + '/AOI.json'):
         #g = gdal.Open(self.toa_bands[0])
         #proj = g.GetProjection()
         #if 'WGS 84' in proj:
         #    subprocess.call(['gdaltindex', '-f', 'GeoJSON', self.toa_dir +'/AOI.json', self.toa_bands[0]])
         #else:
         #    subprocess.call(['gdaltindex', '-f', 'GeoJSON', '-t_srs', 'EPSG:4326', self.toa_dir +'/AOI.json', self.toa_bands[0]])
         if 'WGS 84' in proj:                                           
             #subprocess.call(['gdaltindex', '-f', 'GeoJSON', self.toa_dir +'/AOI.json', self.toa_bands[0]])
             geojson = get_boundary(self.toa_bands[0], to_wgs84 = False)                                                                                             
             with open(self.toa_dir + '/AOI.json', 'wb') as f:          
                 f.write(geojson.encode())                              
         else:                                                          
             #subprocess.call(['gdaltindex', '-f', 'GeoJSON', '-t_srs', 'EPSG:4326', self.toa_dir +'/AOI.json', self.toa_bands[0]])
             geojson = get_boundary(self.toa_bands[0])[0]               
             with open(self.toa_dir + '/AOI.json', 'wb') as f:          
                 f.write(geojson.encode()) 
         self.logger.warning('AOI is not created and full band extend is used')
         self.aoi = self.toa_dir + '/AOI.json'
     else:
         self.aoi = self.toa_dir + '/AOI.json'
Exemplo n.º 13
0
    def _create_base_map(self, ):
        """
        Deal with different types way to define the AOI, if none is specified, then the image bound is used.
        """
        gdal.UseExceptions()
        ogr.UseExceptions()
        if self.aoi is not None:
            if os.path.exists(self.aoi):
                try:
                    g = gdal.Open(self.aoi)
                    # subprocess.call(['gdaltindex', '-f', 'GeoJSON', '-t_srs', 'EPSG:4326', self.toa_dir + '/AOI.json', self.aoi])
                    geojson = get_boundary(self.aoi)[0]
                    with open(self.toa_dir + "/AOI.json", "wb") as f:
                        f.write(geojson.encode())
                except:
                    try:
                        gr = ogr.Open(str(self.aoi))
                        l = gr.GetLayer(0)
                        f = l.GetFeature(0)
                        g = f.GetGeometryRef()
                    except:
                        raise IOError(
                            "AOI file cannot be opened by gdal, please check it or transform into format can be opened by gdal"
                        )
            else:
                try:
                    g = ogr.CreateGeometryFromJson(self.aoi)
                except:
                    try:
                        g = ogr.CreateGeometryFromGML(self.aoi)
                    except:
                        try:
                            g = ogr.CreateGeometryFromWkt(self.aoi)
                        except:
                            try:
                                g = ogr.CreateGeometryFromWkb(self.aoi)
                            except:
                                raise IOError(
                                    "The AOI has to be one of GeoJSON, GML, Wkt or Wkb."
                                )
            gjson_str = (
                """{"type":"FeatureCollection","features":[{"type":"Feature","properties":{},"geometry":%s}]}"""
                % g.ExportToJson())
            with open(self.toa_dir + "/AOI.json", "wb") as f:
                f.write(gjson_str.encode())

        ogr.DontUseExceptions()
        gdal.DontUseExceptions()
        if not os.path.exists(self.toa_dir + "/AOI.json"):
            g = gdal.Open(self.toa_bands[0])
            proj = g.GetProjection()
            if "WGS 84" in proj:
                # subprocess.call(['gdaltindex', '-f', 'GeoJSON', self.toa_dir +'/AOI.json', self.toa_bands[0]])
                geojson = get_boundary(self.toa_bands[0], to_wgs84=False)
                with open(self.toa_dir + "/AOI.json", "wb") as f:
                    f.write(geojson.encode())
            else:
                # subprocess.call(['gdaltindex', '-f', 'GeoJSON', '-t_srs', 'EPSG:4326', self.toa_dir +'/AOI.json', self.toa_bands[0]])
                geojson = get_boundary(self.toa_bands[0])[0]
                with open(self.toa_dir + "/AOI.json", "wb") as f:
                    f.write(geojson.encode())

            self.logger.warning(
                "AOI is not created and full band extend is used")
            self.aoi = self.toa_dir + "/AOI.json"
        else:
            self.aoi = self.toa_dir + "/AOI.json"

        if self.pixel_res is None:
            self.pixel_res = abs(
                gdal.Open(self.toa_bands[0]).GetGeoTransform()[1])

        self.psf_xstd = 260 / self.pixel_res
        self.psf_ystd = 340 / self.pixel_res
Exemplo n.º 14
0
import os
import re
from osgeo import ogr
from .utils import InMemoryZip
from .utils import tempdir

ogr.DontUseExceptions()
ogr.UseExceptions()

GEOMETRY_TYPES = [
    'POINT', 'MULTIPOINT', 'LINESTRING', 'MULTILINESTRING', 'POLYGON',
    'MULTIPOLYGON', 'GEOMETRYCOLLECTION'
]


class ConvertError(Exception):
    pass


def ogr_layer_to_zip(ogr_layer,
                     vector_name='geometry',
                     driver_name='ESRI Shapefile'):
    driver = ogr.GetDriverByName(driver_name)
    if not driver:
        raise ConvertError('Unknown driver')

    with tempdir() as vector_dir:
        ds = driver.CreateDataSource(vector_dir, ['ENCODING=UTF-8'])
        splited_shape = False
        try:
            ds.CopyLayer(ogr_layer, vector_name, ['ENCODING=UTF-8'])