def test04_wkbwriter(self):
        wkb_w = WKBWriter()

        # Representations of 'POINT (5 23)' in hex -- one normal and
        # the other with the byte order changed.
        g = GEOSGeometry('POINT (5 23)')
        hex1 = '010100000000000000000014400000000000003740'
        wkb1 = buffer(binascii.a2b_hex(hex1))
        hex2 = '000000000140140000000000004037000000000000'
        wkb2 = buffer(binascii.a2b_hex(hex2))

        self.assertEqual(hex1, wkb_w.write_hex(g))
        self.assertEqual(wkb1, wkb_w.write(g))

        # Ensuring bad byteorders are not accepted.
        for bad_byteorder in (-1, 2, 523, 'foo', None):
            # Equivalent of `wkb_w.byteorder = bad_byteorder`
            self.assertRaises(ValueError, wkb_w._set_byteorder, bad_byteorder)

        # Setting the byteorder to 0 (for Big Endian)
        wkb_w.byteorder = 0
        self.assertEqual(hex2, wkb_w.write_hex(g))
        self.assertEqual(wkb2, wkb_w.write(g))

        # Back to Little Endian
        wkb_w.byteorder = 1

        # Now, trying out the 3D and SRID flags.
        g = GEOSGeometry('POINT (5 23 17)')
        g.srid = 4326

        hex3d = '0101000080000000000000144000000000000037400000000000003140'
        wkb3d = buffer(binascii.a2b_hex(hex3d))
        hex3d_srid = '01010000A0E6100000000000000000144000000000000037400000000000003140'
        wkb3d_srid = buffer(binascii.a2b_hex(hex3d_srid))

        # Ensuring bad output dimensions are not accepted
        for bad_outdim in (-1, 0, 1, 4, 423, 'foo', None):
            # Equivalent of `wkb_w.outdim = bad_outdim`
            self.assertRaises(ValueError, wkb_w._set_outdim, bad_outdim)

        # These tests will fail on 3.0.0 because of a bug that was fixed in 3.1:
        # http://trac.osgeo.org/geos/ticket/216
        if not geos_version_info()['version'].startswith('3.0.'):
            # Now setting the output dimensions to be 3
            wkb_w.outdim = 3

            self.assertEqual(hex3d, wkb_w.write_hex(g))
            self.assertEqual(wkb3d, wkb_w.write(g))

            # Telling the WKBWriter to inlcude the srid in the representation.
            wkb_w.srid = True
            self.assertEqual(hex3d_srid, wkb_w.write_hex(g))
            self.assertEqual(wkb3d_srid, wkb_w.write(g))
Esempio n. 2
0
    def test03_geom_type(self):
        "Testing GeometryField's handling of different geometry types."
        # By default, all geometry types are allowed.
        fld = forms.GeometryField()
        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.clean(wkt))

        pnt_fld = forms.GeometryField(geom_type='POINT')
        self.assertEqual(GEOSGeometry('POINT(5 23)'),
                         pnt_fld.clean('POINT(5 23)'))
        self.assertRaises(forms.ValidationError, pnt_fld.clean,
                          'LINESTRING(0 0, 1 1)')
Esempio n. 3
0
 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))
    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))
Esempio n. 5
0
 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.assertTrue(union.hasz)
     self.assertEqual(ref_union, union)
 def get_geoms(self, geos=False):
     """
     Returns a list containing the OGRGeometry for every Feature in
     the Layer.
     """
     if geos:
         from my_django.contrib.gis.geos import GEOSGeometry
         return [GEOSGeometry(feat.geom.wkb) for feat in self]
     else:
         return [feat.geom for feat in self]
Esempio n. 7
0
    def test01_3d(self):
        "Test the creation of 3D models."
        # 3D models for the rest of the tests will be populated in here.
        # For each 3D data set create model (and 2D version if necessary),
        # retrieve, and assert geometry is in 3D and contains the expected
        # 3D values.
        for name, pnt_data in city_data:
            x, y, z = pnt_data
            pnt = Point(x, y, z, srid=4326)
            City3D.objects.create(name=name, point=pnt)
            city = City3D.objects.get(name=name)
            self.assertTrue(city.point.hasz)
            self.assertEqual(z, city.point.z)

        # Interstate (2D / 3D and Geographic/Projected variants)
        for name, line, exp_z in interstate_data:
            line_3d = GEOSGeometry(line, srid=4269)
            # Using `hex` attribute because it omits 3D.
            line_2d = GEOSGeometry(line_3d.hex, 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)

            # Retrieving and making sure it's 3D and has expected
            # Z values -- shouldn't change because of coordinate system.
            interstate = Interstate3D.objects.get(name=name)
            interstate_proj = InterstateProj3D.objects.get(name=name)
            for i in [interstate, interstate_proj]:
                self.assertTrue(i.line.hasz)
                self.assertEqual(exp_z, tuple(i.line.z))

        # Creating 3D Polygon.
        bbox2d, bbox3d = gen_bbox()
        Polygon2D.objects.create(name='2D BBox', poly=bbox2d)
        Polygon3D.objects.create(name='3D BBox', poly=bbox3d)
        p3d = Polygon3D.objects.get(name='3D BBox')
        self.assertTrue(p3d.poly.hasz)
        self.assertEqual(bbox3d, p3d.poly)
 def test06_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())
