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