test_rasterfield.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. import json
  2. from django.contrib.gis.db.models.fields import BaseSpatialField
  3. from django.contrib.gis.db.models.functions import Distance
  4. from django.contrib.gis.db.models.lookups import DistanceLookupBase, GISLookup
  5. from django.contrib.gis.gdal import GDALRaster
  6. from django.contrib.gis.geos import GEOSGeometry
  7. from django.contrib.gis.measure import D
  8. from django.contrib.gis.shortcuts import numpy
  9. from django.db import connection
  10. from django.db.models import F, Func, Q
  11. from django.test import TransactionTestCase, skipUnlessDBFeature
  12. from django.test.utils import CaptureQueriesContext
  13. from ..data.rasters.textrasters import JSON_RASTER
  14. from .models import RasterModel, RasterRelatedModel
  15. @skipUnlessDBFeature('supports_raster')
  16. class RasterFieldTest(TransactionTestCase):
  17. available_apps = ['gis_tests.rasterapp']
  18. def setUp(self):
  19. rast = GDALRaster({
  20. "srid": 4326,
  21. "origin": [0, 0],
  22. "scale": [-1, 1],
  23. "skew": [0, 0],
  24. "width": 5,
  25. "height": 5,
  26. "nr_of_bands": 2,
  27. "bands": [{"data": range(25)}, {"data": range(25, 50)}],
  28. })
  29. model_instance = RasterModel.objects.create(
  30. rast=rast,
  31. rastprojected=rast,
  32. geom="POINT (-95.37040 29.70486)",
  33. )
  34. RasterRelatedModel.objects.create(rastermodel=model_instance)
  35. def test_field_null_value(self):
  36. """
  37. Test creating a model where the RasterField has a null value.
  38. """
  39. r = RasterModel.objects.create(rast=None)
  40. r.refresh_from_db()
  41. self.assertIsNone(r.rast)
  42. def test_access_band_data_directly_from_queryset(self):
  43. RasterModel.objects.create(rast=JSON_RASTER)
  44. qs = RasterModel.objects.all()
  45. qs[0].rast.bands[0].data()
  46. def test_deserialize_with_pixeltype_flags(self):
  47. no_data = 3
  48. rast = GDALRaster({
  49. 'srid': 4326,
  50. 'origin': [0, 0],
  51. 'scale': [-1, 1],
  52. 'skew': [0, 0],
  53. 'width': 1,
  54. 'height': 1,
  55. 'nr_of_bands': 1,
  56. 'bands': [{'data': [no_data], 'nodata_value': no_data}],
  57. })
  58. r = RasterModel.objects.create(rast=rast)
  59. RasterModel.objects.filter(pk=r.pk).update(
  60. rast=Func(F('rast'), function='ST_SetBandIsNoData'),
  61. )
  62. r.refresh_from_db()
  63. band = r.rast.bands[0].data()
  64. if numpy:
  65. band = band.flatten().tolist()
  66. self.assertEqual(band, [no_data])
  67. self.assertEqual(r.rast.bands[0].nodata_value, no_data)
  68. def test_model_creation(self):
  69. """
  70. Test RasterField through a test model.
  71. """
  72. # Create model instance from JSON raster
  73. r = RasterModel.objects.create(rast=JSON_RASTER)
  74. r.refresh_from_db()
  75. # Test raster metadata properties
  76. self.assertEqual((5, 5), (r.rast.width, r.rast.height))
  77. self.assertEqual([0.0, -1.0, 0.0, 0.0, 0.0, 1.0], r.rast.geotransform)
  78. self.assertIsNone(r.rast.bands[0].nodata_value)
  79. # Compare srs
  80. self.assertEqual(r.rast.srs.srid, 4326)
  81. # Compare pixel values
  82. band = r.rast.bands[0].data()
  83. # If numpy, convert result to list
  84. if numpy:
  85. band = band.flatten().tolist()
  86. # Loop through rows in band data and assert single
  87. # value is as expected.
  88. self.assertEqual(
  89. [
  90. 0.0, 1.0, 2.0, 3.0, 4.0,
  91. 5.0, 6.0, 7.0, 8.0, 9.0,
  92. 10.0, 11.0, 12.0, 13.0, 14.0,
  93. 15.0, 16.0, 17.0, 18.0, 19.0,
  94. 20.0, 21.0, 22.0, 23.0, 24.0
  95. ],
  96. band
  97. )
  98. def test_implicit_raster_transformation(self):
  99. """
  100. Test automatic transformation of rasters with srid different from the
  101. field srid.
  102. """
  103. # Parse json raster
  104. rast = json.loads(JSON_RASTER)
  105. # Update srid to another value
  106. rast['srid'] = 3086
  107. # Save model and get it from db
  108. r = RasterModel.objects.create(rast=rast)
  109. r.refresh_from_db()
  110. # Confirm raster has been transformed to the default srid
  111. self.assertEqual(r.rast.srs.srid, 4326)
  112. # Confirm geotransform is in lat/lon
  113. expected = [
  114. -87.9298551266551, 9.459646421449934e-06, 0.0, 23.94249275457565,
  115. 0.0, -9.459646421449934e-06,
  116. ]
  117. for val, exp in zip(r.rast.geotransform, expected):
  118. self.assertAlmostEqual(exp, val)
  119. def test_verbose_name_arg(self):
  120. """
  121. RasterField should accept a positional verbose name argument.
  122. """
  123. self.assertEqual(
  124. RasterModel._meta.get_field('rast').verbose_name,
  125. 'A Verbose Raster Name'
  126. )
  127. def test_all_gis_lookups_with_rasters(self):
  128. """
  129. Evaluate all possible lookups for all input combinations (i.e.
  130. raster-raster, raster-geom, geom-raster) and for projected and
  131. unprojected coordinate systems. This test just checks that the lookup
  132. can be called, but doesn't check if the result makes logical sense.
  133. """
  134. from django.contrib.gis.db.backends.postgis.operations import (
  135. PostGISOperations,
  136. )
  137. # Create test raster and geom.
  138. rast = GDALRaster(json.loads(JSON_RASTER))
  139. stx_pnt = GEOSGeometry('POINT (-95.370401017314293 29.704867409475465)', 4326)
  140. stx_pnt.transform(3086)
  141. lookups = [
  142. (name, lookup)
  143. for name, lookup in BaseSpatialField.get_lookups().items()
  144. if issubclass(lookup, GISLookup)
  145. ]
  146. self.assertNotEqual(lookups, [], 'No lookups found')
  147. # Loop through all the GIS lookups.
  148. for name, lookup in lookups:
  149. # Construct lookup filter strings.
  150. combo_keys = [
  151. field + name for field in [
  152. 'rast__', 'rast__', 'rastprojected__0__', 'rast__',
  153. 'rastprojected__', 'geom__', 'rast__',
  154. ]
  155. ]
  156. if issubclass(lookup, DistanceLookupBase):
  157. # Set lookup values for distance lookups.
  158. combo_values = [
  159. (rast, 50, 'spheroid'),
  160. (rast, 0, 50, 'spheroid'),
  161. (rast, 0, D(km=1)),
  162. (stx_pnt, 0, 500),
  163. (stx_pnt, D(km=1000)),
  164. (rast, 500),
  165. (json.loads(JSON_RASTER), 500),
  166. ]
  167. elif name == 'relate':
  168. # Set lookup values for the relate lookup.
  169. combo_values = [
  170. (rast, 'T*T***FF*'),
  171. (rast, 0, 'T*T***FF*'),
  172. (rast, 0, 'T*T***FF*'),
  173. (stx_pnt, 0, 'T*T***FF*'),
  174. (stx_pnt, 'T*T***FF*'),
  175. (rast, 'T*T***FF*'),
  176. (json.loads(JSON_RASTER), 'T*T***FF*'),
  177. ]
  178. elif name == 'isvalid':
  179. # The isvalid lookup doesn't make sense for rasters.
  180. continue
  181. elif PostGISOperations.gis_operators[name].func:
  182. # Set lookup values for all function based operators.
  183. combo_values = [
  184. rast, (rast, 0), (rast, 0), (stx_pnt, 0), stx_pnt,
  185. rast, json.loads(JSON_RASTER)
  186. ]
  187. else:
  188. # Override band lookup for these, as it's not supported.
  189. combo_keys[2] = 'rastprojected__' + name
  190. # Set lookup values for all other operators.
  191. combo_values = [rast, None, rast, stx_pnt, stx_pnt, rast, json.loads(JSON_RASTER)]
  192. # Create query filter combinations.
  193. self.assertEqual(
  194. len(combo_keys),
  195. len(combo_values),
  196. 'Number of lookup names and values should be the same',
  197. )
  198. combos = [x for x in zip(combo_keys, combo_values) if x[1]]
  199. self.assertEqual(
  200. [(n, x) for n, x in enumerate(combos) if x in combos[:n]],
  201. [],
  202. 'There are repeated test lookups',
  203. )
  204. combos = [{k: v} for k, v in combos]
  205. for combo in combos:
  206. # Apply this query filter.
  207. qs = RasterModel.objects.filter(**combo)
  208. # Evaluate normal filter qs.
  209. self.assertIn(qs.count(), [0, 1])
  210. # Evaluate on conditional Q expressions.
  211. qs = RasterModel.objects.filter(Q(**combos[0]) & Q(**combos[1]))
  212. self.assertIn(qs.count(), [0, 1])
  213. def test_dwithin_gis_lookup_output_with_rasters(self):
  214. """
  215. Check the logical functionality of the dwithin lookup for different
  216. input parameters.
  217. """
  218. # Create test raster and geom.
  219. rast = GDALRaster(json.loads(JSON_RASTER))
  220. stx_pnt = GEOSGeometry('POINT (-95.370401017314293 29.704867409475465)', 4326)
  221. stx_pnt.transform(3086)
  222. # Filter raster with different lookup raster formats.
  223. qs = RasterModel.objects.filter(rastprojected__dwithin=(rast, D(km=1)))
  224. self.assertEqual(qs.count(), 1)
  225. qs = RasterModel.objects.filter(rastprojected__dwithin=(json.loads(JSON_RASTER), D(km=1)))
  226. self.assertEqual(qs.count(), 1)
  227. qs = RasterModel.objects.filter(rastprojected__dwithin=(JSON_RASTER, D(km=1)))
  228. self.assertEqual(qs.count(), 1)
  229. # Filter in an unprojected coordinate system.
  230. qs = RasterModel.objects.filter(rast__dwithin=(rast, 40))
  231. self.assertEqual(qs.count(), 1)
  232. # Filter with band index transform.
  233. qs = RasterModel.objects.filter(rast__1__dwithin=(rast, 1, 40))
  234. self.assertEqual(qs.count(), 1)
  235. qs = RasterModel.objects.filter(rast__1__dwithin=(rast, 40))
  236. self.assertEqual(qs.count(), 1)
  237. qs = RasterModel.objects.filter(rast__dwithin=(rast, 1, 40))
  238. self.assertEqual(qs.count(), 1)
  239. # Filter raster by geom.
  240. qs = RasterModel.objects.filter(rast__dwithin=(stx_pnt, 500))
  241. self.assertEqual(qs.count(), 1)
  242. qs = RasterModel.objects.filter(rastprojected__dwithin=(stx_pnt, D(km=10000)))
  243. self.assertEqual(qs.count(), 1)
  244. qs = RasterModel.objects.filter(rast__dwithin=(stx_pnt, 5))
  245. self.assertEqual(qs.count(), 0)
  246. qs = RasterModel.objects.filter(rastprojected__dwithin=(stx_pnt, D(km=100)))
  247. self.assertEqual(qs.count(), 0)
  248. # Filter geom by raster.
  249. qs = RasterModel.objects.filter(geom__dwithin=(rast, 500))
  250. self.assertEqual(qs.count(), 1)
  251. # Filter through related model.
  252. qs = RasterRelatedModel.objects.filter(rastermodel__rast__dwithin=(rast, 40))
  253. self.assertEqual(qs.count(), 1)
  254. # Filter through related model with band index transform
  255. qs = RasterRelatedModel.objects.filter(rastermodel__rast__1__dwithin=(rast, 40))
  256. self.assertEqual(qs.count(), 1)
  257. # Filter through conditional statements.
  258. qs = RasterModel.objects.filter(Q(rast__dwithin=(rast, 40)) & Q(rastprojected__dwithin=(stx_pnt, D(km=10000))))
  259. self.assertEqual(qs.count(), 1)
  260. # Filter through different lookup.
  261. qs = RasterModel.objects.filter(rastprojected__bbcontains=rast)
  262. self.assertEqual(qs.count(), 1)
  263. def test_lookup_input_tuple_too_long(self):
  264. rast = GDALRaster(json.loads(JSON_RASTER))
  265. msg = 'Tuple too long for lookup bbcontains.'
  266. with self.assertRaisesMessage(ValueError, msg):
  267. RasterModel.objects.filter(rast__bbcontains=(rast, 1, 2))
  268. def test_lookup_input_band_not_allowed(self):
  269. rast = GDALRaster(json.loads(JSON_RASTER))
  270. qs = RasterModel.objects.filter(rast__bbcontains=(rast, 1))
  271. msg = 'Band indices are not allowed for this operator, it works on bbox only.'
  272. with self.assertRaisesMessage(ValueError, msg):
  273. qs.count()
  274. def test_isvalid_lookup_with_raster_error(self):
  275. qs = RasterModel.objects.filter(rast__isvalid=True)
  276. msg = 'IsValid function requires a GeometryField in position 1, got RasterField.'
  277. with self.assertRaisesMessage(TypeError, msg):
  278. qs.count()
  279. def test_result_of_gis_lookup_with_rasters(self):
  280. # Point is in the interior
  281. qs = RasterModel.objects.filter(rast__contains=GEOSGeometry('POINT (-0.5 0.5)', 4326))
  282. self.assertEqual(qs.count(), 1)
  283. # Point is in the exterior
  284. qs = RasterModel.objects.filter(rast__contains=GEOSGeometry('POINT (0.5 0.5)', 4326))
  285. self.assertEqual(qs.count(), 0)
  286. # A point on the boundary is not contained properly
  287. qs = RasterModel.objects.filter(rast__contains_properly=GEOSGeometry('POINT (0 0)', 4326))
  288. self.assertEqual(qs.count(), 0)
  289. # Raster is located left of the point
  290. qs = RasterModel.objects.filter(rast__left=GEOSGeometry('POINT (1 0)', 4326))
  291. self.assertEqual(qs.count(), 1)
  292. def test_lookup_with_raster_bbox(self):
  293. rast = GDALRaster(json.loads(JSON_RASTER))
  294. # Shift raster upwards
  295. rast.origin.y = 2
  296. # The raster in the model is not strictly below
  297. qs = RasterModel.objects.filter(rast__strictly_below=rast)
  298. self.assertEqual(qs.count(), 0)
  299. # Shift raster further upwards
  300. rast.origin.y = 6
  301. # The raster in the model is strictly below
  302. qs = RasterModel.objects.filter(rast__strictly_below=rast)
  303. self.assertEqual(qs.count(), 1)
  304. def test_lookup_with_polygonized_raster(self):
  305. rast = GDALRaster(json.loads(JSON_RASTER))
  306. # Move raster to overlap with the model point on the left side
  307. rast.origin.x = -95.37040 + 1
  308. rast.origin.y = 29.70486
  309. # Raster overlaps with point in model
  310. qs = RasterModel.objects.filter(geom__intersects=rast)
  311. self.assertEqual(qs.count(), 1)
  312. # Change left side of raster to be nodata values
  313. rast.bands[0].data(data=[0, 0, 0, 1, 1], shape=(5, 1))
  314. rast.bands[0].nodata_value = 0
  315. qs = RasterModel.objects.filter(geom__intersects=rast)
  316. # Raster does not overlap anymore after polygonization
  317. # where the nodata zone is not included.
  318. self.assertEqual(qs.count(), 0)
  319. def test_lookup_value_error(self):
  320. # Test with invalid dict lookup parameter
  321. obj = {}
  322. msg = "Couldn't create spatial object from lookup value '%s'." % obj
  323. with self.assertRaisesMessage(ValueError, msg):
  324. RasterModel.objects.filter(geom__intersects=obj)
  325. # Test with invalid string lookup parameter
  326. obj = '00000'
  327. msg = "Couldn't create spatial object from lookup value '%s'." % obj
  328. with self.assertRaisesMessage(ValueError, msg):
  329. RasterModel.objects.filter(geom__intersects=obj)
  330. def test_db_function_errors(self):
  331. """
  332. Errors are raised when using DB functions with raster content.
  333. """
  334. point = GEOSGeometry("SRID=3086;POINT (-697024.9213808845 683729.1705516104)")
  335. rast = GDALRaster(json.loads(JSON_RASTER))
  336. msg = "Distance function requires a geometric argument in position 2."
  337. with self.assertRaisesMessage(TypeError, msg):
  338. RasterModel.objects.annotate(distance_from_point=Distance("geom", rast))
  339. with self.assertRaisesMessage(TypeError, msg):
  340. RasterModel.objects.annotate(distance_from_point=Distance("rastprojected", rast))
  341. msg = "Distance function requires a GeometryField in position 1, got RasterField."
  342. with self.assertRaisesMessage(TypeError, msg):
  343. RasterModel.objects.annotate(distance_from_point=Distance("rastprojected", point)).count()
  344. def test_lhs_with_index_rhs_without_index(self):
  345. with CaptureQueriesContext(connection) as queries:
  346. RasterModel.objects.filter(rast__0__contains=json.loads(JSON_RASTER)).exists()
  347. # It's easier to check the indexes in the generated SQL than to write
  348. # tests that cover all index combinations.
  349. self.assertRegex(queries[-1]['sql'], r'WHERE ST_Contains\([^)]*, 1, [^)]*, 1\)')