tests.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. from __future__ import unicode_literals
  2. from django.contrib.gis.db.models.functions import (
  3. Area, Distance, Length, Perimeter, Transform,
  4. )
  5. from django.contrib.gis.geos import GEOSGeometry, LineString, Point
  6. from django.contrib.gis.measure import D # alias for Distance
  7. from django.db import connection
  8. from django.db.models import Q
  9. from django.test import TestCase, ignore_warnings, skipUnlessDBFeature
  10. from django.utils.deprecation import RemovedInDjango20Warning
  11. from ..utils import no_oracle, oracle, postgis, spatialite
  12. from .models import (
  13. AustraliaCity, CensusZipcode, Interstate, SouthTexasCity, SouthTexasCityFt,
  14. SouthTexasInterstate, SouthTexasZipcode,
  15. )
  16. @skipUnlessDBFeature("gis_enabled")
  17. class DistanceTest(TestCase):
  18. fixtures = ['initial']
  19. def setUp(self):
  20. # A point we are testing distances with -- using a WGS84
  21. # coordinate that'll be implicitly transformed to that to
  22. # the coordinate system of the field, EPSG:32140 (Texas South Central
  23. # w/units in meters)
  24. self.stx_pnt = GEOSGeometry('POINT (-95.370401017314293 29.704867409475465)', 4326)
  25. # Another one for Australia
  26. self.au_pnt = GEOSGeometry('POINT (150.791 -34.4919)', 4326)
  27. def get_names(self, qs):
  28. cities = [c.name for c in qs]
  29. cities.sort()
  30. return cities
  31. def test_init(self):
  32. """
  33. Test initialization of distance models.
  34. """
  35. self.assertEqual(9, SouthTexasCity.objects.count())
  36. self.assertEqual(9, SouthTexasCityFt.objects.count())
  37. self.assertEqual(11, AustraliaCity.objects.count())
  38. self.assertEqual(4, SouthTexasZipcode.objects.count())
  39. self.assertEqual(4, CensusZipcode.objects.count())
  40. self.assertEqual(1, Interstate.objects.count())
  41. self.assertEqual(1, SouthTexasInterstate.objects.count())
  42. @skipUnlessDBFeature("supports_dwithin_lookup")
  43. def test_dwithin(self):
  44. """
  45. Test the `dwithin` lookup type.
  46. """
  47. # Distances -- all should be equal (except for the
  48. # degree/meter pair in au_cities, that's somewhat
  49. # approximate).
  50. tx_dists = [(7000, 22965.83), D(km=7), D(mi=4.349)]
  51. au_dists = [(0.5, 32000), D(km=32), D(mi=19.884)]
  52. # Expected cities for Australia and Texas.
  53. tx_cities = ['Downtown Houston', 'Southside Place']
  54. au_cities = ['Mittagong', 'Shellharbour', 'Thirroul', 'Wollongong']
  55. # Performing distance queries on two projected coordinate systems one
  56. # with units in meters and the other in units of U.S. survey feet.
  57. for dist in tx_dists:
  58. if isinstance(dist, tuple):
  59. dist1, dist2 = dist
  60. else:
  61. dist1 = dist2 = dist
  62. qs1 = SouthTexasCity.objects.filter(point__dwithin=(self.stx_pnt, dist1))
  63. qs2 = SouthTexasCityFt.objects.filter(point__dwithin=(self.stx_pnt, dist2))
  64. for qs in qs1, qs2:
  65. self.assertEqual(tx_cities, self.get_names(qs))
  66. # Now performing the `dwithin` queries on a geodetic coordinate system.
  67. for dist in au_dists:
  68. if isinstance(dist, D) and not oracle:
  69. type_error = True
  70. else:
  71. type_error = False
  72. if isinstance(dist, tuple):
  73. if oracle:
  74. dist = dist[1]
  75. else:
  76. dist = dist[0]
  77. # Creating the query set.
  78. qs = AustraliaCity.objects.order_by('name')
  79. if type_error:
  80. # A ValueError should be raised on PostGIS when trying to pass
  81. # Distance objects into a DWithin query using a geodetic field.
  82. self.assertRaises(ValueError, AustraliaCity.objects.filter(point__dwithin=(self.au_pnt, dist)).count)
  83. else:
  84. self.assertListEqual(au_cities, self.get_names(qs.filter(point__dwithin=(self.au_pnt, dist))))
  85. @skipUnlessDBFeature("has_distance_method")
  86. @ignore_warnings(category=RemovedInDjango20Warning)
  87. def test_distance_projected(self):
  88. """
  89. Test the `distance` GeoQuerySet method on projected coordinate systems.
  90. """
  91. # The point for La Grange, TX
  92. lagrange = GEOSGeometry('POINT(-96.876369 29.905320)', 4326)
  93. # Reference distances in feet and in meters. Got these values from
  94. # using the provided raw SQL statements.
  95. # SELECT ST_Distance(point, ST_Transform(ST_GeomFromText('POINT(-96.876369 29.905320)', 4326), 32140))
  96. # FROM distapp_southtexascity;
  97. m_distances = [147075.069813, 139630.198056, 140888.552826,
  98. 138809.684197, 158309.246259, 212183.594374,
  99. 70870.188967, 165337.758878, 139196.085105]
  100. # SELECT ST_Distance(point, ST_Transform(ST_GeomFromText('POINT(-96.876369 29.905320)', 4326), 2278))
  101. # FROM distapp_southtexascityft;
  102. # Oracle 11 thinks this is not a projected coordinate system, so it's
  103. # not tested.
  104. ft_distances = [482528.79154625, 458103.408123001, 462231.860397575,
  105. 455411.438904354, 519386.252102563, 696139.009211594,
  106. 232513.278304279, 542445.630586414, 456679.155883207]
  107. # Testing using different variations of parameters and using models
  108. # with different projected coordinate systems.
  109. dist1 = SouthTexasCity.objects.distance(lagrange, field_name='point').order_by('id')
  110. dist2 = SouthTexasCity.objects.distance(lagrange).order_by('id') # Using GEOSGeometry parameter
  111. if spatialite or oracle:
  112. dist_qs = [dist1, dist2]
  113. else:
  114. dist3 = SouthTexasCityFt.objects.distance(lagrange.ewkt).order_by('id') # Using EWKT string parameter.
  115. dist4 = SouthTexasCityFt.objects.distance(lagrange).order_by('id')
  116. dist_qs = [dist1, dist2, dist3, dist4]
  117. # Original query done on PostGIS, have to adjust AlmostEqual tolerance
  118. # for Oracle.
  119. tol = 2 if oracle else 5
  120. # Ensuring expected distances are returned for each distance queryset.
  121. for qs in dist_qs:
  122. for i, c in enumerate(qs):
  123. self.assertAlmostEqual(m_distances[i], c.distance.m, tol)
  124. self.assertAlmostEqual(ft_distances[i], c.distance.survey_ft, tol)
  125. @skipUnlessDBFeature("has_distance_method", "supports_distance_geodetic")
  126. @ignore_warnings(category=RemovedInDjango20Warning)
  127. def test_distance_geodetic(self):
  128. """
  129. Test the `distance` GeoQuerySet method on geodetic coordinate systems.
  130. """
  131. tol = 2 if oracle else 5
  132. # Testing geodetic distance calculation with a non-point geometry
  133. # (a LineString of Wollongong and Shellharbour coords).
  134. ls = LineString(((150.902, -34.4245), (150.87, -34.5789)))
  135. # Reference query:
  136. # SELECT ST_distance_sphere(point, ST_GeomFromText('LINESTRING(150.9020 -34.4245,150.8700 -34.5789)', 4326))
  137. # FROM distapp_australiacity ORDER BY name;
  138. distances = [1120954.92533513, 140575.720018241, 640396.662906304,
  139. 60580.9693849269, 972807.955955075, 568451.8357838,
  140. 40435.4335201384, 0, 68272.3896586844, 12375.0643697706, 0]
  141. qs = AustraliaCity.objects.distance(ls).order_by('name')
  142. for city, distance in zip(qs, distances):
  143. # Testing equivalence to within a meter.
  144. self.assertAlmostEqual(distance, city.distance.m, 0)
  145. # Got the reference distances using the raw SQL statements:
  146. # SELECT ST_distance_spheroid(point, ST_GeomFromText('POINT(151.231341 -33.952685)', 4326),
  147. # 'SPHEROID["WGS 84",6378137.0,298.257223563]') FROM distapp_australiacity WHERE (NOT (id = 11));
  148. # SELECT ST_distance_sphere(point, ST_GeomFromText('POINT(151.231341 -33.952685)', 4326))
  149. # FROM distapp_australiacity WHERE (NOT (id = 11)); st_distance_sphere
  150. if connection.ops.postgis and connection.ops.proj_version_tuple() >= (4, 7, 0):
  151. # PROJ.4 versions 4.7+ have updated datums, and thus different
  152. # distance values.
  153. spheroid_distances = [60504.0628957201, 77023.9489850262, 49154.8867574404,
  154. 90847.4358768573, 217402.811919332, 709599.234564757,
  155. 640011.483550888, 7772.00667991925, 1047861.78619339,
  156. 1165126.55236034]
  157. sphere_distances = [60580.9693849267, 77144.0435286473, 49199.4415344719,
  158. 90804.7533823494, 217713.384600405, 709134.127242793,
  159. 639828.157159169, 7786.82949717788, 1049204.06569028,
  160. 1162623.7238134]
  161. else:
  162. spheroid_distances = [60504.0628825298, 77023.948962654, 49154.8867507115,
  163. 90847.435881812, 217402.811862568, 709599.234619957,
  164. 640011.483583758, 7772.00667666425, 1047861.7859506,
  165. 1165126.55237647]
  166. sphere_distances = [60580.7612632291, 77143.7785056615, 49199.2725132184,
  167. 90804.4414289463, 217712.63666124, 709131.691061906,
  168. 639825.959074112, 7786.80274606706, 1049200.46122281,
  169. 1162619.7297006]
  170. # Testing with spheroid distances first.
  171. hillsdale = AustraliaCity.objects.get(name='Hillsdale')
  172. qs = AustraliaCity.objects.exclude(id=hillsdale.id).distance(hillsdale.point, spheroid=True).order_by('id')
  173. for i, c in enumerate(qs):
  174. self.assertAlmostEqual(spheroid_distances[i], c.distance.m, tol)
  175. if postgis:
  176. # PostGIS uses sphere-only distances by default, testing these as well.
  177. qs = AustraliaCity.objects.exclude(id=hillsdale.id).distance(hillsdale.point).order_by('id')
  178. for i, c in enumerate(qs):
  179. self.assertAlmostEqual(sphere_distances[i], c.distance.m, tol)
  180. @no_oracle # Oracle already handles geographic distance calculation.
  181. @skipUnlessDBFeature("has_distance_method")
  182. @ignore_warnings(category=RemovedInDjango20Warning)
  183. def test_distance_transform(self):
  184. """
  185. Test the `distance` GeoQuerySet method used with `transform` on a geographic field.
  186. """
  187. # We'll be using a Polygon (created by buffering the centroid
  188. # of 77005 to 100m) -- which aren't allowed in geographic distance
  189. # queries normally, however our field has been transformed to
  190. # a non-geographic system.
  191. z = SouthTexasZipcode.objects.get(name='77005')
  192. # Reference query:
  193. # SELECT ST_Distance(ST_Transform("distapp_censuszipcode"."poly", 32140),
  194. # ST_GeomFromText('<buffer_wkt>', 32140))
  195. # FROM "distapp_censuszipcode";
  196. dists_m = [3553.30384972258, 1243.18391525602, 2186.15439472242]
  197. # Having our buffer in the SRID of the transformation and of the field
  198. # -- should get the same results. The first buffer has no need for
  199. # transformation SQL because it is the same SRID as what was given
  200. # to `transform()`. The second buffer will need to be transformed,
  201. # however.
  202. buf1 = z.poly.centroid.buffer(100)
  203. buf2 = buf1.transform(4269, clone=True)
  204. ref_zips = ['77002', '77025', '77401']
  205. for buf in [buf1, buf2]:
  206. qs = CensusZipcode.objects.exclude(name='77005').transform(32140).distance(buf).order_by('name')
  207. self.assertListEqual(ref_zips, self.get_names(qs))
  208. for i, z in enumerate(qs):
  209. self.assertAlmostEqual(z.distance.m, dists_m[i], 5)
  210. @skipUnlessDBFeature("supports_distances_lookups")
  211. def test_distance_lookups(self):
  212. """
  213. Test the `distance_lt`, `distance_gt`, `distance_lte`, and `distance_gte` lookup types.
  214. """
  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(
  219. point__distance_lte=(self.stx_pnt, D(km=20)),
  220. )
  221. # Can't determine the units on SpatiaLite from PROJ.4 string, and
  222. # Oracle 11 incorrectly thinks it is not projected.
  223. if spatialite or oracle:
  224. dist_qs = (qs1,)
  225. else:
  226. qs2 = SouthTexasCityFt.objects.filter(point__distance_gte=(self.stx_pnt, D(km=7))).filter(
  227. point__distance_lte=(self.stx_pnt, D(km=20)),
  228. )
  229. dist_qs = (qs1, qs2)
  230. for qs in dist_qs:
  231. cities = self.get_names(qs)
  232. self.assertEqual(cities, ['Bellaire', 'Pearland', 'West University Place'])
  233. # Doing a distance query using Polygons instead of a Point.
  234. z = SouthTexasZipcode.objects.get(name='77005')
  235. qs = SouthTexasZipcode.objects.exclude(name='77005').filter(poly__distance_lte=(z.poly, D(m=275)))
  236. self.assertEqual(['77025', '77401'], self.get_names(qs))
  237. # If we add a little more distance 77002 should be included.
  238. qs = SouthTexasZipcode.objects.exclude(name='77005').filter(poly__distance_lte=(z.poly, D(m=300)))
  239. self.assertEqual(['77002', '77025', '77401'], self.get_names(qs))
  240. @skipUnlessDBFeature("supports_distances_lookups", "supports_distance_geodetic")
  241. def test_geodetic_distance_lookups(self):
  242. """
  243. Test distance lookups on geodetic coordinate systems.
  244. """
  245. # Line is from Canberra to Sydney. Query is for all other cities within
  246. # a 100km of that line (which should exclude only Hobart & Adelaide).
  247. line = GEOSGeometry('LINESTRING(144.9630 -37.8143,151.2607 -33.8870)', 4326)
  248. dist_qs = AustraliaCity.objects.filter(point__distance_lte=(line, D(km=100)))
  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. # Too many params (4 in this case) should raise a ValueError.
  255. queryset = AustraliaCity.objects.filter(point__distance_lte=('POINT(5 23)', D(km=100), 'spheroid', '4'))
  256. self.assertRaises(ValueError, len, queryset)
  257. # Not enough params should raise a ValueError.
  258. self.assertRaises(ValueError, len,
  259. AustraliaCity.objects.filter(point__distance_lte=('POINT(5 23)',)))
  260. # Getting all cities w/in 550 miles of Hobart.
  261. hobart = AustraliaCity.objects.get(name='Hobart')
  262. qs = AustraliaCity.objects.exclude(name='Hobart').filter(point__distance_lte=(hobart.point, D(mi=550)))
  263. cities = self.get_names(qs)
  264. self.assertEqual(cities, ['Batemans Bay', 'Canberra', 'Melbourne'])
  265. # Cities that are either really close or really far from Wollongong --
  266. # and using different units of distance.
  267. wollongong = AustraliaCity.objects.get(name='Wollongong')
  268. d1, d2 = D(yd=19500), D(nm=400) # Yards (~17km) & Nautical miles.
  269. # Normal geodetic distance lookup (uses `distance_sphere` on PostGIS.
  270. gq1 = Q(point__distance_lte=(wollongong.point, d1))
  271. gq2 = Q(point__distance_gte=(wollongong.point, d2))
  272. qs1 = AustraliaCity.objects.exclude(name='Wollongong').filter(gq1 | gq2)
  273. # Geodetic distance lookup but telling GeoDjango to use `distance_spheroid`
  274. # instead (we should get the same results b/c accuracy variance won't matter
  275. # in this test case).
  276. querysets = [qs1]
  277. if connection.features.has_distance_spheroid_method:
  278. gq3 = Q(point__distance_lte=(wollongong.point, d1, 'spheroid'))
  279. gq4 = Q(point__distance_gte=(wollongong.point, d2, 'spheroid'))
  280. qs2 = AustraliaCity.objects.exclude(name='Wollongong').filter(gq3 | gq4)
  281. querysets.append(qs2)
  282. for qs in querysets:
  283. cities = self.get_names(qs)
  284. self.assertEqual(cities, ['Adelaide', 'Hobart', 'Shellharbour', 'Thirroul'])
  285. @skipUnlessDBFeature("has_area_method")
  286. @ignore_warnings(category=RemovedInDjango20Warning)
  287. def test_area(self):
  288. """
  289. Test the `area` GeoQuerySet method.
  290. """
  291. # Reference queries:
  292. # SELECT ST_Area(poly) FROM distapp_southtexaszipcode;
  293. area_sq_m = [5437908.90234375, 10183031.4389648, 11254471.0073242, 9881708.91772461]
  294. # Tolerance has to be lower for Oracle
  295. tol = 2
  296. for i, z in enumerate(SouthTexasZipcode.objects.order_by('name').area()):
  297. self.assertAlmostEqual(area_sq_m[i], z.area.sq_m, tol)
  298. @skipUnlessDBFeature("has_length_method")
  299. @ignore_warnings(category=RemovedInDjango20Warning)
  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,
  306. # AUTHORITY["EPSG","7030"]]');
  307. len_m1 = 473504.769553813
  308. len_m2 = 4617.668
  309. if connection.features.supports_distance_geodetic:
  310. qs = Interstate.objects.length()
  311. tol = 2 if oracle else 3
  312. self.assertAlmostEqual(len_m1, qs[0].length.m, tol)
  313. else:
  314. # Does not support geodetic coordinate systems.
  315. self.assertRaises(ValueError, Interstate.objects.length)
  316. # Now doing length on a projected coordinate system.
  317. i10 = SouthTexasInterstate.objects.length().get(name='I-10')
  318. self.assertAlmostEqual(len_m2, i10.length.m, 2)
  319. @skipUnlessDBFeature("has_perimeter_method")
  320. @ignore_warnings(category=RemovedInDjango20Warning)
  321. def test_perimeter(self):
  322. """
  323. Test the `perimeter` GeoQuerySet method.
  324. """
  325. # Reference query:
  326. # SELECT ST_Perimeter(distapp_southtexaszipcode.poly) FROM distapp_southtexaszipcode;
  327. perim_m = [18404.3550889361, 15627.2108551001, 20632.5588368978, 17094.5996143697]
  328. tol = 2 if oracle else 7
  329. for i, z in enumerate(SouthTexasZipcode.objects.order_by('name').perimeter()):
  330. self.assertAlmostEqual(perim_m[i], z.perimeter.m, tol)
  331. # Running on points; should return 0.
  332. for i, c in enumerate(SouthTexasCity.objects.perimeter(model_att='perim')):
  333. self.assertEqual(0, c.perim.m)
  334. @skipUnlessDBFeature("has_area_method", "has_distance_method")
  335. @ignore_warnings(category=RemovedInDjango20Warning)
  336. def test_measurement_null_fields(self):
  337. """
  338. Test the measurement GeoQuerySet methods on fields with NULL values.
  339. """
  340. # Creating SouthTexasZipcode w/NULL value.
  341. SouthTexasZipcode.objects.create(name='78212')
  342. # Performing distance/area queries against the NULL PolygonField,
  343. # and ensuring the result of the operations is None.
  344. htown = SouthTexasCity.objects.get(name='Downtown Houston')
  345. z = SouthTexasZipcode.objects.distance(htown.point).area().get(name='78212')
  346. self.assertIsNone(z.distance)
  347. self.assertIsNone(z.area)
  348. @skipUnlessDBFeature("has_distance_method")
  349. @ignore_warnings(category=RemovedInDjango20Warning)
  350. def test_distance_order_by(self):
  351. qs = SouthTexasCity.objects.distance(Point(3, 3)).order_by(
  352. 'distance'
  353. ).values_list('name', flat=True).filter(name__in=('San Antonio', 'Pearland'))
  354. self.assertQuerysetEqual(qs, ['San Antonio', 'Pearland'], lambda x: x)
  355. '''
  356. =============================
  357. Distance functions on PostGIS
  358. =============================
  359. | Projected Geometry | Lon/lat Geometry | Geography (4326)
  360. ST_Distance(geom1, geom2) | OK (meters) | :-( (degrees) | OK (meters)
  361. ST_Distance(geom1, geom2, use_spheroid=False) | N/A | N/A | OK (meters), less accurate, quick
  362. Distance_Sphere(geom1, geom2) | N/A | OK (meters) | N/A
  363. Distance_Spheroid(geom1, geom2, spheroid) | N/A | OK (meters) | N/A
  364. ================================
  365. Distance functions on Spatialite
  366. ================================
  367. | Projected Geometry | Lon/lat Geometry
  368. ST_Distance(geom1, geom2) | OK (meters) | N/A
  369. ST_Distance(geom1, geom2, use_ellipsoid=True) | N/A | OK (meters)
  370. ST_Distance(geom1, geom2, use_ellipsoid=False) | N/A | OK (meters), less accurate, quick
  371. '''
  372. @skipUnlessDBFeature("gis_enabled")
  373. class DistanceFunctionsTests(TestCase):
  374. fixtures = ['initial']
  375. @skipUnlessDBFeature("has_Area_function")
  376. def test_area(self):
  377. # Reference queries:
  378. # SELECT ST_Area(poly) FROM distapp_southtexaszipcode;
  379. area_sq_m = [5437908.90234375, 10183031.4389648, 11254471.0073242, 9881708.91772461]
  380. # Tolerance has to be lower for Oracle
  381. tol = 2
  382. for i, z in enumerate(SouthTexasZipcode.objects.annotate(area=Area('poly')).order_by('name')):
  383. # MySQL is returning a raw float value
  384. self.assertAlmostEqual(area_sq_m[i], z.area.sq_m if hasattr(z.area, 'sq_m') else z.area, tol)
  385. @skipUnlessDBFeature("has_Distance_function")
  386. def test_distance_simple(self):
  387. """
  388. Test a simple distance query, with projected coordinates and without
  389. transformation.
  390. """
  391. lagrange = GEOSGeometry('POINT(805066.295722839 4231496.29461335)', 32140)
  392. houston = SouthTexasCity.objects.annotate(dist=Distance('point', lagrange)).order_by('id').first()
  393. tol = 2 if oracle else 5
  394. self.assertAlmostEqual(
  395. houston.dist.m if hasattr(houston.dist, 'm') else houston.dist,
  396. 147075.069813,
  397. tol
  398. )
  399. @skipUnlessDBFeature("has_Distance_function", "has_Transform_function")
  400. def test_distance_projected(self):
  401. """
  402. Test the `Distance` function on projected coordinate systems.
  403. """
  404. # The point for La Grange, TX
  405. lagrange = GEOSGeometry('POINT(-96.876369 29.905320)', 4326)
  406. # Reference distances in feet and in meters. Got these values from
  407. # using the provided raw SQL statements.
  408. # SELECT ST_Distance(point, ST_Transform(ST_GeomFromText('POINT(-96.876369 29.905320)', 4326), 32140))
  409. # FROM distapp_southtexascity;
  410. m_distances = [147075.069813, 139630.198056, 140888.552826,
  411. 138809.684197, 158309.246259, 212183.594374,
  412. 70870.188967, 165337.758878, 139196.085105]
  413. # SELECT ST_Distance(point, ST_Transform(ST_GeomFromText('POINT(-96.876369 29.905320)', 4326), 2278))
  414. # FROM distapp_southtexascityft;
  415. # Oracle 11 thinks this is not a projected coordinate system, so it's
  416. # not tested.
  417. ft_distances = [482528.79154625, 458103.408123001, 462231.860397575,
  418. 455411.438904354, 519386.252102563, 696139.009211594,
  419. 232513.278304279, 542445.630586414, 456679.155883207]
  420. # Testing using different variations of parameters and using models
  421. # with different projected coordinate systems.
  422. dist1 = SouthTexasCity.objects.annotate(distance=Distance('point', lagrange)).order_by('id')
  423. if spatialite or oracle:
  424. dist_qs = [dist1]
  425. else:
  426. dist2 = SouthTexasCityFt.objects.annotate(distance=Distance('point', lagrange)).order_by('id')
  427. # Using EWKT string parameter.
  428. dist3 = SouthTexasCityFt.objects.annotate(distance=Distance('point', lagrange.ewkt)).order_by('id')
  429. dist_qs = [dist1, dist2, dist3]
  430. # Original query done on PostGIS, have to adjust AlmostEqual tolerance
  431. # for Oracle.
  432. tol = 2 if oracle else 5
  433. # Ensuring expected distances are returned for each distance queryset.
  434. for qs in dist_qs:
  435. for i, c in enumerate(qs):
  436. self.assertAlmostEqual(m_distances[i], c.distance.m, tol)
  437. self.assertAlmostEqual(ft_distances[i], c.distance.survey_ft, tol)
  438. @skipUnlessDBFeature("has_Distance_function", "supports_distance_geodetic")
  439. def test_distance_geodetic(self):
  440. """
  441. Test the `Distance` function on geodetic coordinate systems.
  442. """
  443. # Testing geodetic distance calculation with a non-point geometry
  444. # (a LineString of Wollongong and Shellharbour coords).
  445. ls = LineString(((150.902, -34.4245), (150.87, -34.5789)), srid=4326)
  446. # Reference query:
  447. # SELECT ST_distance_sphere(point, ST_GeomFromText('LINESTRING(150.9020 -34.4245,150.8700 -34.5789)', 4326))
  448. # FROM distapp_australiacity ORDER BY name;
  449. distances = [1120954.92533513, 140575.720018241, 640396.662906304,
  450. 60580.9693849269, 972807.955955075, 568451.8357838,
  451. 40435.4335201384, 0, 68272.3896586844, 12375.0643697706, 0]
  452. qs = AustraliaCity.objects.annotate(distance=Distance('point', ls)).order_by('name')
  453. for city, distance in zip(qs, distances):
  454. # Testing equivalence to within a meter.
  455. self.assertAlmostEqual(distance, city.distance.m, 0)
  456. @skipUnlessDBFeature("has_Distance_function", "supports_distance_geodetic")
  457. def test_distance_geodetic_spheroid(self):
  458. tol = 2 if oracle else 5
  459. # Got the reference distances using the raw SQL statements:
  460. # SELECT ST_distance_spheroid(point, ST_GeomFromText('POINT(151.231341 -33.952685)', 4326),
  461. # 'SPHEROID["WGS 84",6378137.0,298.257223563]') FROM distapp_australiacity WHERE (NOT (id = 11));
  462. # SELECT ST_distance_sphere(point, ST_GeomFromText('POINT(151.231341 -33.952685)', 4326))
  463. # FROM distapp_australiacity WHERE (NOT (id = 11)); st_distance_sphere
  464. if connection.ops.postgis and connection.ops.proj_version_tuple() >= (4, 7, 0):
  465. # PROJ.4 versions 4.7+ have updated datums, and thus different
  466. # distance values.
  467. spheroid_distances = [60504.0628957201, 77023.9489850262, 49154.8867574404,
  468. 90847.4358768573, 217402.811919332, 709599.234564757,
  469. 640011.483550888, 7772.00667991925, 1047861.78619339,
  470. 1165126.55236034]
  471. sphere_distances = [60580.9693849267, 77144.0435286473, 49199.4415344719,
  472. 90804.7533823494, 217713.384600405, 709134.127242793,
  473. 639828.157159169, 7786.82949717788, 1049204.06569028,
  474. 1162623.7238134]
  475. else:
  476. spheroid_distances = [60504.0628825298, 77023.948962654, 49154.8867507115,
  477. 90847.435881812, 217402.811862568, 709599.234619957,
  478. 640011.483583758, 7772.00667666425, 1047861.7859506,
  479. 1165126.55237647]
  480. sphere_distances = [60580.7612632291, 77143.7785056615, 49199.2725132184,
  481. 90804.4414289463, 217712.63666124, 709131.691061906,
  482. 639825.959074112, 7786.80274606706, 1049200.46122281,
  483. 1162619.7297006]
  484. # Testing with spheroid distances first.
  485. hillsdale = AustraliaCity.objects.get(name='Hillsdale')
  486. qs = AustraliaCity.objects.exclude(id=hillsdale.id).annotate(
  487. distance=Distance('point', hillsdale.point, spheroid=True)
  488. ).order_by('id')
  489. for i, c in enumerate(qs):
  490. self.assertAlmostEqual(spheroid_distances[i], c.distance.m, tol)
  491. if postgis:
  492. # PostGIS uses sphere-only distances by default, testing these as well.
  493. qs = AustraliaCity.objects.exclude(id=hillsdale.id).annotate(
  494. distance=Distance('point', hillsdale.point)
  495. ).order_by('id')
  496. for i, c in enumerate(qs):
  497. self.assertAlmostEqual(sphere_distances[i], c.distance.m, tol)
  498. @no_oracle # Oracle already handles geographic distance calculation.
  499. @skipUnlessDBFeature("has_Distance_function", 'has_Transform_function')
  500. def test_distance_transform(self):
  501. """
  502. Test the `Distance` function used with `Transform` on a geographic field.
  503. """
  504. # We'll be using a Polygon (created by buffering the centroid
  505. # of 77005 to 100m) -- which aren't allowed in geographic distance
  506. # queries normally, however our field has been transformed to
  507. # a non-geographic system.
  508. z = SouthTexasZipcode.objects.get(name='77005')
  509. # Reference query:
  510. # SELECT ST_Distance(ST_Transform("distapp_censuszipcode"."poly", 32140),
  511. # ST_GeomFromText('<buffer_wkt>', 32140))
  512. # FROM "distapp_censuszipcode";
  513. dists_m = [3553.30384972258, 1243.18391525602, 2186.15439472242]
  514. # Having our buffer in the SRID of the transformation and of the field
  515. # -- should get the same results. The first buffer has no need for
  516. # transformation SQL because it is the same SRID as what was given
  517. # to `transform()`. The second buffer will need to be transformed,
  518. # however.
  519. buf1 = z.poly.centroid.buffer(100)
  520. buf2 = buf1.transform(4269, clone=True)
  521. ref_zips = ['77002', '77025', '77401']
  522. for buf in [buf1, buf2]:
  523. qs = CensusZipcode.objects.exclude(name='77005').annotate(
  524. distance=Distance(Transform('poly', 32140), buf)
  525. ).order_by('name')
  526. self.assertEqual(ref_zips, sorted([c.name for c in qs]))
  527. for i, z in enumerate(qs):
  528. self.assertAlmostEqual(z.distance.m, dists_m[i], 5)
  529. @skipUnlessDBFeature("has_Distance_function")
  530. def test_distance_order_by(self):
  531. qs = SouthTexasCity.objects.annotate(distance=Distance('point', Point(3, 3, srid=32140))).order_by(
  532. 'distance'
  533. ).values_list('name', flat=True).filter(name__in=('San Antonio', 'Pearland'))
  534. self.assertQuerysetEqual(qs, ['San Antonio', 'Pearland'], lambda x: x)
  535. @skipUnlessDBFeature("has_Length_function")
  536. def test_length(self):
  537. """
  538. Test the `Length` function.
  539. """
  540. # Reference query (should use `length_spheroid`).
  541. # SELECT ST_length_spheroid(ST_GeomFromText('<wkt>', 4326) 'SPHEROID["WGS 84",6378137,298.257223563,
  542. # AUTHORITY["EPSG","7030"]]');
  543. len_m1 = 473504.769553813
  544. len_m2 = 4617.668
  545. if connection.features.supports_length_geodetic:
  546. qs = Interstate.objects.annotate(length=Length('path'))
  547. tol = 2 if oracle else 3
  548. self.assertAlmostEqual(len_m1, qs[0].length.m, tol)
  549. # TODO: test with spheroid argument (True and False)
  550. else:
  551. # Does not support geodetic coordinate systems.
  552. with self.assertRaises(NotImplementedError):
  553. list(Interstate.objects.annotate(length=Length('path')))
  554. # Now doing length on a projected coordinate system.
  555. i10 = SouthTexasInterstate.objects.annotate(length=Length('path')).get(name='I-10')
  556. self.assertAlmostEqual(len_m2, i10.length.m if isinstance(i10.length, D) else i10.length, 2)
  557. self.assertTrue(
  558. SouthTexasInterstate.objects.annotate(length=Length('path')).filter(length__gt=4000).exists()
  559. )
  560. @skipUnlessDBFeature("has_Perimeter_function")
  561. def test_perimeter(self):
  562. """
  563. Test the `Perimeter` function.
  564. """
  565. # Reference query:
  566. # SELECT ST_Perimeter(distapp_southtexaszipcode.poly) FROM distapp_southtexaszipcode;
  567. perim_m = [18404.3550889361, 15627.2108551001, 20632.5588368978, 17094.5996143697]
  568. tol = 2 if oracle else 7
  569. qs = SouthTexasZipcode.objects.annotate(perimeter=Perimeter('poly')).order_by('name')
  570. for i, z in enumerate(qs):
  571. self.assertAlmostEqual(perim_m[i], z.perimeter.m, tol)
  572. # Running on points; should return 0.
  573. qs = SouthTexasCity.objects.annotate(perim=Perimeter('point'))
  574. for city in qs:
  575. self.assertEqual(0, city.perim.m)
  576. @skipUnlessDBFeature("supports_null_geometries", "has_Area_function", "has_Distance_function")
  577. def test_measurement_null_fields(self):
  578. """
  579. Test the measurement functions on fields with NULL values.
  580. """
  581. # Creating SouthTexasZipcode w/NULL value.
  582. SouthTexasZipcode.objects.create(name='78212')
  583. # Performing distance/area queries against the NULL PolygonField,
  584. # and ensuring the result of the operations is None.
  585. htown = SouthTexasCity.objects.get(name='Downtown Houston')
  586. z = SouthTexasZipcode.objects.annotate(
  587. distance=Distance('poly', htown.point), area=Area('poly')
  588. ).get(name='78212')
  589. self.assertIsNone(z.distance)
  590. self.assertIsNone(z.area)