def __init__(self, *args): """ The initialization function may take an OGREnvelope structure, 4-element tuple or list, or 4 individual arguments. """ if len(args) == 1: if isinstance(args[0], OGREnvelope): # OGREnvelope (a ctypes Structure) was passed in. self._envelope = args[0] elif isinstance(args[0], (tuple, list)): # A tuple was passed in. if len(args[0]) != 4: raise OGRException('Incorrect number of tuple elements (%d).' % len(args[0])) else: self._from_sequence(args[0]) else: raise TypeError('Incorrect type of argument: %s' % str(type(args[0]))) elif len(args) == 4: # Individual parameters passed in. # Thanks to ww for the help self._from_sequence([float(a) for a in args]) else: raise OGRException('Incorrect number (%d) of arguments.' % len(args)) # Checking the x,y coordinates if self.min_x > self.max_x: raise OGRException('Envelope minimum X > maximum X.') if self.min_y > self.max_y: raise OGRException('Envelope minimum Y > maximum Y.')
def __init__(self, ds_input, ds_driver=False, write=False, encoding='utf-8'): # The write flag. if write: self._write = 1 else: self._write = 0 # See also http://trac.osgeo.org/gdal/wiki/rfc23_ogr_unicode self.encoding = encoding Driver.ensure_registered() if isinstance(ds_input, six.string_types): # The data source driver is a void pointer. ds_driver = Driver.ptr_type() try: # OGROpen will auto-detect the data source type. ds = capi.open_ds(force_bytes(ds_input), self._write, byref(ds_driver)) except OGRException: # Making the error message more clear rather than something # like "Invalid pointer returned from OGROpen". raise OGRException('Could not open the datasource at "%s"' % ds_input) elif isinstance(ds_input, self.ptr_type) and isinstance(ds_driver, Driver.ptr_type): ds = ds_input else: raise OGRException('Invalid data source input type: %s' % type(ds_input)) if ds: self.ptr = ds self.driver = Driver(ds_driver) else: # Raise an exception if the returned pointer is NULL raise OGRException('Invalid data source file "%s"' % ds_input)
def __init__(self, dr_input): "Initializes an OGR driver on either a string or integer input." if isinstance(dr_input, six.string_types): # If a string name of the driver was passed in self._register() # Checking the alias dictionary (case-insensitive) to see if an alias # exists for the given driver. if dr_input.lower() in self._alias: name = self._alias[dr_input.lower()] else: name = dr_input # Attempting to get the OGR driver by the string name. dr = capi.get_driver_by_name(force_bytes(name)) elif isinstance(dr_input, int): self._register() dr = capi.get_driver(dr_input) elif isinstance(dr_input, c_void_p): dr = dr_input else: raise OGRException('Unrecognized input type for OGR Driver: %s' % str(type(dr_input))) # Making sure we get a valid pointer to the OGR Driver if not dr: raise OGRException('Could not initialize OGR Driver on input: %s' % str(dr_input)) self.ptr = dr
def __init__(self, ds_input, ds_driver=False, write=False): # The write flag. if write: self._write = 1 else: self._write = 0 # Registering all the drivers, this needs to be done # _before_ we try to open up a data source. if not capi.get_driver_count(): capi.register_all() if isinstance(ds_input, six.string_types): # The data source driver is a void pointer. ds_driver = Driver.ptr_type() try: # OGROpen will auto-detect the data source type. ds = capi.open_ds(force_bytes(ds_input), self._write, byref(ds_driver)) except OGRException: # Making the error message more clear rather than something # like "Invalid pointer returned from OGROpen". raise OGRException('Could not open the datasource at "%s"' % ds_input) elif isinstance(ds_input, self.ptr_type) and isinstance(ds_driver, Driver.ptr_type): ds = ds_input else: raise OGRException('Invalid data source input type: %s' % type(ds_input)) if bool(ds): self.ptr = ds self.driver = Driver(ds_driver) else: # Raise an exception if the returned pointer is NULL raise OGRException('Invalid data source file "%s"' % ds_input)
def output_mapinfo(self): drv_name = "MapInfo File" drv = ogr.GetDriverByName(drv_name) if drv is None: raise OGRException("%s driver not available" % drv) if not options['output']: raise Exception("Must supply output filename") ds = drv.CreateDataSource(options['output']) if ds is None: raise OGRException("Failed to output to '%s'" % options['output']) srs = osr.SpatialReference() check_err(srs.SetFromUserInput(TARGET_CRS)) lyr = ds.CreateLayer('paatos', srs, ogr.wkbPoint) if lyr is None: raise OGRException("Layer creation failed") field_def = ogr.FieldDefn("diaarinro", ogr.OFTString) field_def.SetWidth(20) check_err(lyr.CreateField(field_def)) field_def = ogr.FieldDefn("otsikko", ogr.OFTString) field_def.SetWidth(100) check_err(lyr.CreateField(field_def)) field_def = ogr.FieldDefn("openahjo", ogr.OFTString) field_def.SetWidth(100) check_err(lyr.CreateField(field_def)) issue_list = Issue.objects.filter(geometries__isnull=False) for issue in issue_list: print issue geom_list = issue.geometries.all() pnt = None for geom in geom_list: g = geom.geometry if not isinstance(g, Point): pnt = g.centroid else: pnt = g break pnt.transform(TARGET_CRS) feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetField("diaarinro", issue.register_id.encode('utf8')) feat.SetField("otsikko", issue.subject.encode('utf8')) feat.SetField( "openahjo", "http://dev.hel.fi/paatokset/asia/%s/" % issue.slug.encode('utf8')) pt = ogr.Geometry(ogr.wkbPoint) pt.SetPoint_2D(0, pnt.x, pnt.y) feat.SetGeometry(pt) check_err(lyr.CreateFeature(feat)) feat.Destroy()
def __init__(self, geom_input, srs=None): "Initializes Geometry on either WKT or an OGR pointer as input." str_instance = isinstance(geom_input, six.string_types) # If HEX, unpack input to a binary buffer. if str_instance and hex_regex.match(geom_input): geom_input = memoryview(a2b_hex(geom_input.upper().encode())) str_instance = False # Constructing the geometry, if str_instance: wkt_m = wkt_regex.match(geom_input) json_m = json_regex.match(geom_input) if wkt_m: if wkt_m.group('srid'): # If there's EWKT, set the SRS w/value of the SRID. srs = int(wkt_m.group('srid')) if wkt_m.group('type').upper() == 'LINEARRING': # OGR_G_CreateFromWkt doesn't work with LINEARRING WKT. # See http://trac.osgeo.org/gdal/ticket/1992. g = capi.create_geom(OGRGeomType(wkt_m.group('type')).num) capi.import_wkt(g, byref(c_char_p(wkt_m.group('wkt').encode()))) else: g = capi.from_wkt(byref(c_char_p(wkt_m.group('wkt').encode())), None, byref(c_void_p())) elif json_m: g = capi.from_json(geom_input.encode()) else: # Seeing if the input is a valid short-hand string # (e.g., 'Point', 'POLYGON'). ogr_t = OGRGeomType(geom_input) g = capi.create_geom(OGRGeomType(geom_input).num) elif isinstance(geom_input, memoryview): # WKB was passed in g = capi.from_wkb(bytes(geom_input), None, byref(c_void_p()), len(geom_input)) elif isinstance(geom_input, OGRGeomType): # OGRGeomType was passed in, an empty geometry will be created. g = capi.create_geom(geom_input.num) elif isinstance(geom_input, self.ptr_type): # OGR pointer (c_void_p) was the input. g = geom_input else: raise OGRException('Invalid input type for OGR Geometry construction: %s' % type(geom_input)) # Now checking the Geometry pointer before finishing initialization # by setting the pointer for the object. if not g: raise OGRException('Cannot create OGR Geometry from input: %s' % str(geom_input)) self.ptr = g # Assigning the SpatialReference object to the geometry, if valid. if bool(srs): self.srs = srs # Setting the class depending upon the OGR Geometry Type self.__class__ = GEO_CLASSES[self.geom_type.num]
def __init__(self, type_input): "Figures out the correct OGR Type based upon the input." if isinstance(type_input, OGRGeomType): self._index = type_input._index elif isinstance(type_input, basestring): idx = self._has_str(self.__ogr_str, type_input) if idx == None: raise OGRException('Invalid OGR String Type "%s"' % type_input) self._index = idx elif isinstance(type_input, int): if not type_input in self.__ogr_int: raise OGRException('Invalid OGR Integer Type: %d' % type_input) self._index = self.__ogr_int.index(type_input) else: raise TypeError('Invalid OGR input type given.')
def __init__(self, layer_ptr): "Needs a C pointer (Python/ctypes integer) in order to initialize." self._ptr = None # Initially NULL if not layer_ptr: raise OGRException('Cannot create Layer, invalid pointer given') self._ptr = layer_ptr self._ldefn = get_layer_defn(self._ptr)
def gdal_version_info(): ver = gdal_version() m = version_regex.match(ver) if not m: raise OGRException('Could not parse GDAL version string "%s"' % ver) return dict([(key, m.group(key)) for key in ('major', 'minor', 'subminor')])
def __init__(self, feat, fdefn): "Initializes on the pointers for the feature and the layer definition." if not feat or not fdefn: raise OGRException( 'Cannot create OGR Feature, invalid pointer given.') self.ptr = feat self._fdefn = fdefn
def expand_to_include(self, *args): """ Modifies the envelope to expand to include the boundaries of the passed-in 2-tuple (a point), 4-tuple (an extent) or envelope. """ # We provide a number of different signatures for this method, # and the logic here is all about converting them into a # 4-tuple single parameter which does the actual work of # expanding the envelope. if len(args) == 1: if isinstance(args[0], Envelope): return self.expand_to_include(args[0].tuple) elif hasattr(args[0], 'x') and hasattr(args[0], 'y'): return self.expand_to_include(args[0].x, args[0].y, args[0].x, args[0].y) elif isinstance(args[0], (tuple, list)): # A tuple was passed in. if len(args[0]) == 2: return self.expand_to_include( (args[0][0], args[0][1], args[0][0], args[0][1])) elif len(args[0]) == 4: (minx, miny, maxx, maxy) = args[0] if minx < self._envelope.MinX: self._envelope.MinX = minx if miny < self._envelope.MinY: self._envelope.MinY = miny if maxx > self._envelope.MaxX: self._envelope.MaxX = maxx if maxy > self._envelope.MaxY: self._envelope.MaxY = maxy else: raise OGRException( 'Incorrect number of tuple elements (%d).' % len(args[0])) else: raise TypeError('Incorrect type of argument: %s' % str(type(args[0]))) elif len(args) == 2: # An x and an y parameter were passed in return self.expand_to_include((args[0], args[1], args[0], args[1])) elif len(args) == 4: # Individual parameters passed in. return self.expand_to_include(args) else: raise OGRException('Incorrect number (%d) of arguments.' % len(args[0]))
def check_pointer(result, func, cargs): "Makes sure the result pointer is valid." if isinstance(result, (int, long)): result = c_void_p(result) if bool(result): return result else: raise OGRException('Invalid pointer returned from "%s"' % func.__name__)
def __init__(self, type_input): "Figures out the correct OGR Type based upon the input." if isinstance(type_input, OGRGeomType): num = type_input.num elif isinstance(type_input, basestring): num = self._str_types.get(type_input.lower(), None) if num is None: raise OGRException('Invalid OGR String Type "%s"' % type_input) elif isinstance(type_input, int): if not type_input in self._types: raise OGRException('Invalid OGR Integer Type: %d' % type_input) num = type_input else: raise TypeError('Invalid OGR input type given.') # Setting the OGR geometry type number. self.num = num
def check_pointer(result, func, cargs): "Makes sure the result pointer is valid." if isinstance(result, six.integer_types): result = c_void_p(result) if result: return result else: raise OGRException('Invalid pointer returned from "%s"' % func.__name__)
def get_fields(self, field_name): """ Returns a list containing the given field name for every Feature in the Layer. """ if not field_name in self.fields: raise OGRException('invalid field name: %s' % field_name) return [feat.get(field_name) for feat in self]
def __setstate__(self, state): wkb, srs = state ptr = capi.from_wkb(wkb, None, byref(c_void_p()), len(wkb)) if not ptr: raise OGRException( 'Invalid OGRGeometry loaded from pickled state.') self.ptr = ptr self.srs = srs
def as_datetime(self): "Retrieves the Field's value as a tuple of date & time components." yy, mm, dd, hh, mn, ss, tz = [c_int() for i in range(7)] status = capi.get_field_as_datetime(self._feat, self._index, byref(yy), byref(mm), byref(dd), byref(hh), byref(mn), byref(ss), byref(tz)) if status: return (yy, mm, dd, hh, mn, ss, tz) else: raise OGRException('Unable to retrieve date & time information from the field.')
def __init__(self, layer_ptr): "Needs a C pointer (Python/ctypes integer) in order to initialize." self._ptr = None # Initially NULL if not layer_ptr: raise OGRException('Cannot create Layer, invalid pointer given') self._ptr = layer_ptr self._ldefn = get_layer_defn(self._ptr) # Does the Layer support random reading? self._random_read = self.test_capability('RandomRead')
def __init__(self, feat, layer): """ Initializes Feature from a pointer and its Layer object. """ if not feat: raise OGRException( 'Cannot create OGR Feature, invalid pointer given.') self.ptr = feat self._layer = layer
def check_geom(result, func, cargs): "Checks a function that returns a geometry." # OGR_G_Clone may return an integer, even though the # restype is set to c_void_p if isinstance(result, (int, long)): result = c_void_p(result) if not result: raise OGRException('Invalid geometry pointer returned from "%s".' % func.__name__) return result
def add(self, geom): "Add the geometry to this Geometry Collection." if isinstance(geom, OGRGeometry): if isinstance(geom, self.__class__): for g in geom: capi.add_geom(self.ptr, g.ptr) else: capi.add_geom(self.ptr, geom.ptr) elif isinstance(geom, six.string_types): tmp = OGRGeometry(geom) capi.add_geom(self.ptr, tmp.ptr) else: raise OGRException('Must add an OGRGeometry.')
def __eq__(self, other): """ Returns True if the envelopes are equivalent; can compare against other Envelopes and 4-tuples. """ if isinstance(other, Envelope): return (self.min_x == other.min_x) and (self.min_y == other.min_y) and \ (self.max_x == other.max_x) and (self.max_y == other.max_y) elif isinstance(other, tuple) and len(other) == 4: return (self.min_x == other[0]) and (self.min_y == other[1]) and \ (self.max_x == other[2]) and (self.max_y == other[3]) else: raise OGRException('Equivalence testing only works with other Envelopes.')
def add(self, geom): "Add the geometry to this Geometry Collection." if isinstance(geom, OGRGeometry): if isinstance(geom, self.__class__): for g in geom: add_geom(self._ptr, g._ptr) else: add_geom(self._ptr, geom._ptr) elif isinstance(geom, basestring): tmp = OGRGeometry(geom) add_geom(self._ptr, tmp._ptr) else: raise OGRException('Must add an OGRGeometry.')
def __init__(self, layer_ptr, ds): """ Initializes on an OGR C pointer to the Layer and the `DataSource` object that owns this layer. The `DataSource` object is required so that a reference to it is kept with this Layer. This prevents garbage collection of the `DataSource` while this Layer is still active. """ if not layer_ptr: raise OGRException('Cannot create Layer, invalid pointer given') self.ptr = layer_ptr self._ds = ds self._ldefn = capi.get_layer_defn(self._ptr) # Does the Layer support random reading? self._random_read = self.test_capability(b'RandomRead')
def __init__(self, feat, index): """ Initializes on the feature pointer and the integer index of the field within the feature. """ # Setting the feature pointer and index. self._feat = feat self._index = index # Getting the pointer for this field. fld_ptr = capi.get_feat_field_defn(feat, index) if not fld_ptr: raise OGRException('Cannot create OGR Field, invalid pointer given.') self.ptr = fld_ptr # Setting the class depending upon the OGR Field Type (OFT) self.__class__ = OGRFieldTypes[self.type] # OFTReal with no precision should be an OFTInteger. if isinstance(self, OFTReal) and self.precision == 0: self.__class__ = OFTInteger
def __init__(self, geom_input, srs=None): "Initializes Geometry on either WKT or an OGR pointer as input." str_instance = isinstance(geom_input, basestring) # If HEX, unpack input to to a binary buffer. if str_instance and hex_regex.match(geom_input): geom_input = buffer(a2b_hex(geom_input.upper())) str_instance = False # Constructing the geometry, if str_instance: # Checking if unicode if isinstance(geom_input, unicode): # Encoding to ASCII, WKT or HEX doesn't need any more. geom_input = geom_input.encode('ascii') wkt_m = wkt_regex.match(geom_input) json_m = json_regex.match(geom_input) if wkt_m: if wkt_m.group('type').upper() == 'LINEARRING': # OGR_G_CreateFromWkt doesn't work with LINEARRING WKT. # See http://trac.osgeo.org/gdal/ticket/1992. g = capi.create_geom(OGRGeomType(wkt_m.group('type')).num) capi.import_wkt(g, byref(c_char_p(geom_input))) else: g = capi.from_wkt(byref(c_char_p(geom_input)), None, byref(c_void_p())) elif json_m: if GEOJSON: g = capi.from_json(geom_input) else: raise NotImplementedError( 'GeoJSON input only supported on GDAL 1.5+.') else: # Seeing if the input is a valid short-hand string # (e.g., 'Point', 'POLYGON'). ogr_t = OGRGeomType(geom_input) g = capi.create_geom(OGRGeomType(geom_input).num) elif isinstance(geom_input, buffer): # WKB was passed in g = capi.from_wkb(str(geom_input), None, byref(c_void_p()), len(geom_input)) elif isinstance(geom_input, OGRGeomType): # OGRGeomType was passed in, an empty geometry will be created. g = capi.create_geom(geom_input.num) elif isinstance(geom_input, self.ptr_type): # OGR pointer (c_void_p) was the input. g = geom_input else: raise OGRException( 'Invalid input type for OGR Geometry construction: %s' % type(geom_input)) # Now checking the Geometry pointer before finishing initialization # by setting the pointer for the object. if not g: raise OGRException('Cannot create OGR Geometry from input: %s' % str(geom_input)) self.ptr = g # Assigning the SpatialReference object to the geometry, if valid. if bool(srs): self.srs = srs # Setting the class depending upon the OGR Geometry Type self.__class__ = GEO_CLASSES[self.geom_type.num]
if lib_name: pass elif os.name == 'nt': # Windows NT shared library lib_name = 'gdal15.dll' elif os.name == 'posix': platform = os.uname()[0] if platform == 'Darwin': # Mac OSX shared library lib_name = 'libgdal.dylib' else: # Attempting to use .so extension for all other platforms. lib_name = 'libgdal.so' else: raise OGRException('Unsupported OS "%s"' % os.name) # This loads the GDAL/OGR C library lgdal = CDLL(lib_name) # On Windows, the GDAL binaries have some OSR routines exported with # STDCALL, while others are not. Thus, the library will also need to # be loaded up as WinDLL for said OSR functions that require the # different calling convention. if os.name == 'nt': from ctypes import WinDLL lwingdal = WinDLL(lib_name) def std_call(func): """ Returns the correct STDCALL function for certain OSR routines on Win32
try: from django.conf import settings lib_path = settings.GDAL_LIBRARY_PATH except (AttributeError, EnvironmentError, ImportError): lib_path = None if lib_path: lib_names = None elif os.name == 'nt': # Windows NT shared library lib_names = ['gdal15'] elif os.name == 'posix': # *NIX library names. lib_names = ['gdal', 'gdal1.5.0'] else: raise OGRException('Unsupported OS "%s"' % os.name) # Using the ctypes `find_library` utility to find the # path to the GDAL library from the list of library names. if lib_names: for lib_name in lib_names: lib_path = find_library(lib_name) if not lib_path is None: break if lib_path is None: raise OGRException('Could not find the GDAL library (tried "%s"). ' 'Try setting GDAL_LIBRARY_PATH in your settings.' % '", "'.join(lib_names)) # This loads the GDAL/OGR C library lgdal = CDLL(lib_path)
def check_pointer(result, func, cargs): "Makes sure the result pointer is valid." if bool(result): return result else: raise OGRException('Invalid pointer returned from "%s"' % func.__name__)