test_functions.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. import json
  2. import math
  3. import re
  4. from decimal import Decimal
  5. from django.contrib.gis.db.models import functions
  6. from django.contrib.gis.geos import (
  7. GEOSGeometry, LineString, Point, Polygon, fromstr,
  8. )
  9. from django.contrib.gis.measure import Area
  10. from django.db import connection
  11. from django.db.models import Sum
  12. from django.test import TestCase, skipUnlessDBFeature
  13. from ..utils import mysql, oracle, postgis, spatialite
  14. from .models import City, Country, CountryWebMercator, State, Track
  15. class GISFunctionsTests(TestCase):
  16. """
  17. Testing functions from django/contrib/gis/db/models/functions.py.
  18. Area/Distance/Length/Perimeter are tested in distapp/tests.
  19. Please keep the tests in function's alphabetic order.
  20. """
  21. fixtures = ['initial']
  22. def test_asgeojson(self):
  23. # Only PostGIS and SpatiaLite support GeoJSON.
  24. if not connection.features.has_AsGeoJSON_function:
  25. with self.assertRaises(NotImplementedError):
  26. list(Country.objects.annotate(json=functions.AsGeoJSON('mpoly')))
  27. return
  28. pueblo_json = '{"type":"Point","coordinates":[-104.609252,38.255001]}'
  29. houston_json = (
  30. '{"type":"Point","crs":{"type":"name","properties":'
  31. '{"name":"EPSG:4326"}},"coordinates":[-95.363151,29.763374]}'
  32. )
  33. victoria_json = (
  34. '{"type":"Point","bbox":[-123.30519600,48.46261100,-123.30519600,48.46261100],'
  35. '"coordinates":[-123.305196,48.462611]}'
  36. )
  37. chicago_json = (
  38. '{"type":"Point","crs":{"type":"name","properties":{"name":"EPSG:4326"}},'
  39. '"bbox":[-87.65018,41.85039,-87.65018,41.85039],"coordinates":[-87.65018,41.85039]}'
  40. )
  41. # MySQL ignores the crs option.
  42. if mysql:
  43. houston_json = json.loads(houston_json)
  44. del houston_json['crs']
  45. chicago_json = json.loads(chicago_json)
  46. del chicago_json['crs']
  47. # Precision argument should only be an integer
  48. with self.assertRaises(TypeError):
  49. City.objects.annotate(geojson=functions.AsGeoJSON('point', precision='foo'))
  50. # Reference queries and values.
  51. # SELECT ST_AsGeoJson("geoapp_city"."point", 8, 0)
  52. # FROM "geoapp_city" WHERE "geoapp_city"."name" = 'Pueblo';
  53. self.assertJSONEqual(
  54. pueblo_json,
  55. City.objects.annotate(geojson=functions.AsGeoJSON('point')).get(name='Pueblo').geojson
  56. )
  57. # SELECT ST_AsGeoJson("geoapp_city"."point", 8, 2) FROM "geoapp_city"
  58. # WHERE "geoapp_city"."name" = 'Houston';
  59. # This time we want to include the CRS by using the `crs` keyword.
  60. self.assertJSONEqual(
  61. City.objects.annotate(json=functions.AsGeoJSON('point', crs=True)).get(name='Houston').json,
  62. houston_json,
  63. )
  64. # SELECT ST_AsGeoJson("geoapp_city"."point", 8, 1) FROM "geoapp_city"
  65. # WHERE "geoapp_city"."name" = 'Houston';
  66. # This time we include the bounding box by using the `bbox` keyword.
  67. self.assertJSONEqual(
  68. victoria_json,
  69. City.objects.annotate(
  70. geojson=functions.AsGeoJSON('point', bbox=True)
  71. ).get(name='Victoria').geojson
  72. )
  73. # SELECT ST_AsGeoJson("geoapp_city"."point", 5, 3) FROM "geoapp_city"
  74. # WHERE "geoapp_city"."name" = 'Chicago';
  75. # Finally, we set every available keyword.
  76. self.assertJSONEqual(
  77. City.objects.annotate(
  78. geojson=functions.AsGeoJSON('point', bbox=True, crs=True, precision=5)
  79. ).get(name='Chicago').geojson,
  80. chicago_json,
  81. )
  82. @skipUnlessDBFeature("has_AsGML_function")
  83. def test_asgml(self):
  84. # Should throw a TypeError when trying to obtain GML from a
  85. # non-geometry field.
  86. qs = City.objects.all()
  87. with self.assertRaises(TypeError):
  88. qs.annotate(gml=functions.AsGML('name'))
  89. ptown = City.objects.annotate(gml=functions.AsGML('point', precision=9)).get(name='Pueblo')
  90. if oracle:
  91. # No precision parameter for Oracle :-/
  92. gml_regex = re.compile(
  93. r'^<gml:Point srsName="EPSG:4326" xmlns:gml="http://www.opengis.net/gml">'
  94. r'<gml:coordinates decimal="\." cs="," ts=" ">-104.60925\d+,38.25500\d+ '
  95. r'</gml:coordinates></gml:Point>'
  96. )
  97. else:
  98. gml_regex = re.compile(
  99. r'^<gml:Point srsName="EPSG:4326"><gml:coordinates>'
  100. r'-104\.60925\d+,38\.255001</gml:coordinates></gml:Point>'
  101. )
  102. self.assertTrue(gml_regex.match(ptown.gml))
  103. self.assertIn(
  104. '<gml:pos srsDimension="2">',
  105. City.objects.annotate(gml=functions.AsGML('point', version=3)).get(name='Pueblo').gml
  106. )
  107. @skipUnlessDBFeature("has_AsKML_function")
  108. def test_askml(self):
  109. # Should throw a TypeError when trying to obtain KML from a
  110. # non-geometry field.
  111. with self.assertRaises(TypeError):
  112. City.objects.annotate(kml=functions.AsKML('name'))
  113. # Ensuring the KML is as expected.
  114. qs = City.objects.annotate(kml=functions.AsKML('point', precision=9))
  115. ptown = qs.get(name='Pueblo')
  116. self.assertEqual('<Point><coordinates>-104.609252,38.255001</coordinates></Point>', ptown.kml)
  117. # Same result if the queryset is evaluated again.
  118. self.assertEqual(qs.get(name='Pueblo').kml, ptown.kml)
  119. @skipUnlessDBFeature("has_AsSVG_function")
  120. def test_assvg(self):
  121. with self.assertRaises(TypeError):
  122. City.objects.annotate(svg=functions.AsSVG('point', precision='foo'))
  123. # SELECT AsSVG(geoapp_city.point, 0, 8) FROM geoapp_city WHERE name = 'Pueblo';
  124. svg1 = 'cx="-104.609252" cy="-38.255001"'
  125. # Even though relative, only one point so it's practically the same except for
  126. # the 'c' letter prefix on the x,y values.
  127. svg2 = svg1.replace('c', '')
  128. self.assertEqual(svg1, City.objects.annotate(svg=functions.AsSVG('point')).get(name='Pueblo').svg)
  129. self.assertEqual(svg2, City.objects.annotate(svg=functions.AsSVG('point', relative=5)).get(name='Pueblo').svg)
  130. @skipUnlessDBFeature("has_Azimuth_function")
  131. def test_azimuth(self):
  132. # Returns the azimuth in radians.
  133. azimuth_expr = functions.Azimuth(Point(0, 0, srid=4326), Point(1, 1, srid=4326))
  134. self.assertAlmostEqual(City.objects.annotate(azimuth=azimuth_expr).first().azimuth, math.pi / 4)
  135. # Returns None if the two points are coincident.
  136. azimuth_expr = functions.Azimuth(Point(0, 0, srid=4326), Point(0, 0, srid=4326))
  137. self.assertIsNone(City.objects.annotate(azimuth=azimuth_expr).first().azimuth)
  138. @skipUnlessDBFeature("has_BoundingCircle_function")
  139. def test_bounding_circle(self):
  140. def circle_num_points(num_seg):
  141. # num_seg is the number of segments per quarter circle.
  142. return (4 * num_seg) + 1
  143. expected_areas = (169, 136) if postgis else (171, 126)
  144. qs = Country.objects.annotate(circle=functions.BoundingCircle('mpoly')).order_by('name')
  145. self.assertAlmostEqual(qs[0].circle.area, expected_areas[0], 0)
  146. self.assertAlmostEqual(qs[1].circle.area, expected_areas[1], 0)
  147. if postgis:
  148. # By default num_seg=48.
  149. self.assertEqual(qs[0].circle.num_points, circle_num_points(48))
  150. self.assertEqual(qs[1].circle.num_points, circle_num_points(48))
  151. qs = Country.objects.annotate(circle=functions.BoundingCircle('mpoly', num_seg=12)).order_by('name')
  152. if postgis:
  153. self.assertGreater(qs[0].circle.area, 168.4, 0)
  154. self.assertLess(qs[0].circle.area, 169.5, 0)
  155. self.assertAlmostEqual(qs[1].circle.area, 136, 0)
  156. self.assertEqual(qs[0].circle.num_points, circle_num_points(12))
  157. self.assertEqual(qs[1].circle.num_points, circle_num_points(12))
  158. else:
  159. self.assertAlmostEqual(qs[0].circle.area, expected_areas[0], 0)
  160. self.assertAlmostEqual(qs[1].circle.area, expected_areas[1], 0)
  161. @skipUnlessDBFeature("has_Centroid_function")
  162. def test_centroid(self):
  163. qs = State.objects.exclude(poly__isnull=True).annotate(centroid=functions.Centroid('poly'))
  164. tol = 1.8 if mysql else (0.1 if oracle else 0.00001)
  165. for state in qs:
  166. self.assertTrue(state.poly.centroid.equals_exact(state.centroid, tol))
  167. with self.assertRaisesMessage(TypeError, "'Centroid' takes exactly 1 argument (2 given)"):
  168. State.objects.annotate(centroid=functions.Centroid('poly', 'poly'))
  169. @skipUnlessDBFeature("has_Difference_function")
  170. def test_difference(self):
  171. geom = Point(5, 23, srid=4326)
  172. qs = Country.objects.annotate(diff=functions.Difference('mpoly', geom))
  173. # Oracle does something screwy with the Texas geometry.
  174. if oracle:
  175. qs = qs.exclude(name='Texas')
  176. for c in qs:
  177. self.assertTrue(c.mpoly.difference(geom).equals(c.diff))
  178. @skipUnlessDBFeature("has_Difference_function", "has_Transform_function")
  179. def test_difference_mixed_srid(self):
  180. """Testing with mixed SRID (Country has default 4326)."""
  181. geom = Point(556597.4, 2632018.6, srid=3857) # Spherical mercator
  182. qs = Country.objects.annotate(difference=functions.Difference('mpoly', geom))
  183. # Oracle does something screwy with the Texas geometry.
  184. if oracle:
  185. qs = qs.exclude(name='Texas')
  186. for c in qs:
  187. self.assertTrue(c.mpoly.difference(geom).equals(c.difference))
  188. @skipUnlessDBFeature("has_Envelope_function")
  189. def test_envelope(self):
  190. countries = Country.objects.annotate(envelope=functions.Envelope('mpoly'))
  191. for country in countries:
  192. self.assertIsInstance(country.envelope, Polygon)
  193. @skipUnlessDBFeature("has_ForceRHR_function")
  194. def test_force_rhr(self):
  195. rings = (
  196. ((0, 0), (5, 0), (0, 5), (0, 0)),
  197. ((1, 1), (1, 3), (3, 1), (1, 1)),
  198. )
  199. rhr_rings = (
  200. ((0, 0), (0, 5), (5, 0), (0, 0)),
  201. ((1, 1), (3, 1), (1, 3), (1, 1)),
  202. )
  203. State.objects.create(name='Foo', poly=Polygon(*rings))
  204. st = State.objects.annotate(force_rhr=functions.ForceRHR('poly')).get(name='Foo')
  205. self.assertEqual(rhr_rings, st.force_rhr.coords)
  206. @skipUnlessDBFeature("has_GeoHash_function")
  207. def test_geohash(self):
  208. # Reference query:
  209. # SELECT ST_GeoHash(point) FROM geoapp_city WHERE name='Houston';
  210. # SELECT ST_GeoHash(point, 5) FROM geoapp_city WHERE name='Houston';
  211. ref_hash = '9vk1mfq8jx0c8e0386z6'
  212. h1 = City.objects.annotate(geohash=functions.GeoHash('point')).get(name='Houston')
  213. h2 = City.objects.annotate(geohash=functions.GeoHash('point', precision=5)).get(name='Houston')
  214. self.assertEqual(ref_hash, h1.geohash[:len(ref_hash)])
  215. self.assertEqual(ref_hash[:5], h2.geohash)
  216. @skipUnlessDBFeature("has_Intersection_function")
  217. def test_intersection(self):
  218. geom = Point(5, 23, srid=4326)
  219. qs = Country.objects.annotate(inter=functions.Intersection('mpoly', geom))
  220. for c in qs:
  221. if spatialite or (mysql and not connection.ops.uses_invalid_empty_geometry_collection) or oracle:
  222. # When the intersection is empty, some databases return None.
  223. expected = None
  224. else:
  225. expected = c.mpoly.intersection(geom)
  226. self.assertEqual(c.inter, expected)
  227. @skipUnlessDBFeature("has_IsValid_function")
  228. def test_isvalid(self):
  229. valid_geom = fromstr('POLYGON((0 0, 0 1, 1 1, 1 0, 0 0))')
  230. invalid_geom = fromstr('POLYGON((0 0, 0 1, 1 1, 1 0, 1 1, 1 0, 0 0))')
  231. State.objects.create(name='valid', poly=valid_geom)
  232. State.objects.create(name='invalid', poly=invalid_geom)
  233. valid = State.objects.filter(name='valid').annotate(isvalid=functions.IsValid('poly')).first()
  234. invalid = State.objects.filter(name='invalid').annotate(isvalid=functions.IsValid('poly')).first()
  235. self.assertIs(valid.isvalid, True)
  236. self.assertIs(invalid.isvalid, False)
  237. @skipUnlessDBFeature("has_Area_function")
  238. def test_area_with_regular_aggregate(self):
  239. # Create projected country objects, for this test to work on all backends.
  240. for c in Country.objects.all():
  241. CountryWebMercator.objects.create(name=c.name, mpoly=c.mpoly.transform(3857, clone=True))
  242. # Test in projected coordinate system
  243. qs = CountryWebMercator.objects.annotate(area_sum=Sum(functions.Area('mpoly')))
  244. # Some backends (e.g. Oracle) cannot group by multipolygon values, so
  245. # defer such fields in the aggregation query.
  246. for c in qs.defer('mpoly'):
  247. result = c.area_sum
  248. # If the result is a measure object, get value.
  249. if isinstance(result, Area):
  250. result = result.sq_m
  251. self.assertAlmostEqual((result - c.mpoly.area) / c.mpoly.area, 0)
  252. @skipUnlessDBFeature("has_Area_function")
  253. def test_area_lookups(self):
  254. # Create projected countries so the test works on all backends.
  255. CountryWebMercator.objects.bulk_create(
  256. CountryWebMercator(name=c.name, mpoly=c.mpoly.transform(3857, clone=True))
  257. for c in Country.objects.all()
  258. )
  259. qs = CountryWebMercator.objects.annotate(area=functions.Area('mpoly'))
  260. self.assertEqual(qs.get(area__lt=Area(sq_km=500000)), CountryWebMercator.objects.get(name='New Zealand'))
  261. with self.assertRaisesMessage(ValueError, 'AreaField only accepts Area measurement objects.'):
  262. qs.get(area__lt=500000)
  263. @skipUnlessDBFeature("has_LineLocatePoint_function")
  264. def test_line_locate_point(self):
  265. pos_expr = functions.LineLocatePoint(LineString((0, 0), (0, 3), srid=4326), Point(0, 1, srid=4326))
  266. self.assertAlmostEqual(State.objects.annotate(pos=pos_expr).first().pos, 0.3333333)
  267. @skipUnlessDBFeature("has_MakeValid_function")
  268. def test_make_valid(self):
  269. invalid_geom = fromstr('POLYGON((0 0, 0 1, 1 1, 1 0, 1 1, 1 0, 0 0))')
  270. State.objects.create(name='invalid', poly=invalid_geom)
  271. invalid = State.objects.filter(name='invalid').annotate(repaired=functions.MakeValid('poly')).first()
  272. self.assertIs(invalid.repaired.valid, True)
  273. self.assertEqual(invalid.repaired, fromstr('POLYGON((0 0, 0 1, 1 1, 1 0, 0 0))', srid=invalid.poly.srid))
  274. @skipUnlessDBFeature("has_MemSize_function")
  275. def test_memsize(self):
  276. ptown = City.objects.annotate(size=functions.MemSize('point')).get(name='Pueblo')
  277. self.assertTrue(20 <= ptown.size <= 40) # Exact value may depend on PostGIS version
  278. @skipUnlessDBFeature("has_NumGeom_function")
  279. def test_num_geom(self):
  280. # Both 'countries' only have two geometries.
  281. for c in Country.objects.annotate(num_geom=functions.NumGeometries('mpoly')):
  282. self.assertEqual(2, c.num_geom)
  283. qs = City.objects.filter(point__isnull=False).annotate(num_geom=functions.NumGeometries('point'))
  284. for city in qs:
  285. # Oracle and PostGIS return 1 for the number of geometries on
  286. # non-collections, whereas MySQL returns None.
  287. if mysql:
  288. self.assertIsNone(city.num_geom)
  289. else:
  290. self.assertEqual(1, city.num_geom)
  291. @skipUnlessDBFeature("has_NumPoint_function")
  292. def test_num_points(self):
  293. coords = [(-95.363151, 29.763374), (-95.448601, 29.713803)]
  294. Track.objects.create(name='Foo', line=LineString(coords))
  295. qs = Track.objects.annotate(num_points=functions.NumPoints('line'))
  296. self.assertEqual(qs.first().num_points, 2)
  297. mpoly_qs = Country.objects.annotate(num_points=functions.NumPoints('mpoly'))
  298. if not connection.features.supports_num_points_poly:
  299. msg = 'NumPoints can only operate on LineString content on this database.'
  300. with self.assertRaisesMessage(TypeError, msg):
  301. list(mpoly_qs)
  302. return
  303. for c in mpoly_qs:
  304. self.assertEqual(c.mpoly.num_points, c.num_points)
  305. for c in City.objects.annotate(num_points=functions.NumPoints('point')):
  306. self.assertEqual(c.num_points, 1)
  307. @skipUnlessDBFeature("has_PointOnSurface_function")
  308. def test_point_on_surface(self):
  309. # Reference values.
  310. if oracle:
  311. # SELECT SDO_UTIL.TO_WKTGEOMETRY(SDO_GEOM.SDO_POINTONSURFACE(GEOAPP_COUNTRY.MPOLY, 0.05))
  312. # FROM GEOAPP_COUNTRY;
  313. ref = {'New Zealand': fromstr('POINT (174.616364 -36.100861)', srid=4326),
  314. 'Texas': fromstr('POINT (-103.002434 36.500397)', srid=4326),
  315. }
  316. else:
  317. # Using GEOSGeometry to compute the reference point on surface values
  318. # -- since PostGIS also uses GEOS these should be the same.
  319. ref = {'New Zealand': Country.objects.get(name='New Zealand').mpoly.point_on_surface,
  320. 'Texas': Country.objects.get(name='Texas').mpoly.point_on_surface
  321. }
  322. qs = Country.objects.annotate(point_on_surface=functions.PointOnSurface('mpoly'))
  323. for country in qs:
  324. tol = 0.00001 # SpatiaLite might have WKT-translation-related precision issues
  325. self.assertTrue(ref[country.name].equals_exact(country.point_on_surface, tol))
  326. @skipUnlessDBFeature("has_Reverse_function")
  327. def test_reverse_geom(self):
  328. coords = [(-95.363151, 29.763374), (-95.448601, 29.713803)]
  329. Track.objects.create(name='Foo', line=LineString(coords))
  330. track = Track.objects.annotate(reverse_geom=functions.Reverse('line')).get(name='Foo')
  331. coords.reverse()
  332. self.assertEqual(tuple(coords), track.reverse_geom.coords)
  333. @skipUnlessDBFeature("has_Scale_function")
  334. def test_scale(self):
  335. xfac, yfac = 2, 3
  336. tol = 5 # The low precision tolerance is for SpatiaLite
  337. qs = Country.objects.annotate(scaled=functions.Scale('mpoly', xfac, yfac))
  338. for country in qs:
  339. for p1, p2 in zip(country.mpoly, country.scaled):
  340. for r1, r2 in zip(p1, p2):
  341. for c1, c2 in zip(r1.coords, r2.coords):
  342. self.assertAlmostEqual(c1[0] * xfac, c2[0], tol)
  343. self.assertAlmostEqual(c1[1] * yfac, c2[1], tol)
  344. # Test float/Decimal values
  345. qs = Country.objects.annotate(scaled=functions.Scale('mpoly', 1.5, Decimal('2.5')))
  346. self.assertGreater(qs[0].scaled.area, qs[0].mpoly.area)
  347. @skipUnlessDBFeature("has_SnapToGrid_function")
  348. def test_snap_to_grid(self):
  349. # Let's try and break snap_to_grid() with bad combinations of arguments.
  350. for bad_args in ((), range(3), range(5)):
  351. with self.assertRaises(ValueError):
  352. Country.objects.annotate(snap=functions.SnapToGrid('mpoly', *bad_args))
  353. for bad_args in (('1.0',), (1.0, None), tuple(map(str, range(4)))):
  354. with self.assertRaises(TypeError):
  355. Country.objects.annotate(snap=functions.SnapToGrid('mpoly', *bad_args))
  356. # Boundary for San Marino, courtesy of Bjorn Sandvik of thematicmapping.org
  357. # from the world borders dataset he provides.
  358. wkt = ('MULTIPOLYGON(((12.41580 43.95795,12.45055 43.97972,12.45389 43.98167,'
  359. '12.46250 43.98472,12.47167 43.98694,12.49278 43.98917,'
  360. '12.50555 43.98861,12.51000 43.98694,12.51028 43.98277,'
  361. '12.51167 43.94333,12.51056 43.93916,12.49639 43.92333,'
  362. '12.49500 43.91472,12.48778 43.90583,12.47444 43.89722,'
  363. '12.46472 43.89555,12.45917 43.89611,12.41639 43.90472,'
  364. '12.41222 43.90610,12.40782 43.91366,12.40389 43.92667,'
  365. '12.40500 43.94833,12.40889 43.95499,12.41580 43.95795)))')
  366. Country.objects.create(name='San Marino', mpoly=fromstr(wkt))
  367. # Because floating-point arithmetic isn't exact, we set a tolerance
  368. # to pass into GEOS `equals_exact`.
  369. tol = 0.000000001
  370. # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.1)) FROM "geoapp_country"
  371. # WHERE "geoapp_country"."name" = 'San Marino';
  372. ref = fromstr('MULTIPOLYGON(((12.4 44,12.5 44,12.5 43.9,12.4 43.9,12.4 44)))')
  373. self.assertTrue(
  374. ref.equals_exact(
  375. Country.objects.annotate(
  376. snap=functions.SnapToGrid('mpoly', 0.1)
  377. ).get(name='San Marino').snap,
  378. tol
  379. )
  380. )
  381. # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.05, 0.23)) FROM "geoapp_country"
  382. # WHERE "geoapp_country"."name" = 'San Marino';
  383. ref = fromstr('MULTIPOLYGON(((12.4 43.93,12.45 43.93,12.5 43.93,12.45 43.93,12.4 43.93)))')
  384. self.assertTrue(
  385. ref.equals_exact(
  386. Country.objects.annotate(
  387. snap=functions.SnapToGrid('mpoly', 0.05, 0.23)
  388. ).get(name='San Marino').snap,
  389. tol
  390. )
  391. )
  392. # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.5, 0.17, 0.05, 0.23)) FROM "geoapp_country"
  393. # WHERE "geoapp_country"."name" = 'San Marino';
  394. ref = fromstr(
  395. 'MULTIPOLYGON(((12.4 43.87,12.45 43.87,12.45 44.1,12.5 44.1,12.5 43.87,12.45 43.87,12.4 43.87)))'
  396. )
  397. self.assertTrue(
  398. ref.equals_exact(
  399. Country.objects.annotate(
  400. snap=functions.SnapToGrid('mpoly', 0.05, 0.23, 0.5, 0.17)
  401. ).get(name='San Marino').snap,
  402. tol
  403. )
  404. )
  405. @skipUnlessDBFeature("has_SymDifference_function")
  406. def test_sym_difference(self):
  407. geom = Point(5, 23, srid=4326)
  408. qs = Country.objects.annotate(sym_difference=functions.SymDifference('mpoly', geom))
  409. # Oracle does something screwy with the Texas geometry.
  410. if oracle:
  411. qs = qs.exclude(name='Texas')
  412. for country in qs:
  413. self.assertTrue(country.mpoly.sym_difference(geom).equals(country.sym_difference))
  414. @skipUnlessDBFeature("has_Transform_function")
  415. def test_transform(self):
  416. # Pre-transformed points for Houston and Pueblo.
  417. ptown = fromstr('POINT(992363.390841912 481455.395105533)', srid=2774)
  418. prec = 3 # Precision is low due to version variations in PROJ and GDAL.
  419. # Asserting the result of the transform operation with the values in
  420. # the pre-transformed points.
  421. h = City.objects.annotate(pt=functions.Transform('point', ptown.srid)).get(name='Pueblo')
  422. self.assertEqual(2774, h.pt.srid)
  423. self.assertAlmostEqual(ptown.x, h.pt.x, prec)
  424. self.assertAlmostEqual(ptown.y, h.pt.y, prec)
  425. @skipUnlessDBFeature("has_Translate_function")
  426. def test_translate(self):
  427. xfac, yfac = 5, -23
  428. qs = Country.objects.annotate(translated=functions.Translate('mpoly', xfac, yfac))
  429. for c in qs:
  430. for p1, p2 in zip(c.mpoly, c.translated):
  431. for r1, r2 in zip(p1, p2):
  432. for c1, c2 in zip(r1.coords, r2.coords):
  433. # The low precision is for SpatiaLite
  434. self.assertAlmostEqual(c1[0] + xfac, c2[0], 5)
  435. self.assertAlmostEqual(c1[1] + yfac, c2[1], 5)
  436. # Some combined function tests
  437. @skipUnlessDBFeature(
  438. "has_Difference_function", "has_Intersection_function",
  439. "has_SymDifference_function", "has_Union_function")
  440. def test_diff_intersection_union(self):
  441. geom = Point(5, 23, srid=4326)
  442. qs = Country.objects.all().annotate(
  443. difference=functions.Difference('mpoly', geom),
  444. sym_difference=functions.SymDifference('mpoly', geom),
  445. union=functions.Union('mpoly', geom),
  446. intersection=functions.Intersection('mpoly', geom),
  447. )
  448. if oracle:
  449. # Should be able to execute the queries; however, they won't be the same
  450. # as GEOS (because Oracle doesn't use GEOS internally like PostGIS or
  451. # SpatiaLite).
  452. return
  453. for c in qs:
  454. self.assertTrue(c.mpoly.difference(geom).equals(c.difference))
  455. if not (spatialite or mysql):
  456. self.assertEqual(c.mpoly.intersection(geom), c.intersection)
  457. self.assertTrue(c.mpoly.sym_difference(geom).equals(c.sym_difference))
  458. self.assertTrue(c.mpoly.union(geom).equals(c.union))
  459. @skipUnlessDBFeature("has_Union_function")
  460. def test_union(self):
  461. """Union with all combinations of geometries/geometry fields."""
  462. geom = Point(-95.363151, 29.763374, srid=4326)
  463. union = City.objects.annotate(union=functions.Union('point', geom)).get(name='Dallas').union
  464. expected = fromstr('MULTIPOINT(-96.801611 32.782057,-95.363151 29.763374)', srid=4326)
  465. self.assertTrue(expected.equals(union))
  466. union = City.objects.annotate(union=functions.Union(geom, 'point')).get(name='Dallas').union
  467. self.assertTrue(expected.equals(union))
  468. union = City.objects.annotate(union=functions.Union('point', 'point')).get(name='Dallas').union
  469. expected = GEOSGeometry('POINT(-96.801611 32.782057)', srid=4326)
  470. self.assertTrue(expected.equals(union))
  471. union = City.objects.annotate(union=functions.Union(geom, geom)).get(name='Dallas').union
  472. self.assertTrue(geom.equals(union))
  473. @skipUnlessDBFeature("has_Union_function", "has_Transform_function")
  474. def test_union_mixed_srid(self):
  475. """The result SRID depends on the order of parameters."""
  476. geom = Point(61.42915, 55.15402, srid=4326)
  477. geom_3857 = geom.transform(3857, clone=True)
  478. tol = 0.001
  479. for city in City.objects.annotate(union=functions.Union('point', geom_3857)):
  480. expected = city.point | geom
  481. self.assertTrue(city.union.equals_exact(expected, tol))
  482. self.assertEqual(city.union.srid, 4326)
  483. for city in City.objects.annotate(union=functions.Union(geom_3857, 'point')):
  484. expected = geom_3857 | city.point.transform(3857, clone=True)
  485. self.assertTrue(expected.equals_exact(city.union, tol))
  486. self.assertEqual(city.union.srid, 3857)
  487. def test_argument_validation(self):
  488. with self.assertRaisesMessage(ValueError, 'SRID is required for all geometries.'):
  489. City.objects.annotate(geo=functions.GeoFunc(Point(1, 1)))
  490. msg = 'GeoFunc function requires a GeometryField in position 1, got CharField.'
  491. with self.assertRaisesMessage(TypeError, msg):
  492. City.objects.annotate(geo=functions.GeoFunc('name'))
  493. msg = 'GeoFunc function requires a geometric argument in position 1.'
  494. with self.assertRaisesMessage(TypeError, msg):
  495. City.objects.annotate(union=functions.GeoFunc(1, 'point')).get(name='Dallas')