django.contrib.gis.geos.GEOSGeometry

Here are the examples of the python api django.contrib.gis.geos.GEOSGeometry taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: django-etl-sync
Source File: generators.py
View license
    def _prepare_geometry(self, field, value):
        """
        Reduce geometry to two dimensions if models. GeometryField
        dim parameter is not set otherwise.
        """
        from django.contrib.gis.geos import WKBWriter, GEOSGeometry
        if isinstance(value, (str, text_type)):
            value = GEOSGeometry(value)
        wkb_writer = WKBWriter()
        if isinstance(value, GEOSGeometry):
            if value.hasz and field.dim == 2:
                value = GEOSGeometry(wkb_writer.write(value))
        return value

Example 2

Project: PyClassLessons
Source File: tests.py
View license
    def _load_interstate_data(self):
        # Interstate (2D / 3D and Geographic/Projected variants)
        for name, line, exp_z in interstate_data:
            line_3d = GEOSGeometry(line, srid=4269)
            line_2d = LineString([l[:2] for l in line_3d.coords], srid=4269)

            # Creating a geographic and projected version of the
            # interstate in both 2D and 3D.
            Interstate3D.objects.create(name=name, line=line_3d)
            InterstateProj3D.objects.create(name=name, line=line_3d)
            Interstate2D.objects.create(name=name, line=line_2d)
            InterstateProj2D.objects.create(name=name, line=line_2d)

Example 3

Project: PyClassLessons
Source File: tests.py
View license
    def _load_polygon_data(self):
        bbox_wkt, bbox_z = bbox_data
        bbox_2d = GEOSGeometry(bbox_wkt, srid=32140)
        bbox_3d = Polygon(tuple((x, y, z) for (x, y), z in zip(bbox_2d[0].coords, bbox_z)), srid=32140)
        Polygon2D.objects.create(name='2D BBox', poly=bbox_2d)
        Polygon3D.objects.create(name='3D BBox', poly=bbox_3d)

Example 4

Project: Django--an-app-at-a-time
Source File: widgets.py
View license
    def deserialize(self, value):
        try:
            return GEOSGeometry(value, self.map_srid)
        except (GEOSException, ValueError) as err:
            logger.error(
                "Error creating geometry from value '%s' (%s)" % (
                    value, err)
            )
        return None

Example 5

Project: Django--an-app-at-a-time
Source File: layer.py
View license
    def get_geoms(self, geos=False):
        """
        Returns a list containing the OGRGeometry for every Feature in
        the Layer.
        """
        if geos:
            from django.contrib.gis.geos import GEOSGeometry
            return [GEOSGeometry(feat.geom.wkb) for feat in self]
        else:
            return [feat.geom for feat in self]

Example 6

Project: splunk-webframework
Source File: test_geos.py
View license
    def test_create_hex(self):
        "Testing creation from HEX."
        for g in self.geometries.hex_wkt:
            geom_h = GEOSGeometry(g.hex)
            # we need to do this so decimal places get normalised
            geom_t = fromstr(g.wkt)
            self.assertEqual(geom_t.wkt, geom_h.wkt)

Example 7

Project: splunk-webframework
Source File: test_geos.py
View license
    def test_create_wkb(self):
        "Testing creation from WKB."
        for g in self.geometries.hex_wkt:
            wkb = memoryview(a2b_hex(g.hex.encode()))
            geom_h = GEOSGeometry(wkb)
            # we need to do this so decimal places get normalised
            geom_t = fromstr(g.wkt)
            self.assertEqual(geom_t.wkt, geom_h.wkt)

Example 8

Project: splunk-webframework
Source File: test_geos.py
View license
    @unittest.skipUnless(gdal.HAS_GDAL, "gdal is required")
    def test_json(self):
        "Testing GeoJSON input/output (via GDAL)."
        for g in self.geometries.json_geoms:
            geom = GEOSGeometry(g.wkt)
            if not hasattr(g, 'not_equal'):
                # Loading jsons to prevent decimal differences
                self.assertEqual(json.loads(g.json), json.loads(geom.json))
                self.assertEqual(json.loads(g.json), json.loads(geom.geojson))
            self.assertEqual(GEOSGeometry(g.wkt), GEOSGeometry(geom.json))

Example 9