Esempio n. 9
0
    def render(self, name, value, attrs=None):
        # Update the template parameters with any attributes passed in.
        if attrs: self.params.update(attrs)

        # Defaulting the WKT value to a blank string -- this
        # will be tested in the JavaScript and the appropriate
        # interface will be constructed.
        self.params['wkt'] = ''

        # If a string reaches here (via a validation error on another
        # field) then just reconstruct the Geometry.
        if isinstance(value, basestring):
            try:
                value = GEOSGeometry(value)
            except (GEOSException, ValueError):
                value = None

        if value and value.geom_type.upper() != self.geom_type:
            value = None

        # Constructing the dictionary of the map options.
        self.params['map_options'] = self.map_options()

        # Constructing the JavaScript module name using the name of
        # the GeometryField (passed in via the `attrs` keyword).
        # Use the 'name' attr for the field name (rather than 'field')
        self.params['name'] = name
        # note: we must switch out dashes for underscores since js
        # functions are created using the module variable
        js_safe_name = self.params['name'].replace('-','_')
        self.params['module'] = 'geodjango_%s' % js_safe_name

        if value:
            # Transforming the geometry to the projection used on the
            # OpenLayers map.
            srid = self.params['srid']
            if value.srid != srid:
                try:
                    ogr = value.ogr
                    ogr.transform(srid)
                    wkt = ogr.wkt
                except OGRException:
                    wkt = ''
            else:
                wkt = value.wkt

            # Setting the parameter WKT with that of the transformed
            # geometry.
            self.params['wkt'] = wkt

        return loader.render_to_string(self.template, self.params,
                                       context_instance=geo_context)
    def clean(self, value):
        """
        Validates that the input value can be converted to a Geometry
        object (which is returned).  A ValidationError is raised if
        the value cannot be instantiated as a Geometry.
        """
        if not value:
            if self.null and not self.required:
                # The geometry column allows NULL and is not required.
                return None
            else:
                raise forms.ValidationError(self.error_messages['no_geom'])

        # Trying to create a Geometry object from the form value.
        try:
            geom = GEOSGeometry(value)
        except:
            raise forms.ValidationError(self.error_messages['invalid_geom'])

        # Ensuring that the geometry is of the correct type (indicated
        # using the OGC string label).
        if str(geom.geom_type).upper(
        ) != self.geom_type and not self.geom_type == 'GEOMETRY':
            raise forms.ValidationError(
                self.error_messages['invalid_geom_type'])

        # Transforming the geometry if the SRID was set.
        if self.srid:
            if not geom.srid:
                # Should match that of the field if not given.
                geom.srid = self.srid
            elif self.srid != -1 and self.srid != geom.srid:
                try:
                    geom.transform(self.srid)
                except:
                    raise forms.ValidationError(
                        self.error_messages['transform_error'])

        return geom
    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'))
    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)
    def test06_f_expressions(self):
        "Testing F() expressions on GeometryFields."
        # Constructing a dummy parcel border and getting the City instance for
        # assigning the FK.
        b1 = GEOSGeometry('POLYGON((-97.501205 33.052520,-97.501205 33.052576,-97.501150 33.052576,-97.501150 33.052520,-97.501205 33.052520))', srid=4326)
        pcity = City.objects.get(name='Aurora')

        # First parcel has incorrect center point that is equal to the City;
        # it also has a second border that is different from the first as a
        # 100ft buffer around the City.
        c1 = pcity.location.point
        c2 = c1.transform(2276, clone=True)
        b2 = c2.buffer(100)
        p1 = Parcel.objects.create(name='P1', city=pcity, center1=c1, center2=c2, border1=b1, border2=b2)

        # Now creating a second Parcel where the borders are the same, just
        # in different coordinate systems.  The center points are also the
        # same (but in different coordinate systems), and this time they
        # actually correspond to the centroid of the border.
        c1 = b1.centroid
        c2 = c1.transform(2276, clone=True)
        p2 = Parcel.objects.create(name='P2', city=pcity, center1=c1, center2=c2, border1=b1, border2=b1)

        # Should return the second Parcel, which has the center within the
        # border.
        qs = Parcel.objects.filter(center1__within=F('border1'))
        self.assertEqual(1, len(qs))
        self.assertEqual('P2', qs[0].name)

        if not mysql:
            # This time center2 is in a different coordinate system and needs
            # to be wrapped in transformation SQL.
            qs = Parcel.objects.filter(center2__within=F('border1'))
            self.assertEqual(1, len(qs))
            self.assertEqual('P2', qs[0].name)

        # Should return the first Parcel, which has the center point equal
        # to the point in the City ForeignKey.
        qs = Parcel.objects.filter(center1=F('city__location__point'))
        self.assertEqual(1, len(qs))
        self.assertEqual('P1', qs[0].name)

        if not mysql:
            # This time the city column should be wrapped in transformation SQL.
            qs = Parcel.objects.filter(border2__contains=F('city__location__point'))
            self.assertEqual(1, len(qs))
            self.assertEqual('P1', qs[0].name)
