Пример #1
0
    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(map(float, 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.')
Пример #2
0
    def __init__(self, dr_input):
        "Initializes an OGR driver on either a string or integer input."

        if isinstance(dr_input, basestring):
            # 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(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
Пример #3
0
    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, basestring):
            # 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(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)
Пример #4
0
 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
Пример #5
0
 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]))
Пример #6
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 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]
Пример #8
0
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 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, 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):
            type_input = type_input.lower()
            if type_input == 'geometry': type_input = 'unknown'
            num = self._str_types.get(type_input, 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
Пример #11
0
 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, basestring):
         tmp = OGRGeometry(geom)
         capi.add_geom(self.ptr, tmp.ptr)
     else:
         raise OGRException('Must add an OGRGeometry.')
Пример #12
0
 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 __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('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
            self._double = True
Пример #15
0
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')])
Пример #16
0
try:
    from my_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 libraries
    lib_names = ['gdal18', 'gdal17', 'gdal16', 'gdal15']
elif os.name == 'posix':
    # *NIX library names.
    lib_names = ['gdal', 'GDAL', 'gdal1.8.0', 'gdal1.7.0', 'gdal1.6.0', 'gdal1.5.0', 'gdal1.4.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)
Пример #17
0
    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('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'))))
                else:
                    g = capi.from_wkt(byref(c_char_p(wkt_m.group('wkt'))), 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]
Пример #18
0
 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