Project: splunk-webframework
Source File: test_geos.py
View license
    def test_fromfile(self):
        "Testing the fromfile() factory."
        ref_pnt = GEOSGeometry('POINT(5 23)')

        wkt_f = BytesIO()
        wkt_f.write(force_bytes(ref_pnt.wkt))
        wkb_f = BytesIO()
        wkb_f.write(bytes(ref_pnt.wkb))

        # Other tests use `fromfile()` on string filenames so those
        # aren't tested here.
        for fh in (wkt_f, wkb_f):
            fh.seek(0)
            pnt = fromfile(fh)
            self.assertEqual(ref_pnt, pnt)

Example 10

Project: wq.db
Source File: serializers.py
View license
    def to_internal_value(self, value):
        import json
        if isinstance(value, dict):
            value = json.dumps(value)
        geom = GEOSGeometry(value)
        srid = getattr(settings, 'SRID', 4326)

        if 'crs' in value and value['crs'].get('type', None) == 'name':
            name = value['crs']['properties']['name']
            if name.startswith('urn:ogc:def:crs:EPSG::'):
                geom.srid = int(name.replace('urn:ogc:def:crs:EPSG::', ''))

        if geom.srid is None:
            geom.srid = 4326
        if geom.srid != srid:
            geom.transform(srid)
        return geom

Example 11

Project: anycluster
Source File: MapTools.py
View license
    def getClusterCellsAsPolyList(self, toprightCellID, bottomleftCellID, zoom, gridSize, srid):

        cells_as_poly = []
        
        cells_as_keys = self.getClusterCells(toprightCellID, bottomleftCellID, zoom)

        for cell in cells_as_keys:
            poly_string = self.clusterCellToBounds(cell, zoom, gridSize, srid)
            poly = GEOSGeometry(poly_string, srid=srid)
            cells_as_poly.append(poly)

        return cells_as_poly

Example 12

Project: anycluster
Source File: MapTools.py
View license
    def getCellForPointAsGeos(self, point, zoom, gridSize, srid):
        point = point.clone()
        cell_id = self.getCellIDForPoint(point, zoom, gridSize)
        poly_string = self.clusterCellToBounds(cell_id, zoom, gridSize, srid)
        poly = GEOSGeometry(poly_string, srid=srid)

        return poly

Example 13

Project: prometapi
Source File: models.py
View license
def _transform_dataset(original_data):
    data = _loads(original_data)
    geotransform = get_coordtransform()
    for pr in data:
        si_point = GEOSGeometry('SRID=3787;POINT (%s %s)' % (pr['x'], pr['y']))
        si_point.transform(geotransform)
        pr['x_wgs'] = si_point.x
        pr['y_wgs'] = si_point.y

    return data

Example 14

Project: OIPA
Source File: filters.py
View license
    def filter_queryset(self, request, queryset, view):

        location_longitude = request.query_params.get('location_longitude', None)
        location_latitude = request.query_params.get('location_latitude', None)
        distance_km = request.query_params.get('location_distance_km', None)

        if location_longitude and location_latitude and distance_km:
            pnt = GEOSGeometry('POINT({0} {1})'.format(location_longitude, location_latitude), srid=4326)

            if Location is not queryset.model:
                model_prefix = 'location__'
            else:
                model_prefix = ''
                
            loc_ids = Location.objects.filter(**{'point_pos__distance_lte': (pnt, D(km=distance_km))}).values('id')

            return queryset.filter(**{"{}id__in".format(model_prefix): loc_ids})

        return queryset

Example 15

Project: OIPA
Source File: forms.py
View license
    def __init__(self, *args, **kwargs):
        if args:
            data = args[0]
            if data['latitude'] and data['longitude']:
                latitude = float(data['latitude'])
                longitude = float(data['longitude'])
                data['point_pos'] = GEOSGeometry(Point(longitude, latitude), srid=4326)
        try:
            coordinates = kwargs['instance'].point_pos.tuple
            initial = kwargs.get('initial', {})
            initial['longitude'] = coordinates[0]
            initial['latitude'] = coordinates[1]
            kwargs['initial'] = initial
        except (KeyError, AttributeError):
            pass
        super(LocationForm, self).__init__(*args, **kwargs)

Example 16