Esempio n. 14
0
    def test03a_distance_method(self):
        "Testing the `distance` GeoQuerySet method on projected coordinate systems."
        # The point for La Grange, TX
        lagrange = GEOSGeometry('POINT(-96.876369 29.905320)', 4326)
        # Reference distances in feet and in meters. Got these values from
        # using the provided raw SQL statements.
        #  SELECT ST_Distance(point, ST_Transform(ST_GeomFromText('POINT(-96.876369 29.905320)', 4326), 32140)) FROM distapp_southtexascity;
        m_distances = [
            147075.069813, 139630.198056, 140888.552826, 138809.684197,
            158309.246259, 212183.594374, 70870.188967, 165337.758878,
            139196.085105
        ]
        #  SELECT ST_Distance(point, ST_Transform(ST_GeomFromText('POINT(-96.876369 29.905320)', 4326), 2278)) FROM distapp_southtexascityft;
        # Oracle 11 thinks this is not a projected coordinate system, so it's s
        # not tested.
        ft_distances = [
            482528.79154625, 458103.408123001, 462231.860397575,
            455411.438904354, 519386.252102563, 696139.009211594,
            232513.278304279, 542445.630586414, 456679.155883207
        ]

        # Testing using different variations of parameters and using models
        # with different projected coordinate systems.
        dist1 = SouthTexasCity.objects.distance(lagrange, field_name='point')
        dist2 = SouthTexasCity.objects.distance(
            lagrange)  # Using GEOSGeometry parameter
        if spatialite or oracle:
            dist_qs = [dist1, dist2]
        else:
            dist3 = SouthTexasCityFt.objects.distance(
                lagrange.ewkt)  # Using EWKT string parameter.
            dist4 = SouthTexasCityFt.objects.distance(lagrange)
            dist_qs = [dist1, dist2, dist3, dist4]

        # Original query done on PostGIS, have to adjust AlmostEqual tolerance
        # for Oracle.
        if oracle: tol = 2
        else: tol = 5

        # Ensuring expected distances are returned for each distance queryset.
        for qs in dist_qs:
            for i, c in enumerate(qs):
                self.assertAlmostEqual(m_distances[i], c.distance.m, tol)
                self.assertAlmostEqual(ft_distances[i], c.distance.survey_ft,
                                       tol)
    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)
    def test03_transform_related(self):
        "Testing the `transform` GeoQuerySet method on related geographic models."
        # All the transformations are to state plane coordinate systems using
        # US Survey Feet (thus a tolerance of 0 implies error w/in 1 survey foot).
        tol = 0

        def check_pnt(ref, pnt):
            self.assertAlmostEqual(ref.x, pnt.x, tol)
            self.assertAlmostEqual(ref.y, pnt.y, tol)
            self.assertEqual(ref.srid, pnt.srid)

        # Each city transformed to the SRID of their state plane coordinate system.
        transformed = (('Kecksburg', 2272, 'POINT(1490553.98959621 314792.131023984)'),
                       ('Roswell', 2257, 'POINT(481902.189077221 868477.766629735)'),
                       ('Aurora', 2276, 'POINT(2269923.2484839 7069381.28722222)'),
                       )

        for name, srid, wkt in transformed:
            # Doing this implicitly sets `select_related` select the location.
            # TODO: Fix why this breaks on Oracle.
            qs = list(City.objects.filter(name=name).transform(srid, field_name='location__point'))
            check_pnt(GEOSGeometry(wkt, srid), qs[0].location.point)
