Ejemplo n.º 1
0
    def transform(self, ct, clone=False):
        """
        Requires GDAL. Transforms the geometry according to the given
        transformation object, which may be an integer SRID, and WKT or
        PROJ.4 string. By default, the geometry is transformed in-place and
        nothing is returned. However if the `clone` keyword is set, then this
        geometry will not be modified and a transformed clone will be returned
        instead.
        """
        srid = self.srid

        if ct == srid:
            # short-circuit where source & dest SRIDs match
            if clone:
                return self.clone()
            else:
                return

        if (srid is None) or (srid < 0):
            warnings.warn(
                "Calling transform() with no SRID set does no transformation!",
                stacklevel=2)
            warnings.warn(
                "Calling transform() with no SRID will raise GEOSException in v1.5",
                FutureWarning,
                stacklevel=2)
            return

        if not gdal.HAS_GDAL:
            raise GEOSException(
                "GDAL library is not available to transform() geometry.")

        # Creating an OGR Geometry, which is then transformed.
        g = gdal.OGRGeometry(self.wkb, srid)
        g.transform(ct)
        # Getting a new GEOS pointer
        ptr = wkb_r().read(g.wkb)
        if clone:
            # User wants a cloned transformed geometry returned.
            return GEOSGeometry(ptr, srid=g.srid)
        if ptr:
            # Reassigning pointer, and performing post-initialization setup
            # again due to the reassignment.
            capi.destroy_geom(self.ptr)
            self.ptr = ptr
            self._post_init(g.srid)
        else:
            raise GEOSException('Transformed WKB was invalid.')
Ejemplo n.º 2
0
def check_geom(result, func, cargs):
    "Error checking on routines that return Geometries."
    if not result:
        raise GEOSException(
            'Error encountered checking Geometry returned from GEOS C function "%s".'
            % func.__name__)
    return result
 def cascaded_union(self):
     "Returns a cascaded union of this MultiPolygon."
     if GEOS_PREPARE:
         return GEOSGeometry(capi.geos_cascaded_union(self.ptr), self.srid)
     else:
         raise GEOSException(
             'The cascaded union operation requires GEOS 3.1+.')
Ejemplo n.º 4
0
 def valid_reason(self):
     """
     Returns a string containing the reason for any invalidity.
     """
     if not GEOS_PREPARE:
         raise GEOSException('Upgrade GEOS to 3.1 to get validity reason.')
     return capi.geos_isvalidreason(self.ptr)
Ejemplo n.º 5
0
def check_minus_one(result, func, cargs):
    "Error checking on routines that should not return -1."
    if result == -1:
        raise GEOSException('Error encountered in GEOS C function "%s".' %
                            func.__name__)
    else:
        return result
Ejemplo n.º 6
0
 def _get_ptr(self):
     # Raise an exception if the pointer isn't valid don't
     # want to be passing NULL pointers to routines --
     # that's very bad.
     if self._ptr: return self._ptr
     else:
         raise GEOSException('NULL GEOS %s pointer encountered.' %
                             self.__class__.__name__)
Ejemplo n.º 7
0
 def relate_pattern(self, other, pattern):
     """
     Returns true if the elements in the DE-9IM intersection matrix for the
     two Geometries match the elements in pattern.
     """
     if not isinstance(pattern, basestring) or len(pattern) > 9:
         raise GEOSException('invalid intersection matrix pattern')
     return capi.geos_relatepattern(self.ptr, other.ptr, pattern)
Ejemplo n.º 8
0
 def __setstate__(self, state):
     # Instantiating from the tuple state that was pickled.
     wkb, srid = state
     ptr = wkb_r().read(buffer(wkb))
     if not ptr:
         raise GEOSException('Invalid Geometry loaded from pickled state.')
     self.ptr = ptr
     self._post_init(srid)
