PageRenderTime 25ms CodeModel.GetById 6ms RepoModel.GetById 0ms app.codeStats 0ms

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

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