PageRenderTime 619ms CodeModel.GetById 171ms app.highlight 283ms RepoModel.GetById 159ms app.codeStats 1ms

/django/contrib/gis/tests/distapp/tests.py

https://code.google.com/p/mango-py/
Python | 358 lines | 219 code | 47 blank | 92 comment | 59 complexity | 5cf0854f25e14c3dc758463dece9570e MD5 | raw file
  1import os
  2from decimal import Decimal
  3
  4from django.db import connection
  5from django.db.models import Q
  6from django.contrib.gis.geos import GEOSGeometry, Point, LineString
  7from django.contrib.gis.measure import D # alias for Distance
  8from django.contrib.gis.tests.utils import oracle, postgis, spatialite, no_oracle, no_spatialite
  9from django.test import TestCase
 10
 11from models import AustraliaCity, Interstate, SouthTexasInterstate, \
 12    SouthTexasCity, SouthTexasCityFt, CensusZipcode, SouthTexasZipcode
 13
 14class DistanceTest(TestCase):
 15
 16    # A point we are testing distances with -- using a WGS84
 17    # coordinate that'll be implicitly transormed to that to
 18    # the coordinate system of the field, EPSG:32140 (Texas South Central
 19    # w/units in meters)
 20    stx_pnt = GEOSGeometry('POINT (-95.370401017314293 29.704867409475465)', 4326)
 21    # Another one for Australia
 22    au_pnt = GEOSGeometry('POINT (150.791 -34.4919)', 4326)
 23
 24    def get_names(self, qs):
 25        cities = [c.name for c in qs]
 26        cities.sort()
 27        return cities
 28
 29    def test01_init(self):
 30        "Test initialization of distance models."
 31        self.assertEqual(9, SouthTexasCity.objects.count())
 32        self.assertEqual(9, SouthTexasCityFt.objects.count())
 33        self.assertEqual(11, AustraliaCity.objects.count())
 34        self.assertEqual(4, SouthTexasZipcode.objects.count())
 35        self.assertEqual(4, CensusZipcode.objects.count())
 36        self.assertEqual(1, Interstate.objects.count())
 37        self.assertEqual(1, SouthTexasInterstate.objects.count())
 38
 39    @no_spatialite
 40    def test02_dwithin(self):
 41        "Testing the `dwithin` lookup type."
 42        # Distances -- all should be equal (except for the
 43        # degree/meter pair in au_cities, that's somewhat
 44        # approximate).
 45        tx_dists = [(7000, 22965.83), D(km=7), D(mi=4.349)]
 46        au_dists = [(0.5, 32000), D(km=32), D(mi=19.884)]
 47
 48        # Expected cities for Australia and Texas.
 49        tx_cities = ['Downtown Houston', 'Southside Place']
 50        au_cities = ['Mittagong', 'Shellharbour', 'Thirroul', 'Wollongong']
 51
 52        # Performing distance queries on two projected coordinate systems one
 53        # with units in meters and the other in units of U.S. survey feet.
 54        for dist in tx_dists:
 55            if isinstance(dist, tuple): dist1, dist2 = dist
 56            else: dist1 = dist2 = dist
 57            qs1 = SouthTexasCity.objects.filter(point__dwithin=(self.stx_pnt, dist1))
 58            qs2 = SouthTexasCityFt.objects.filter(point__dwithin=(self.stx_pnt, dist2))
 59            for qs in qs1, qs2:
 60                self.assertEqual(tx_cities, self.get_names(qs))
 61
 62        # Now performing the `dwithin` queries on a geodetic coordinate system.
 63        for dist in au_dists:
 64            if isinstance(dist, D) and not oracle: type_error = True
 65            else: type_error = False
 66
 67            if isinstance(dist, tuple):
 68                if oracle: dist = dist[1]
 69                else: dist = dist[0]
 70
 71            # Creating the query set.
 72            qs = AustraliaCity.objects.order_by('name')
 73            if type_error:
 74                # A ValueError should be raised on PostGIS when trying to pass
 75                # Distance objects into a DWithin query using a geodetic field.
 76                self.assertRaises(ValueError, AustraliaCity.objects.filter(point__dwithin=(self.au_pnt, dist)).count)
 77            else:
 78                self.assertEqual(au_cities, self.get_names(qs.filter(point__dwithin=(self.au_pnt, dist))))
 79
 80    def test03a_distance_method(self):
 81        "Testing the `distance` GeoQuerySet method on projected coordinate systems."
 82        # The point for La Grange, TX
 83        lagrange = GEOSGeometry('POINT(-96.876369 29.905320)', 4326)
 84        # Reference distances in feet and in meters. Got these values from
 85        # using the provided raw SQL statements.
 86        #  SELECT ST_Distance(point, ST_Transform(ST_GeomFromText('POINT(-96.876369 29.905320)', 4326), 32140)) FROM distapp_southtexascity;
 87        m_distances = [147075.069813, 139630.198056, 140888.552826,
 88                       138809.684197, 158309.246259, 212183.594374,
 89                       70870.188967, 165337.758878, 139196.085105]
 90        #  SELECT ST_Distance(point, ST_Transform(ST_GeomFromText('POINT(-96.876369 29.905320)', 4326), 2278)) FROM distapp_southtexascityft;
 91        # Oracle 11 thinks this is not a projected coordinate system, so it's s
 92        # not tested.
 93        ft_distances = [482528.79154625, 458103.408123001, 462231.860397575,
 94                        455411.438904354, 519386.252102563, 696139.009211594,
 95                        232513.278304279, 542445.630586414, 456679.155883207]
 96
 97        # Testing using different variations of parameters and using models
 98        # with different projected coordinate systems.
 99        dist1 = SouthTexasCity.objects.distance(lagrange, field_name='point')
