tests.py 19 KB

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