Project: OIPA
Source File: forms.py
View license
    def clean(self):
        data = super(LocationForm, self).clean()
        if 'point_pos' in self.errors:
            del self.errors['point_pos']
        if "latitude" in self.changed_data or "longitude" in self.changed_data:
            try:
                lat, lng = float(data.pop("latitude", None)), float(data.pop("longitude", None))
                data['point_pos'] = GEOSGeometry(Point(lng, lat), srid=4326)
            except (TypeError, ValueError):
                data['point_pos'] = None

        if not (data.get("point_pos") or data.get("latitude")):
            raise forms.ValidationError({"latitude": "Coordinates is required"})
        return data

Example 17

Project: django-spillway
Source File: test_generics.py
View license
    def _parse_collection(self, response, srid=None):
        data = json.loads(response.content)
        self.assertEqual(data['type'], 'FeatureCollection')
        self.assertEqual(len(data['features']), len(self.qs))
        for feature in data['features']:
            yield geos.GEOSGeometry(
                json.dumps(feature['geometry']), srid or self.srid)

Example 18

Project: django-spillway
Source File: test_query.py
View license
    def test_simplify_geojson(self):
        sqs = self.qs.simplify(self.tol, srid=self.srid,
                               format='geojson', precision=2)
        geom = geos.GEOSGeometry(sqs[0].geojson, self.srid)
        source = self.qs[0].geom
        self.assertNotEqual(geom, source)
        self.assertEqual(geom.srid, source.srid)
        self.assertLess(geom.num_coords, source.num_coords)

Example 19

Project: cgstudiomap
Source File: widgets.py
View license
    def deserialize(self, value):
        try:
            return GEOSGeometry(value, self.map_srid)
        except (GEOSException, ValueError) as err:
            logger.error(
                "Error creating geometry from value '%s' (%s)" % (
                    value, err)
            )
        return None

Example 20

Project: cgstudiomap
Source File: layer.py
View license
    def get_geoms(self, geos=False):
        """
        Returns a list containing the OGRGeometry for every Feature in
        the Layer.
        """
        if geos:
            from django.contrib.gis.geos import GEOSGeometry
            return [GEOSGeometry(feat.geom.wkb) for feat in self]
        else:
            return [feat.geom for feat in self]

Example 21

Project: django-nonrel
Source File: tests.py
View license
    @no_mysql
    @no_oracle
    @no_spatialite
    def test14_collect(self):
        "Testing the `collect` GeoQuerySet method and `Collect` aggregate."
        # Reference query:
        # SELECT AsText(ST_Collect("relatedapp_location"."point")) FROM "relatedapp_city" LEFT OUTER JOIN
        #    "relatedapp_location" ON ("relatedapp_city"."location_id" = "relatedapp_location"."id")
        #    WHERE "relatedapp_city"."state" = 'TX';
        ref_geom = GEOSGeometry('MULTIPOINT(-97.516111 33.058333,-96.801611 32.782057,-95.363151 29.763374,-96.801611 32.782057)')

        c1 = City.objects.filter(state='TX').collect(field_name='location__point')
        c2 = City.objects.filter(state='TX').aggregate(Collect('location__point'))['location__point__collect']

        for coll in (c1, c2):
            # Even though Dallas and Ft. Worth share same point, Collect doesn't
            # consolidate -- that's why 4 points in MultiPoint.
            self.assertEqual(4, len(coll))
            self.assertEqual(ref_geom, coll)

Example 22

Project: django-nonrel
Source File: test_geoforms.py
View license
    def test01_srid(self):
        "Testing GeometryField with a SRID set."
        # Input that doesn't specify the SRID is assumed to be in the SRID
        # of the input field.
        fld = forms.GeometryField(srid=4326)
        geom = fld.clean('POINT(5 23)')
        self.assertEqual(4326, geom.srid)
        # Making the field in a different SRID from that of the geometry, and
        # asserting it transforms.
        fld = forms.GeometryField(srid=32140)
        tol = 0.0000001
        xform_geom = GEOSGeometry('POINT (951640.547328465 4219369.26171664)', srid=32140)
        # The cleaned geometry should be transformed to 32140.
        cleaned_geom = fld.clean('SRID=4326;POINT (-95.363151 29.763374)')
        self.assertTrue(xform_geom.equals_exact(cleaned_geom, tol))

Example 23