Ejemplo n.º 9
0
 def ogr(self):
     "Returns the OGR Geometry for this Geometry."
     if gdal.HAS_GDAL:
         if self.srid:
             return gdal.OGRGeometry(self.wkb, self.srid)
         else:
             return gdal.OGRGeometry(self.wkb)
     else:
         raise GEOSException('GDAL required to convert to an OGRGeometry.')
Ejemplo n.º 10
0
 def json(self):
     """
     Returns GeoJSON representation of this Geometry if GDAL 1.5+
     is installed.
     """
     if gdal.GEOJSON:
         return self.ogr.json
     else:
         raise GEOSException('GeoJSON output only supported on GDAL 1.5+.')
Ejemplo n.º 11
0
    def __init__(self, geo_input, srid=None):
        """
        The base constructor for GEOS geometry objects, and may take the
        following inputs:

         * strings:
            - WKT
            - HEXEWKB (a PostGIS-specific canonical form)
            - GeoJSON (requires GDAL)
         * buffer:
            - WKB

        The `srid` keyword is used to specify the Source Reference Identifier
        (SRID) number for this Geometry.  If not set, the SRID will be None.
        """
        if isinstance(geo_input, basestring):
            if isinstance(geo_input, unicode):
                # Encoding to ASCII, WKT or HEXEWKB doesn't need any more.
                geo_input = geo_input.encode('ascii')

            wkt_m = wkt_regex.match(geo_input)
            if wkt_m:
                # Handling WKT input.
                if wkt_m.group('srid'): srid = int(wkt_m.group('srid'))
                g = wkt_r().read(wkt_m.group('wkt'))
            elif hex_regex.match(geo_input):
                # Handling HEXEWKB input.
                g = wkb_r().read(geo_input)
            elif gdal.GEOJSON and json_regex.match(geo_input):
                # Handling GeoJSON input.
                g = wkb_r().read(gdal.OGRGeometry(geo_input).wkb)
            else:
                raise ValueError(
                    'String or unicode input unrecognized as WKT EWKT, and HEXEWKB.'
                )
        elif isinstance(geo_input, GEOM_PTR):
            # When the input is a pointer to a geomtry (GEOM_PTR).
            g = geo_input
        elif isinstance(geo_input, buffer):
            # When the input is a buffer (WKB).
            g = wkb_r().read(geo_input)
        elif isinstance(geo_input, GEOSGeometry):
            g = capi.geom_clone(geo_input.ptr)
        else:
            # Invalid geometry type.
            raise TypeError('Improper geometry input type: %s' %
                            str(type(geo_input)))

        if bool(g):
            # Setting the pointer object with a valid pointer.
            self.ptr = g
        else:
            raise GEOSException(
                'Could not initialize GEOS Geometry with given input.')

        # Post-initialization setup.
        self._post_init(srid)
Ejemplo n.º 12
0
def check_predicate(result, func, cargs):
    "Error checking for unary/binary predicate functions."
    val = ord(result)  # getting the ordinal from the character
    if val == 1: return True
    elif val == 0: return False
    else:
        raise GEOSException(
            'Error encountered on GEOS C predicate function "%s".' %
            func.__name__)
Ejemplo n.º 13
0
 def prepared(self):
     """
     Returns a PreparedGeometry corresponding to this geometry -- it is
     optimized for the contains, intersects, and covers operations.
     """
     if GEOS_PREPARE:
         return PreparedGeometry(self)
     else:
         raise GEOSException(
             'GEOS 3.1+ required for prepared geometry support.')
Ejemplo n.º 14
0
 def srs(self):
     "Returns the OSR SpatialReference for SRID of this Geometry."
     if gdal.HAS_GDAL:
         if self.srid:
             return gdal.SpatialReference(self.srid)
         else:
             return None
     else:
         raise GEOSException(
             'GDAL required to return a SpatialReference object.')
 def _set_list(self, length, items):
     ptr = self._create_point(length, items)
     if ptr:
         capi.destroy_geom(self.ptr)
         self._ptr = ptr
         self._set_cs()
     else:
         # can this happen?
         raise GEOSException(
             'Geometry resulting from slice deletion was invalid.')