Esempio n. 17
0
def gen_bbox():
    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)
    return bbox_2d, bbox_3d
Esempio n. 18
0
class DistanceTest(TestCase):

    # A point we are testing distances with -- using a WGS84
    # coordinate that'll be implicitly transormed to that to
    # the coordinate system of the field, EPSG:32140 (Texas South Central
    # w/units in meters)
    stx_pnt = GEOSGeometry('POINT (-95.370401017314293 29.704867409475465)',
                           4326)
    # Another one for Australia
    au_pnt = GEOSGeometry('POINT (150.791 -34.4919)', 4326)

    def get_names(self, qs):
        cities = [c.name for c in qs]
        cities.sort()
        return cities

    def test01_init(self):
        "Test initialization of distance models."
        self.assertEqual(9, SouthTexasCity.objects.count())
        self.assertEqual(9, SouthTexasCityFt.objects.count())
        self.assertEqual(11, AustraliaCity.objects.count())
        self.assertEqual(4, SouthTexasZipcode.objects.count())
        self.assertEqual(4, CensusZipcode.objects.count())
        self.assertEqual(1, Interstate.objects.count())
        self.assertEqual(1, SouthTexasInterstate.objects.count())

    @no_spatialite
    def test02_dwithin(self):
        "Testing the `dwithin` lookup type."
        # Distances -- all should be equal (except for the
        # degree/meter pair in au_cities, that's somewhat
        # approximate).
        tx_dists = [(7000, 22965.83), D(km=7), D(mi=4.349)]
        au_dists = [(0.5, 32000), D(km=32), D(mi=19.884)]

        # Expected cities for Australia and Texas.
        tx_cities = ['Downtown Houston', 'Southside Place']
        au_cities = ['Mittagong', 'Shellharbour', 'Thirroul', 'Wollongong']

        # Performing distance queries on two projected coordinate systems one
        # with units in meters and the other in units of U.S. survey feet.
        for dist in tx_dists:
            if isinstance(dist, tuple): dist1, dist2 = dist
            else: dist1 = dist2 = dist
            qs1 = SouthTexasCity.objects.filter(point__dwithin=(self.stx_pnt,
                                                                dist1))
            qs2 = SouthTexasCityFt.objects.filter(point__dwithin=(self.stx_pnt,
                                                                  dist2))
            for qs in qs1, qs2:
                self.assertEqual(tx_cities, self.get_names(qs))

        # Now performing the `dwithin` queries on a geodetic coordinate system.
        for dist in au_dists:
            if isinstance(dist, D) and not oracle: type_error = True
            else: type_error = False

            if isinstance(dist, tuple):
                if oracle: dist = dist[1]
                else: dist = dist[0]

            # Creating the query set.
            qs = AustraliaCity.objects.order_by('name')
            if type_error:
                # A ValueError should be raised on PostGIS when trying to pass
                # Distance objects into a DWithin query using a geodetic field.
                self.assertRaises(
                    ValueError,
                    AustraliaCity.objects.filter(point__dwithin=(self.au_pnt,
                                                                 dist)).count)
            else:
                self.assertEqual(
                    au_cities,
                    self.get_names(
                        qs.filter(point__dwithin=(self.au_pnt, dist))))

    def test03a_distance_method(self):
        "Testing the `distance` GeoQuerySet method on projected coordinate systems."
        # The point for La Grange, TX
        lagrange = GEOSGeometry('POINT(-96.876369 29.905320)', 4326)
        # Reference distances in feet and in meters. Got these values from
        # using the provided raw SQL statements.
        #  SELECT ST_Distance(point, ST_Transform(ST_GeomFromText('POINT(-96.876369 29.905320)', 4326), 32140)) FROM distapp_southtexascity;
        m_distances = [
            147075.069813, 139630.198056, 140888.552826, 138809.684197,
            158309.246259, 212183.594374, 70870.188967, 165337.758878,
            139196.085105
        ]
        #  SELECT ST_Distance(point, ST_Transform(ST_GeomFromText('POINT(-96.876369 29.905320)', 4326), 2278)) FROM distapp_southtexascityft;
        # Oracle 11 thinks this is not a projected coordinate system, so it's s
        # not tested.
        ft_distances = [
            482528.79154625, 458103.408123001, 462231.860397575,
            455411.438904354, 519386.252102563, 696139.009211594,
            232513.278304279, 542445.630586414, 456679.155883207
        ]

        # Testing using different variations of parameters and using models
        # with different projected coordinate systems.
        dist1 = SouthTexasCity.objects.distance(lagrange, field_name='point')
        dist2 = SouthTexasCity.objects.distance(
            lagrange)  # Using GEOSGeometry parameter
        if spatialite or oracle:
            dist_qs = [dist1, dist2]
        else:
            dist3 = SouthTexasCityFt.objects.distance(
                lagrange.ewkt)  # Using EWKT string parameter.
            dist4 = SouthTexasCityFt.objects.distance(lagrange)
            dist_qs = [dist1, dist2, dist3, dist4]

        # Original query done on PostGIS, have to adjust AlmostEqual tolerance
        # for Oracle.
        if oracle: tol = 2
        else: tol = 5

        # Ensuring expected distances are returned for each distance queryset.
        for qs in dist_qs:
            for i, c in enumerate(qs):
                self.assertAlmostEqual(m_distances[i], c.distance.m, tol)
                self.assertAlmostEqual(ft_distances[i], c.distance.survey_ft,
                                       tol)

    @no_spatialite
    def test03b_distance_method(self):
        "Testing the `distance` GeoQuerySet method on geodetic coordnate systems."
        if oracle: tol = 2
        else: tol = 5

        # Testing geodetic distance calculation with a non-point geometry
        # (a LineString of Wollongong and Shellharbour coords).
        ls = LineString(((150.902, -34.4245), (150.87, -34.5789)))
        if oracle or connection.ops.geography:
            # Reference query:
            #  SELECT ST_distance_sphere(point, ST_GeomFromText('LINESTRING(150.9020 -34.4245,150.8700 -34.5789)', 4326)) FROM distapp_australiacity ORDER BY name;
            distances = [
                1120954.92533513, 140575.720018241, 640396.662906304,
                60580.9693849269, 972807.955955075, 568451.8357838,
                40435.4335201384, 0, 68272.3896586844, 12375.0643697706, 0
            ]
            qs = AustraliaCity.objects.distance(ls).order_by('name')
            for city, distance in zip(qs, distances):
                # Testing equivalence to within a meter.
                self.assertAlmostEqual(distance, city.distance.m, 0)
        else:
            # PostGIS 1.4 and below is limited to disance queries only
            # to/from point geometries, check for raising of ValueError.
            self.assertRaises(ValueError, AustraliaCity.objects.distance, ls)
            self.assertRaises(ValueError, AustraliaCity.objects.distance,
                              ls.wkt)

        # Got the reference distances using the raw SQL statements:
        #  SELECT ST_distance_spheroid(point, ST_GeomFromText('POINT(151.231341 -33.952685)', 4326), 'SPHEROID["WGS 84",6378137.0,298.257223563]') FROM distapp_australiacity WHERE (NOT (id = 11));
        #  SELECT ST_distance_sphere(point, ST_GeomFromText('POINT(151.231341 -33.952685)', 4326)) FROM distapp_australiacity WHERE (NOT (id = 11));  st_distance_sphere
        if connection.ops.postgis and connection.ops.proj_version_tuple() >= (
                4, 7, 0):
            # PROJ.4 versions 4.7+ have updated datums, and thus different
            # distance values.
            spheroid_distances = [
                60504.0628957201, 77023.9489850262, 49154.8867574404,
                90847.4358768573, 217402.811919332, 709599.234564757,
                640011.483550888, 7772.00667991925, 1047861.78619339,
                1165126.55236034
            ]
            sphere_distances = [
                60580.9693849267, 77144.0435286473, 49199.4415344719,
                90804.7533823494, 217713.384600405, 709134.127242793,
                639828.157159169, 7786.82949717788, 1049204.06569028,
                1162623.7238134
            ]

        else:
            spheroid_distances = [
                60504.0628825298, 77023.948962654, 49154.8867507115,
                90847.435881812, 217402.811862568, 709599.234619957,
                640011.483583758, 7772.00667666425, 1047861.7859506,
                1165126.55237647
            ]
            sphere_distances = [
                60580.7612632291, 77143.7785056615, 49199.2725132184,
                90804.4414289463, 217712.63666124, 709131.691061906,
                639825.959074112, 7786.80274606706, 1049200.46122281,
                1162619.7297006
            ]

        # Testing with spheroid distances first.
        hillsdale = AustraliaCity.objects.get(name='Hillsdale')
        qs = AustraliaCity.objects.exclude(id=hillsdale.id).distance(
            hillsdale.point, spheroid=True)
        for i, c in enumerate(qs):
            self.assertAlmostEqual(spheroid_distances[i], c.distance.m, tol)
        if postgis:
            # PostGIS uses sphere-only distances by default, testing these as well.
            qs = AustraliaCity.objects.exclude(id=hillsdale.id).distance(
                hillsdale.point)
            for i, c in enumerate(qs):
                self.assertAlmostEqual(sphere_distances[i], c.distance.m, tol)

    @no_oracle  # Oracle already handles geographic distance calculation.
    def test03c_distance_method(self):
        "Testing the `distance` GeoQuerySet method used with `transform` on a geographic field."
        # Normally you can't compute distances from a geometry field
        # that is not a PointField (on PostGIS 1.4 and below).
        if not connection.ops.geography:
            self.assertRaises(ValueError, CensusZipcode.objects.distance,
                              self.stx_pnt)

        # We'll be using a Polygon (created by buffering the centroid
        # of 77005 to 100m) -- which aren't allowed in geographic distance
        # queries normally, however our field has been transformed to
        # a non-geographic system.
        z = SouthTexasZipcode.objects.get(name='77005')

        # Reference query:
        # SELECT ST_Distance(ST_Transform("distapp_censuszipcode"."poly", 32140), ST_GeomFromText('<buffer_wkt>', 32140)) FROM "distapp_censuszipcode";
        dists_m = [3553.30384972258, 1243.18391525602, 2186.15439472242]

        # Having our buffer in the SRID of the transformation and of the field
        # -- should get the same results. The first buffer has no need for
        # transformation SQL because it is the same SRID as what was given
        # to `transform()`.  The second buffer will need to be transformed,
        # however.
        buf1 = z.poly.centroid.buffer(100)
        buf2 = buf1.transform(4269, clone=True)
        ref_zips = ['77002', '77025', '77401']

        for buf in [buf1, buf2]:
            qs = CensusZipcode.objects.exclude(
                name='77005').transform(32140).distance(buf)
            self.assertEqual(ref_zips, self.get_names(qs))
            for i, z in enumerate(qs):
                self.assertAlmostEqual(z.distance.m, dists_m[i], 5)

    def test04_distance_lookups(self):
        "Testing the `distance_lt`, `distance_gt`, `distance_lte`, and `distance_gte` lookup types."
        # Retrieving the cities within a 20km 'donut' w/a 7km radius 'hole'
        # (thus, Houston and Southside place will be excluded as tested in
        # the `test02_dwithin` above).
        qs1 = SouthTexasCity.objects.filter(
            point__distance_gte=(self.stx_pnt, D(km=7))).filter(
                point__distance_lte=(self.stx_pnt, D(km=20)))

        # Can't determine the units on SpatiaLite from PROJ.4 string, and
        # Oracle 11 incorrectly thinks it is not projected.
        if spatialite or oracle:
            dist_qs = (qs1, )
        else:
            qs2 = SouthTexasCityFt.objects.filter(
                point__distance_gte=(self.stx_pnt, D(km=7))).filter(
                    point__distance_lte=(self.stx_pnt, D(km=20)))
            dist_qs = (qs1, qs2)

        for qs in dist_qs:
            cities = self.get_names(qs)
            self.assertEqual(cities,
                             ['Bellaire', 'Pearland', 'West University Place'])

        # Doing a distance query using Polygons instead of a Point.
        z = SouthTexasZipcode.objects.get(name='77005')
        qs = SouthTexasZipcode.objects.exclude(name='77005').filter(
            poly__distance_lte=(z.poly, D(m=275)))
        self.assertEqual(['77025', '77401'], self.get_names(qs))
        # If we add a little more distance 77002 should be included.
        qs = SouthTexasZipcode.objects.exclude(name='77005').filter(
            poly__distance_lte=(z.poly, D(m=300)))
        self.assertEqual(['77002', '77025', '77401'], self.get_names(qs))

    def test05_geodetic_distance_lookups(self):
        "Testing distance lookups on geodetic coordinate systems."
        # Line is from Canberra to Sydney.  Query is for all other cities within
        # a 100km of that line (which should exclude only Hobart & Adelaide).
        line = GEOSGeometry('LINESTRING(144.9630 -37.8143,151.2607 -33.8870)',
                            4326)
        dist_qs = AustraliaCity.objects.filter(point__distance_lte=(line,
                                                                    D(km=100)))

        if oracle or connection.ops.geography:
            # Oracle and PostGIS 1.5 can do distance lookups on arbitrary geometries.
            self.assertEqual(9, dist_qs.count())
            self.assertEqual([
                'Batemans Bay', 'Canberra', 'Hillsdale', 'Melbourne',
                'Mittagong', 'Shellharbour', 'Sydney', 'Thirroul', 'Wollongong'
            ], self.get_names(dist_qs))
        else:
            # PostGIS 1.4 and below only allows geodetic distance queries (utilizing
            # ST_Distance_Sphere/ST_Distance_Spheroid) from Points to PointFields
            # on geometry columns.
            self.assertRaises(ValueError, dist_qs.count)

            # Ensured that a ValueError was raised, none of the rest of the test is
            # support on this backend, so bail now.
            if spatialite: return

        # Too many params (4 in this case) should raise a ValueError.
        self.assertRaises(
            ValueError, len,
            AustraliaCity.objects.filter(point__distance_lte=('POINT(5 23)',
                                                              D(km=100),
                                                              'spheroid',
                                                              '4')))

        # Not enough params should raise a ValueError.
        self.assertRaises(
            ValueError, len,
            AustraliaCity.objects.filter(
                point__distance_lte=('POINT(5 23)', )))

        # Getting all cities w/in 550 miles of Hobart.
        hobart = AustraliaCity.objects.get(name='Hobart')
        qs = AustraliaCity.objects.exclude(name='Hobart').filter(
            point__distance_lte=(hobart.point, D(mi=550)))
        cities = self.get_names(qs)
        self.assertEqual(cities, ['Batemans Bay', 'Canberra', 'Melbourne'])

        # Cities that are either really close or really far from Wollongong --
        # and using different units of distance.
        wollongong = AustraliaCity.objects.get(name='Wollongong')
        d1, d2 = D(yd=19500), D(nm=400)  # Yards (~17km) & Nautical miles.

        # Normal geodetic distance lookup (uses `distance_sphere` on PostGIS.
        gq1 = Q(point__distance_lte=(wollongong.point, d1))
        gq2 = Q(point__distance_gte=(wollongong.point, d2))
        qs1 = AustraliaCity.objects.exclude(name='Wollongong').filter(gq1
                                                                      | gq2)

        # Geodetic distance lookup but telling GeoDjango to use `distance_spheroid`
        # instead (we should get the same results b/c accuracy variance won't matter
        # in this test case).
        if postgis:
            gq3 = Q(point__distance_lte=(wollongong.point, d1, 'spheroid'))
            gq4 = Q(point__distance_gte=(wollongong.point, d2, 'spheroid'))
            qs2 = AustraliaCity.objects.exclude(
                name='Wollongong').filter(gq3 | gq4)
            querysets = [qs1, qs2]
        else:
            querysets = [qs1]

        for qs in querysets:
            cities = self.get_names(qs)
            self.assertEqual(
                cities, ['Adelaide', 'Hobart', 'Shellharbour', 'Thirroul'])

    def test06_area(self):
        "Testing the `area` GeoQuerySet method."
        # Reference queries:
        # SELECT ST_Area(poly) FROM distapp_southtexaszipcode;
        area_sq_m = [
            5437908.90234375, 10183031.4389648, 11254471.0073242,
            9881708.91772461
        ]
        # Tolerance has to be lower for Oracle and differences
        # with GEOS 3.0.0RC4
        tol = 2
        for i, z in enumerate(SouthTexasZipcode.objects.area()):
            self.assertAlmostEqual(area_sq_m[i], z.area.sq_m, tol)

    def test07_length(self):
        "Testing the `length` GeoQuerySet method."
        # Reference query (should use `length_spheroid`).
        # SELECT ST_length_spheroid(ST_GeomFromText('<wkt>', 4326) 'SPHEROID["WGS 84",6378137,298.257223563, AUTHORITY["EPSG","7030"]]');
        len_m1 = 473504.769553813
        len_m2 = 4617.668

        if spatialite:
            # Does not support geodetic coordinate systems.
            self.assertRaises(ValueError, Interstate.objects.length)
        else:
            qs = Interstate.objects.length()
            if oracle: tol = 2
            else: tol = 5
            self.assertAlmostEqual(len_m1, qs[0].length.m, tol)

        # Now doing length on a projected coordinate system.
        i10 = SouthTexasInterstate.objects.length().get(name='I-10')
        self.assertAlmostEqual(len_m2, i10.length.m, 2)

    @no_spatialite
    def test08_perimeter(self):
        "Testing the `perimeter` GeoQuerySet method."
        # Reference query:
        # SELECT ST_Perimeter(distapp_southtexaszipcode.poly) FROM distapp_southtexaszipcode;
        perim_m = [
            18404.3550889361, 15627.2108551001, 20632.5588368978,
            17094.5996143697
        ]
        if oracle: tol = 2
        else: tol = 7
        for i, z in enumerate(SouthTexasZipcode.objects.perimeter()):
            self.assertAlmostEqual(perim_m[i], z.perimeter.m, tol)

        # Running on points; should return 0.
        for i, c in enumerate(
                SouthTexasCity.objects.perimeter(model_att='perim')):
            self.assertEqual(0, c.perim.m)

    def test09_measurement_null_fields(self):
        "Testing the measurement GeoQuerySet methods on fields with NULL values."
        # Creating SouthTexasZipcode w/NULL value.
        SouthTexasZipcode.objects.create(name='78212')
        # Performing distance/area queries against the NULL PolygonField,
        # and ensuring the result of the operations is None.
        htown = SouthTexasCity.objects.get(name='Downtown Houston')
        z = SouthTexasZipcode.objects.distance(
            htown.point).area().get(name='78212')
        self.assertEqual(None, z.distance)
        self.assertEqual(None, z.area)