Project: hue
Source File: tests.py
View license
    def test_union(self):
        """
        Testing the Union aggregate of 3D models.
        """
        # PostGIS query that returned the reference EWKT for this test:
        #  `SELECT ST_AsText(ST_Union(point)) FROM geo3d_city3d;`
        self._load_city_data()
        ref_ewkt = 'SRID=4326;MULTIPOINT(-123.305196 48.462611 15,-104.609252 38.255001 1433,-97.521157 34.464642 380,-96.801611 32.782057 147,-95.363151 29.763374 18,-95.23506 38.971823 251,-87.650175 41.850385 181,174.783117 -41.315268 14)'
        ref_union = GEOSGeometry(ref_ewkt)
        union = City3D.objects.aggregate(Union('point'))['point__union']
        self.assertTrue(union.hasz)
        self.assertEqual(ref_union, union)

Example 24

Project: hue
Source File: tests.py
View license
    @no_mysql
    @no_oracle
    @no_spatialite
    def test_make_line(self):
        "Testing the `make_line` GeoQuerySet method."
        # Ensuring that a `TypeError` is raised on models without PointFields.
        self.assertRaises(TypeError, State.objects.make_line)
        self.assertRaises(TypeError, Country.objects.make_line)
        # Reference query:
        # SELECT AsText(ST_MakeLine(geoapp_city.point)) FROM geoapp_city;
        ref_line = GEOSGeometry('LINESTRING(-95.363151 29.763374,-96.801611 32.782057,-97.521157 34.464642,174.783117 -41.315268,-104.609252 38.255001,-95.23506 38.971823,-87.650175 41.850385,-123.305196 48.462611)', srid=4326)
        self.assertEqual(ref_line, City.objects.make_line())

Example 25

Project: hue
Source File: test_geoforms.py
View license
    def test_to_python(self):
        """
        Testing to_python returns a correct GEOSGeometry object or
        a ValidationError
        """
        fld = forms.GeometryField()
        # to_python returns the same GEOSGeometry for a WKT
        for wkt in ('POINT(5 23)', 'MULTIPOLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))', 'LINESTRING(0 0, 1 1)'):
            self.assertEqual(GEOSGeometry(wkt), fld.to_python(wkt))
        # but raises a ValidationError for any other string
        for wkt in ('POINT(5)', 'MULTI   POLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))', 'BLAH(0 0, 1 1)'):
            self.assertRaises(forms.ValidationError, fld.to_python, wkt)

Example 26

Project: decode-Django
Source File: test_geos.py
View license
    def test_copy(self):
        "Testing use with the Python `copy` module."
        import copy
        poly = GEOSGeometry('POLYGON((0 0, 0 23, 23 23, 23 0, 0 0), (5 5, 5 10, 10 10, 10 5, 5 5))')
        cpy1 = copy.copy(poly)
        cpy2 = copy.deepcopy(poly)
        self.assertNotEqual(poly._ptr, cpy1._ptr)
        self.assertNotEqual(poly._ptr, cpy2._ptr)

Example 27

Project: decode-Django
Source File: test_geos.py
View license
    def test_transform_nosrid(self):
        """ Testing `transform` method (no SRID or negative SRID) """

        g = GEOSGeometry('POINT (-104.609 38.255)', srid=None)
        self.assertRaises(GEOSException, g.transform, 2774)

        g = GEOSGeometry('POINT (-104.609 38.255)', srid=None)
        self.assertRaises(GEOSException, g.transform, 2774, clone=True)

        g = GEOSGeometry('POINT (-104.609 38.255)', srid=-1)
        self.assertRaises(GEOSException, g.transform, 2774)

        g = GEOSGeometry('POINT (-104.609 38.255)', srid=-1)
        self.assertRaises(GEOSException, g.transform, 2774, clone=True)

Example 28

Project: decode-Django
Source File: test_geos.py
View license
    def test_transform_nogdal(self):
        """ Testing `transform` method (GDAL not available) """
        old_has_gdal = gdal.HAS_GDAL
        try:
            gdal.HAS_GDAL = False

            g = GEOSGeometry('POINT (-104.609 38.255)', 4326)
            self.assertRaises(GEOSException, g.transform, 2774)

            g = GEOSGeometry('POINT (-104.609 38.255)', 4326)
            self.assertRaises(GEOSException, g.transform, 2774, clone=True)
        finally:
            gdal.HAS_GDAL = old_has_gdal