def geos_version_info():
    """
    Returns a dictionary containing the various version metadata parsed from
    the GEOS version string, including the version number, whether the version
    is a release candidate (and what number release candidate), and the C API
    version.
    """
    ver = geos_version()
    m = version_regex.match(ver)
    if not m:
        raise GEOSException('Could not parse version info string "%s"' % ver)
    return dict((key, m.group(key))
                for key in ('version', 'release_candidate', 'capi_version',
                            'major', 'minor', 'subminor'))
Ejemplo n.º 17
0
 def hexewkb(self):
     """
     Returns the EWKB of this Geometry in hexadecimal form.  This is an
     extension of the WKB specification that includes SRID and Z values
     that are a part of this geometry.
     """
     if self.hasz:
         if not GEOS_PREPARE:
             # See: http://trac.osgeo.org/geos/ticket/216
             raise GEOSException(
                 'Upgrade GEOS to 3.1 to get valid 3D HEXEWKB.')
         return ewkb_w3d().write_hex(self)
     else:
         return ewkb_w().write_hex(self)
Ejemplo n.º 18
0
 def ewkb(self):
     """
     Return the EWKB representation of this Geometry as a Python buffer.
     This is an extension of the WKB specification that includes any SRID
     and Z values that are a part of this geometry.
     """
     if self.hasz:
         if not GEOS_PREPARE:
             # See: http://trac.osgeo.org/geos/ticket/216
             raise GEOSException(
                 'Upgrade GEOS to 3.1 to get valid 3D EWKB.')
         return ewkb_w3d().write(self)
     else:
         return ewkb_w().write(self)
Ejemplo n.º 19
0
def check_string(result, func, cargs):
    """
    Error checking for routines that return strings.

    This frees the memory allocated by GEOS at the result pointer.
    """
    if not result:
        raise GEOSException(
            'Error encountered checking string return value in GEOS C function "%s".'
            % func.__name__)
    # Getting the string value at the pointer address.
    s = string_at(result)
    # Freeing the memory allocated within GEOS
    free(result)
    return s
Ejemplo n.º 20
0
def check_sized_string(result, func, cargs):
    """
    Error checking for routines that return explicitly sized strings.

    This frees the memory allocated by GEOS at the result pointer.
    """
    if not result:
        raise GEOSException(
            'Invalid string pointer returned by GEOS C function "%s"' %
            func.__name__)
    # A c_size_t object is passed in by reference for the second
    # argument on these routines, and its needed to determine the
    # correct size.
    s = string_at(result, last_arg_byref(cargs))
    # Freeing the memory allocated within GEOS
    free(result)
    return s
Ejemplo n.º 21
0
    def _set_list(self, length, items):
        ndim = self._cs.dims  #
        hasz = self._cs.hasz  # I don't understand why these are different

        # create a new coordinate sequence and populate accordingly
        cs = GEOSCoordSeq(capi.create_cs(length, ndim), z=hasz)
        for i, c in enumerate(items):
            cs[i] = c

        ptr = self._init_func(cs.ptr)
        if ptr:
            capi.destroy_geom(self.ptr)
            self.ptr = ptr
            self._post_init(self.srid)
        else:
            # can this happen?
            raise GEOSException(
                'Geometry resulting from slice deletion was invalid.')
 def _checkdim(self, dim):
     "Checks the given dimension."
     if dim < 0 or dim > 2:
         raise GEOSException('invalid ordinate dimension "%d"' % dim)
 def set_z(self, value):
     "Sets the Z component of the Point."
     if self.hasz:
         self._cs.setOrdinate(2, 0, value)
     else:
         raise GEOSException('Cannot set Z on 2D Point.')