Esempio n. 19
0
    def test05_geodetic_distance_lookups(self):
        "Testing distance lookups on geodetic coordinate systems."
        # Line is from Canberra to Sydney.  Query is for all other cities within
        # a 100km of that line (which should exclude only Hobart & Adelaide).
        line = GEOSGeometry('LINESTRING(144.9630 -37.8143,151.2607 -33.8870)',
                            4326)
        dist_qs = AustraliaCity.objects.filter(point__distance_lte=(line,
                                                                    D(km=100)))

        if oracle or connection.ops.geography:
            # Oracle and PostGIS 1.5 can do distance lookups on arbitrary geometries.
            self.assertEqual(9, dist_qs.count())
            self.assertEqual([
                'Batemans Bay', 'Canberra', 'Hillsdale', 'Melbourne',
                'Mittagong', 'Shellharbour', 'Sydney', 'Thirroul', 'Wollongong'
            ], self.get_names(dist_qs))
        else:
            # PostGIS 1.4 and below only allows geodetic distance queries (utilizing
            # ST_Distance_Sphere/ST_Distance_Spheroid) from Points to PointFields
            # on geometry columns.
            self.assertRaises(ValueError, dist_qs.count)

            # Ensured that a ValueError was raised, none of the rest of the test is
            # support on this backend, so bail now.
            if spatialite: return

        # Too many params (4 in this case) should raise a ValueError.
        self.assertRaises(
            ValueError, len,
            AustraliaCity.objects.filter(point__distance_lte=('POINT(5 23)',
                                                              D(km=100),
                                                              'spheroid',
                                                              '4')))

        # Not enough params should raise a ValueError.
        self.assertRaises(
            ValueError, len,
            AustraliaCity.objects.filter(
                point__distance_lte=('POINT(5 23)', )))

        # Getting all cities w/in 550 miles of Hobart.
        hobart = AustraliaCity.objects.get(name='Hobart')
        qs = AustraliaCity.objects.exclude(name='Hobart').filter(
            point__distance_lte=(hobart.point, D(mi=550)))
        cities = self.get_names(qs)
        self.assertEqual(cities, ['Batemans Bay', 'Canberra', 'Melbourne'])

        # Cities that are either really close or really far from Wollongong --
        # and using different units of distance.
        wollongong = AustraliaCity.objects.get(name='Wollongong')
        d1, d2 = D(yd=19500), D(nm=400)  # Yards (~17km) & Nautical miles.

        # Normal geodetic distance lookup (uses `distance_sphere` on PostGIS.
        gq1 = Q(point__distance_lte=(wollongong.point, d1))
        gq2 = Q(point__distance_gte=(wollongong.point, d2))
        qs1 = AustraliaCity.objects.exclude(name='Wollongong').filter(gq1
                                                                      | gq2)

        # Geodetic distance lookup but telling GeoDjango to use `distance_spheroid`
        # instead (we should get the same results b/c accuracy variance won't matter
        # in this test case).
        if postgis:
            gq3 = Q(point__distance_lte=(wollongong.point, d1, 'spheroid'))
            gq4 = Q(point__distance_gte=(wollongong.point, d2, 'spheroid'))
            qs2 = AustraliaCity.objects.exclude(
                name='Wollongong').filter(gq3 | gq4)
            querysets = [qs1, qs2]
        else:
            querysets = [qs1]

        for qs in querysets:
            cities = self.get_names(qs)
            self.assertEqual(
                cities, ['Adelaide', 'Hobart', 'Shellharbour', 'Thirroul'])
Esempio n. 20
0
 def geos(self):
     "Returns a GEOSGeometry object from this OGRGeometry."
     from my_django.contrib.gis.geos import GEOSGeometry
     return GEOSGeometry(self.wkb, self.srid)