Example 29

Project: django-compositepks
Source File: layer.py
View license
    def get_geoms(self, geos=False):
        """
        Returns a list containing the OGRGeometry for every Feature in
        the Layer.
        """
        if geos:
            from django.contrib.gis.geos import GEOSGeometry
            return [GEOSGeometry(feat.geom.wkb) for feat in self]
        else:
            return [feat.geom for feat in self]

Example 30

Project: django
Source File: widgets.py
View license
    def deserialize(self, value):
        try:
            return GEOSGeometry(value, self.map_srid)
        except (GEOSException, ValueError) as err:
            logger.error("Error creating geometry from value '%s' (%s)", value, err)
        return None

Example 31

Project: django
Source File: layer.py
View license
    def get_geoms(self, geos=False):
        """
        Returns a list containing the OGRGeometry for every Feature in
        the Layer.
        """
        if geos:
            from django.contrib.gis.geos import GEOSGeometry
            return [GEOSGeometry(feat.geom.wkb) for feat in self]
        else:
            return [feat.geom for feat in self]

Example 32

Project: django-haystack
Source File: test_spatial.py
View license
    def test_ensure_wgs84(self):
        self.assertRaises(SpatialError, ensure_wgs84, GEOSGeometry('POLYGON((-95 38, -96 40, -97 42, -95 38))'))

        orig_pnt = Point(-95.23592948913574, 38.97127105172941)
        std_pnt = ensure_wgs84(orig_pnt)
        self.assertEqual(orig_pnt.srid, None)
        self.assertEqual(std_pnt.srid, 4326)
        self.assertEqual(std_pnt.x, -95.23592948913574)
        self.assertEqual(std_pnt.y, 38.97127105172941)

        orig_pnt = Point(-95.23592948913574, 38.97127105172941)
        orig_pnt.set_srid(2805)
        std_pnt = ensure_wgs84(orig_pnt)
        self.assertEqual(orig_pnt.srid, 2805)
        self.assertEqual(std_pnt.srid, 4326)
        # These should be different, since it got transformed.
        self.assertNotEqual(std_pnt.x, -95.23592948913574)
        self.assertNotEqual(std_pnt.y, 38.97127105172941)

Example 33

Project: django-oscar-stores
Source File: forms.py
View license
    def geocoordinates(self, data):
        latitude = data.get('latitude', None)
        longitude = data.get('longitude', None)
        if latitude and longitude:
            return GEOSGeometry('POINT(%s %s)' % (longitude, latitude))

        query = data.get('query', None)
        if query is not None:
            try:
                return geocode.GeoCodeService().geocode(query)
            except geocode.ServiceError:
                return None

Example 34

Project: django-tastypie
Source File: resources.py
View license
    def filter_value_to_python(self, value, field_name, filters, filter_expr,
            filter_type):
        value = super(ModelResource, self).filter_value_to_python(
            value, field_name, filters, filter_expr, filter_type)

        # If we are filtering on a GeometryApiField then we should try
        # and convert this to a GEOSGeometry object.  The conversion
        # will fail if we don't have value JSON, so in that case we'll
        # just return ``value`` as normal.
        if isinstance(self.fields[field_name], GeometryApiField):
            try:
                value = GEOSGeometry(unquote(value))
            except ValueError:
                pass
        return value

Example 35

Project: django-rest-framework-gis
Source File: fields.py
View license
    def to_internal_value(self, value):
        if value == '' or value is None:
            return value
        if isinstance(value, GEOSGeometry):
            # value already has the correct representation
            return value
        if isinstance(value, dict):
            value = json.dumps(value)
        try:
            return GEOSGeometry(value)
        except (ValueError, GEOSException, OGRException, TypeError):
            raise ValidationError(_('Invalid format: string or unicode input unrecognized as GeoJSON, WKT EWKT or HEXEWKB.'))

Example 36

Project: django-rest-framework-gis
Source File: tests.py
View license
    def test_pickle(self):
        geometry = GEOSGeometry('POINT (30 10)')
        geojsondict = GeoJsonDict((
            ('type', geometry.geom_type),
            ('coordinates', geometry.coords),
        ))
        pickled = pickle.dumps(geojsondict)
        restored = pickle.loads(pickled)
        self.assertEqual(restored, geojsondict)