100        dist2 = SouthTexasCity.objects.distance(lagrange)  # Using GEOSGeometry parameter
101        if spatialite or oracle:
102            dist_qs = [dist1, dist2]
103        else:
104            dist3 = SouthTexasCityFt.objects.distance(lagrange.ewkt) # Using EWKT string parameter.
105            dist4 = SouthTexasCityFt.objects.distance(lagrange)
106            dist_qs = [dist1, dist2, dist3, dist4]
107
108        # Original query done on PostGIS, have to adjust AlmostEqual tolerance
109        # for Oracle.
110        if oracle: tol = 2
111        else: tol = 5
112
113        # Ensuring expected distances are returned for each distance queryset.
114        for qs in dist_qs:
115            for i, c in enumerate(qs):
116                self.assertAlmostEqual(m_distances[i], c.distance.m, tol)
117                self.assertAlmostEqual(ft_distances[i], c.distance.survey_ft, tol)
118
119    @no_spatialite
120    def test03b_distance_method(self):
121        "Testing the `distance` GeoQuerySet method on geodetic coordnate systems."
122        if oracle: tol = 2
123        else: tol = 5
124
125        # Testing geodetic distance calculation with a non-point geometry
126        # (a LineString of Wollongong and Shellharbour coords).
127        ls = LineString( ( (150.902, -34.4245), (150.87, -34.5789) ) )
128        if oracle or connection.ops.geography:
129            # Reference query:
130            #  SELECT ST_distance_sphere(point, ST_GeomFromText('LINESTRING(150.9020 -34.4245,150.8700 -34.5789)', 4326)) FROM distapp_australiacity ORDER BY name;
131            distances = [1120954.92533513, 140575.720018241, 640396.662906304,
132                         60580.9693849269, 972807.955955075, 568451.8357838,
133                         40435.4335201384, 0, 68272.3896586844, 12375.0643697706, 0]
134            qs = AustraliaCity.objects.distance(ls).order_by('name')
135            for city, distance in zip(qs, distances):
136                # Testing equivalence to within a meter.
137                self.assertAlmostEqual(distance, city.distance.m, 0)
138        else:
139            # PostGIS 1.4 and below is limited to disance queries only
140            # to/from point geometries, check for raising of ValueError.
141            self.assertRaises(ValueError, AustraliaCity.objects.distance, ls)
142            self.assertRaises(ValueError, AustraliaCity.objects.distance, ls.wkt)
143
144        # Got the reference distances using the raw SQL statements:
145        #  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));
146        #  SELECT ST_distance_sphere(point, ST_GeomFromText('POINT(151.231341 -33.952685)', 4326)) FROM distapp_australiacity WHERE (NOT (id = 11));  st_distance_sphere
147        if connection.ops.postgis and connection.ops.proj_version_tuple() >= (4, 7, 0):
148            # PROJ.4 versions 4.7+ have updated datums, and thus different
149            # distance values.
150            spheroid_distances = [60504.0628957201, 77023.9489850262, 49154.8867574404,
151                                  90847.4358768573, 217402.811919332, 709599.234564757,
152                                  640011.483550888, 7772.00667991925, 1047861.78619339,
153                                  1165126.55236034]
154            sphere_distances = [60580.9693849267, 77144.0435286473, 49199.4415344719,
155                                90804.7533823494, 217713.384600405, 709134.127242793,
156                                639828.157159169, 7786.82949717788, 1049204.06569028,
157                                1162623.7238134]
158
159        else:
160            spheroid_distances = [60504.0628825298, 77023.948962654, 49154.8867507115,
161                                  90847.435881812, 217402.811862568, 709599.234619957,
162                                  640011.483583758, 7772.00667666425, 1047861.7859506,
163                                  1165126.55237647]
164            sphere_distances = [60580.7612632291, 77143.7785056615, 49199.2725132184,
165                                90804.4414289463, 217712.63666124, 709131.691061906,
166                                639825.959074112, 7786.80274606706, 1049200.46122281,
167                                1162619.7297006]
168
169        # Testing with spheroid distances first.
170        hillsdale = AustraliaCity.objects.get(name='Hillsdale')
171        qs = AustraliaCity.objects.exclude(id=hillsdale.id).distance(hillsdale.point, spheroid=True)
172        for i, c in enumerate(qs):
173            self.assertAlmostEqual(spheroid_distances[i], c.distance.m, tol)
174        if postgis:
175            # PostGIS uses sphere-only distances by default, testing these as well.
176            qs =  AustraliaCity.objects.exclude(id=hillsdale.id).distance(hillsdale.point)
177            for i, c in enumerate(qs):
178                self.assertAlmostEqual(sphere_distances[i], c.distance.m, tol)
179
180    @no_oracle # Oracle already handles geographic distance calculation.
181    def test03c_distance_method(self):
182        "Testing the `distance` GeoQuerySet method used with `transform` on a geographic field."
183        # Normally you can't compute distances from a geometry field
184        # that is not a PointField (on PostGIS 1.4 and below).
185        if not connection.ops.geography:
186            self.assertRaises(ValueError, CensusZipcode.objects.distance, self.stx_pnt)
187
188        # We'll be using a Polygon (created by buffering the centroid
189        # of 77005 to 100m) -- which aren't allowed in geographic distance
190        # queries normally, however our field has been transformed to
191        # a non-geographic system.
192        z = SouthTexasZipcode.objects.get(name='77005')
193
194        # Reference query:
195        # SELECT ST_Distance(ST_Transform("distapp_censuszipcode"."poly", 32140), ST_GeomFromText('<buffer_wkt>', 32140)) FROM "distapp_censuszipcode";
196        dists_m = [3553.30384972258, 1243.18391525602, 2186.15439472242]
197
198        # Having our buffer in the SRID of the transformation and of the field
199        # -- should get the same results. The first buffer has no need for
200        # transformation SQL because it is the same SRID as what was given
201        # to `transform()`.  The second buffer will need to be transformed,
202        # however.
203        buf1 = z.poly.centroid.buffer(100)
204        buf2 = buf1.transform(4269, clone=True)
205        ref_zips = ['77002', '77025', '77401']
206
207        for buf in [buf1, buf2]:
208            qs = CensusZipcode.objects.exclude(name='77005').transform(32140).distance(buf)
209            self.assertEqual(ref_zips, self.get_names(qs))
210            for i, z in enumerate(qs):
211                self.assertAlmostEqual(z.distance.m, dists_m[i], 5)
212
213    def test04_distance_lookups(self):
214        "Testing the `distance_lt`, `distance_gt`, `distance_lte`, and `distance_gte` lookup types."
215        # Retrieving the cities within a 20km 'donut' w/a 7km radius 'hole'
216        # (thus, Houston and Southside place will be excluded as tested in
217        # the `test02_dwithin` above).
218        qs1 = SouthTexasCity.objects.filter(point__distance_gte=(self.stx_pnt, D(km=7))).filter(point__distance_lte=(self.stx_pnt, D(km=20)))
219
220        # Can't determine the units on SpatiaLite from PROJ.4 string, and
221        # Oracle 11 incorrectly thinks it is not projected.
222        if spatialite or oracle:
223            dist_qs = (qs1,)
224        else:
225            qs2 = SouthTexasCityFt.objects.filter(point__distance_gte=(self.stx_pnt, D(km=7))).filter(point__distance_lte=(self.stx_pnt, D(km=20)))
226            dist_qs = (qs1, qs2)
227
228        for qs in dist_qs:
229            cities = self.get_names(qs)
230            self.assertEqual(cities, ['Bellaire', 'Pearland', 'West University Place'])
231
232        # Doing a distance query using Polygons instead of a Point.
233        z = SouthTexasZipcode.objects.get(name='77005')
234        qs = SouthTexasZipcode.objects.exclude(name='77005').filter(poly__distance_lte=(z.poly, D(m=275)))
235        self.assertEqual(['77025', '77401'], self.get_names(qs))
236        # If we add a little more distance 77002 should be included.
237        qs = SouthTexasZipcode.objects.exclude(name='77005').filter(poly__distance_lte=(z.poly, D(m=300)))
238        self.assertEqual(['77002', '77025', '77401'], self.get_names(qs))
239
240    def test05_geodetic_distance_lookups(self):
241        "Testing distance lookups on geodetic coordinate systems."
242        # Line is from Canberra to Sydney.  Query is for all other cities within
243        # a 100km of that line (which should exclude only Hobart & Adelaide).
244        line = GEOSGeometry('LINESTRING(144.9630 -37.8143,151.2607 -33.8870)', 4326)
245        dist_qs = AustraliaCity.objects.filter(point__distance_lte=(line, D(km=100)))
246
247        if oracle or connection.ops.geography:
248            # Oracle and PostGIS 1.5 can do distance lookups on arbitrary geometries.
249            self.assertEqual(9, dist_qs.count())
250            self.assertEqual(['Batemans Bay', 'Canberra', 'Hillsdale',
251                              'Melbourne', 'Mittagong', 'Shellharbour',
252                              'Sydney', 'Thirroul', 'Wollongong'],
253                             self.get_names(dist_qs))
254        else:
255            # PostGIS 1.4 and below only allows geodetic distance queries (utilizing
256            # ST_Distance_Sphere/ST_Distance_Spheroid) from Points to PointFields
257            # on geometry columns.
258            self.assertRaises(ValueError, dist_qs.count)
259
260            # Ensured that a ValueError was raised, none of the rest of the test is
261            # support on this backend, so bail now.
262            if spatialite: return
263
264        # Too many params (4 in this case) should raise a ValueError.
265        self.assertRaises(ValueError, len,
266                          AustraliaCity.objects.filter(point__distance_lte=('POINT(5 23)', D(km=100), 'spheroid', '4')))
267
268        # Not enough params should raise a ValueError.
269        self.assertRaises(ValueError, len,
270                          AustraliaCity.objects.filter(point__distance_lte=('POINT(5 23)',)))
271
272        # Getting all cities w/in 550 miles of Hobart.
273        hobart = AustraliaCity.objects.get(name='Hobart')
274        qs = AustraliaCity.objects.exclude(name='Hobart').filter(point__distance_lte=(hobart.point, D(mi=550)))
275        cities = self.get_names(qs)
276        self.assertEqual(cities, ['Batemans Bay', 'Canberra', 'Melbourne'])
277
278        # Cities that are either really close or really far from Wollongong --
279        # and using different units of distance.
280        wollongong = AustraliaCity.objects.get(name='Wollongong')
281        d1, d2 = D(yd=19500), D(nm=400) # Yards (~17km) & Nautical miles.
282
283        # Normal geodetic distance lookup (uses `distance_sphere` on PostGIS.
284        gq1 = Q(point__distance_lte=(wollongong.point, d1))
285        gq2 = Q(point__distance_gte=(wollongong.point, d2))
286        qs1 = AustraliaCity.objects.exclude(name='Wollongong').filter(gq1 | gq2)
287
288        # Geodetic distance lookup but telling GeoDjango to use `distance_spheroid`
289        # instead (we should get the same results b/c accuracy variance won't matter
290        # in this test case).
291        if postgis:
292            gq3 = Q(point__distance_lte=(wollongong.point, d1, 'spheroid'))
293            gq4 = Q(point__distance_gte=(wollongong.point, d2, 'spheroid'))
294            qs2 = AustraliaCity.objects.exclude(name='Wollongong').filter(gq3 | gq4)
295            querysets = [qs1, qs2]
296        else:
297            querysets = [qs1]
298
299        for qs in querysets:
300            cities = self.get_names(qs)
301            self.assertEqual(cities, ['Adelaide', 'Hobart', 'Shellharbour', 'Thirroul'])
302
303    def test06_area(self):
304        "Testing the `area` GeoQuerySet method."
305        # Reference queries:
306        # SELECT ST_Area(poly) FROM distapp_southtexaszipcode;
307        area_sq_m = [5437908.90234375, 10183031.4389648, 11254471.0073242, 9881708.91772461]
308        # Tolerance has to be lower for Oracle and differences
309        # with GEOS 3.0.0RC4
310        tol = 2
311        for i, z in enumerate(SouthTexasZipcode.objects.area()):
312            self.assertAlmostEqual(area_sq_m[i], z.area.sq_m, tol)
313
314    def test07_length(self):
315        "Testing the `length` GeoQuerySet method."
316        # Reference query (should use `length_spheroid`).
317        # SELECT ST_length_spheroid(ST_GeomFromText('<wkt>', 4326) 'SPHEROID["WGS 84",6378137,298.257223563, AUTHORITY["EPSG","7030"]]');
318        len_m1 = 473504.769553813
319        len_m2 = 4617.668
320
321        if spatialite:
322            # Does not support geodetic coordinate systems.
323            self.assertRaises(ValueError, Interstate.objects.length)
324        else:
325            qs = Interstate.objects.length()
326            if oracle: tol = 2
327            else: tol = 5
328            self.assertAlmostEqual(len_m1, qs[0].length.m, tol)
329
330        # Now doing length on a projected coordinate system.
331        i10 = SouthTexasInterstate.objects.length().get(name='I-10')
332        self.assertAlmostEqual(len_m2, i10.length.m, 2)
333
334    @no_spatialite
335    def test08_perimeter(self):
336        "Testing the `perimeter` GeoQuerySet method."
337        # Reference query:
338        # SELECT ST_Perimeter(distapp_southtexaszipcode.poly) FROM distapp_southtexaszipcode;
339        perim_m = [18404.3550889361, 15627.2108551001, 20632.5588368978, 17094.5996143697]
340        if oracle: tol = 2
341        else: tol = 7
342        for i, z in enumerate(SouthTexasZipcode.objects.perimeter()):
343            self.assertAlmostEqual(perim_m[i], z.perimeter.m, tol)
344
345        # Running on points; should return 0.
346        for i, c in enumerate(SouthTexasCity.objects.perimeter(model_att='perim')):
347            self.assertEqual(0, c.perim.m)
348
349    def test09_measurement_null_fields(self):
350        "Testing the measurement GeoQuerySet methods on fields with NULL values."
351        # Creating SouthTexasZipcode w/NULL value.
352        SouthTexasZipcode.objects.create(name='78212')
353        # Performing distance/area queries against the NULL PolygonField,
354        # and ensuring the result of the operations is None.
355        htown = SouthTexasCity.objects.get(name='Downtown Houston')
356        z = SouthTexasZipcode.objects.distance(htown.point).area().get(name='78212')
357        self.assertEqual(None, z.distance)
358        self.assertEqual(None, z.area)