Example 37

Project: HealthStarter
Source File: widgets.py
View license
    def deserialize(self, value):
        try:
            return GEOSGeometry(value, self.map_srid)
        except (GEOSException, ValueError) as err:
            logger.error(
                "Error creating geometry from value '%s' (%s)" % (
                    value, err)
            )
        return None

Example 38

Project: HealthStarter
Source File: layer.py
View license
    def get_geoms(self, geos=False):
        """
        Returns a list containing the OGRGeometry for every Feature in
        the Layer.
        """
        if geos:
            from django.contrib.gis.geos import GEOSGeometry
            return [GEOSGeometry(feat.geom.wkb) for feat in self]
        else:
            return [feat.geom for feat in self]

Example 39

Project: lettuce
Source File: layer.py
View license
    def get_geoms(self, geos=False):
        """
        Returns a list containing the OGRGeometry for every Feature in
        the Layer.
        """
        if geos:
            from django.contrib.gis.geos import GEOSGeometry
            return [GEOSGeometry(feat.geom.wkb) for feat in self]
        else:
            return [feat.geom for feat in self]

Example 40

Project: lettuce
Source File: test_io.py
View license
    def test02_wktwriter(self):
        # Creating a WKTWriter instance, testing its ptr property.
        wkt_w = WKTWriter()
        self.assertRaises(TypeError, wkt_w._set_ptr, WKTReader.ptr_type())

        ref = GEOSGeometry('POINT (5 23)')
        ref_wkt = 'POINT (5.0000000000000000 23.0000000000000000)'
        self.assertEqual(ref_wkt, wkt_w.write(ref))

Example 41

Project: lettuce
Source File: tests.py
View license
    @no_mysql
    @no_oracle
    @no_spatialite
    def test14_collect(self):
        "Testing the `collect` GeoQuerySet method and `Collect` aggregate."
        # Reference query:
        # SELECT AsText(ST_Collect("relatedapp_location"."point")) FROM "relatedapp_city" LEFT OUTER JOIN
        #    "relatedapp_location" ON ("relatedapp_city"."location_id" = "relatedapp_location"."id")
        #    WHERE "relatedapp_city"."state" = 'TX';
        ref_geom = GEOSGeometry('MULTIPOINT(-97.516111 33.058333,-96.801611 32.782057,-95.363151 29.763374,-96.801611 32.782057)')

        c1 = City.objects.filter(state='TX').collect(field_name='location__point')
        c2 = City.objects.filter(state='TX').aggregate(Collect('location__point'))['location__point__collect']

        for coll in (c1, c2):
            # Even though Dallas and Ft. Worth share same point, Collect doesn't
            # consolidate -- that's why 4 points in MultiPoint.
            self.assertEqual(4, len(coll))
            self.assertEqual(ref_geom, coll)

Example 42

Project: Geotrek-admin
Source File: serializers.py
View license
    def validate_geom(self, attrs, source):
        if source not in attrs:
            return attrs
        geom = attrs[source]
        point = GEOSGeometry(geom, srid=4326)
        attrs[source] = point
        return attrs

Example 43

Project: Geotrek-admin
Source File: test_loadpoi.py
View license
    def test_create_pois_receives_geometries(self):
        geom1 = GEOSGeometry('POINT(-1.36308670782119 -5.98358469800134696)')
        geom2 = GEOSGeometry('POINT(-1.363087202331107 -5.98358423531846917)')
        with patch.object(Command, 'create_poi') as mocked:
            self.cmd.execute(self.filename)
            call1 = mocked.call_args_list[0][0]
            call2 = mocked.call_args_list[1][0]
            self.assertEquals(call1[0], geom1)
            self.assertEquals(call2[0], geom2)

Example 44

Project: Geotrek-admin
Source File: test_loadpoi.py
View license
    def test_pois_are_created(self):
        geom = GEOSGeometry('POINT(1 1)')
        before = len(POI.objects.all())
        self.cmd.create_poi(geom, 'bridge', 'infra')
        after = len(POI.objects.all())
        self.assertEquals(after - before, 1)

Example 45

Project: feedsanitizer
Source File: test_io.py
View license
    def test01_wktreader(self):
        # Creating a WKTReader instance
        wkt_r = WKTReader()
        wkt = 'POINT (5 23)'

        # read() should return a GEOSGeometry
        ref = GEOSGeometry(wkt)
        g1 = wkt_r.read(wkt)
        g2 = wkt_r.read(unicode(wkt))

        for geom in (g1, g2):
            self.assertEqual(ref, geom)

        # Should only accept basestring objects.
        self.assertRaises(TypeError, wkt_r.read, 1)
        self.assertRaises(TypeError, wkt_r.read, buffer('foo'))

Example 46

Project: feedsanitizer
Source File: test_io.py
View license
    def test02_wktwriter(self):
        # Creating a WKTWriter instance, testing its ptr property.
        wkt_w = WKTWriter()
        self.assertRaises(TypeError, wkt_w._set_ptr, WKTReader.ptr_type())

        ref = GEOSGeometry('POINT (5 23)')
        ref_wkt = 'POINT (5.0000000000000000 23.0000000000000000)'
        self.assertEqual(ref_wkt, wkt_w.write(ref))

Example 47

Project: feedsanitizer
Source File: test_io.py
View license
    def test03_wkbreader(self):
        # Creating a WKBReader instance
        wkb_r = WKBReader()

        hex = '000000000140140000000000004037000000000000'
        wkb = buffer(binascii.a2b_hex(hex))
        ref = GEOSGeometry(hex)

        # read() should return a GEOSGeometry on either a hex string or
        # a WKB buffer.
        g1 = wkb_r.read(wkb)
        g2 = wkb_r.read(hex)
        for geom in (g1, g2):
            self.assertEqual(ref, geom)

        bad_input = (1, 5.23, None, False)
        for bad_wkb in bad_input:
            self.assertRaises(TypeError, wkb_r.read, bad_wkb)

Example 48

Project: hortonworks-sandbox
Source File: tests.py
View license
    def test03a_union(self):
        "Testing the Union aggregate of 3D models."
        # PostGIS query that returned the reference EWKT for this test:
        #  `SELECT ST_AsText(ST_Union(point)) FROM geo3d_city3d;`
        ref_ewkt = 'SRID=4326;MULTIPOINT(-123.305196 48.462611 15,-104.609252 38.255001 1433,-97.521157 34.464642 380,-96.801611 32.782057 147,-95.363151 29.763374 18,-95.23506 38.971823 251,-87.650175 41.850385 181,174.783117 -41.315268 14)'
        ref_union = GEOSGeometry(ref_ewkt)
        union = City3D.objects.aggregate(Union('point'))['point__union']
        self.failUnless(union.hasz)
        self.assertEqual(ref_union, union)

Example 49

Project: hunch-gift-app
Source File: tests.py
View license
    def test03a_union(self):
        "Testing the Union aggregate of 3D models."
        # PostGIS query that returned the reference EWKT for this test:
        #  `SELECT ST_AsText(ST_Union(point)) FROM geo3d_city3d;`
        ref_ewkt = 'SRID=4326;MULTIPOINT(-123.305196 48.462611 15,-104.609252 38.255001 1433,-97.521157 34.464642 380,-96.801611 32.782057 147,-95.363151 29.763374 18,-95.23506 38.971823 251,-87.650175 41.850385 181,174.783117 -41.315268 14)'
        ref_union = GEOSGeometry(ref_ewkt)
        union = City3D.objects.aggregate(Union('point'))['point__union']
        self.failUnless(union.hasz)
        self.assertEqual(ref_union, union)

Example 50

Project: hunch-gift-app
Source File: test_geoforms.py
View license
    def test01_srid(self):
        "Testing GeometryField with a SRID set."
        # Input that doesn't specify the SRID is assumed to be in the SRID
        # of the input field.
        fld = forms.GeometryField(srid=4326)
        geom = fld.clean('POINT(5 23)')
        self.assertEqual(4326, geom.srid)
        # Making the field in a different SRID from that of the geometry, and
        # asserting it transforms.
        fld = forms.GeometryField(srid=32140)
        tol = 0.0000001
        xform_geom = GEOSGeometry('POINT (951640.547328465 4219369.26171664)', srid=32140)
        # The cleaned geometry should be transformed to 32140.
        cleaned_geom = fld.clean('SRID=4326;POINT (-95.363151 29.763374)')
        self.failUnless(xform_geom.equals_exact(cleaned_geom, tol))