/
test_processors.py
571 lines (526 loc) · 23 KB
/
test_processors.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright Kitware Inc. and Epidemico Inc.
#
# Licensed under the Apache License, Version 2.0 ( the "License" );
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
import os
import json
import unittest
from zipfile import ZipFile
import gaia
import gaia.geo as geo
from gaia.geo.geo_inputs import RasterFileIO, VectorFileIO, FeatureIO
base_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)))
testfile_path = os.path.join(base_dir, '../data')
class TestGaiaProcessors(unittest.TestCase):
@classmethod
def setUpClass(cls):
config_file = os.path.join(base_dir, '../../gaia/conf/gaia.cfg')
gaia.get_config(config_file)
def test_zonalstats(self):
vector_io = FeatureIO(features=[
{"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[[100.0, 0.0], [120.0, 0.0], [120.0, 30.0],
[100.0, 30.0], [100.0, 0.0]]
]
},
"properties": {
"prop0": "value1",
"prop1": {"this": "that"}
}
},
{"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[[-100.0, 0.0], [-120.0, 0.0], [-120.0, -30.0],
[100.0, -30.0], [100.0, 0.0]]
]
},
"properties": {
"prop0": "value0",
"prop1": {"this": "other thing"}
}
}])
raster_io = RasterFileIO(name='temp', uri=os.path.join(
testfile_path, 'globalairtemp.tif'))
process = geo.ZonalStatsProcess(inputs=[raster_io, vector_io])
try:
process.compute()
with open(os.path.join(
testfile_path,
'zonalstats_process_results.json')) as exp:
expected_json = json.load(exp)
actual_json = json.loads(process.output.read(
format=geo.formats.JSON))
self.assertEquals(len(expected_json['features']),
len(actual_json['features']))
finally:
pass
if process:
process.purge()
def test_within(self):
"""
Test WithinProcess for vector inputs
"""
vector1_io = VectorFileIO(
uri=os.path.join(testfile_path, 'iraq_hospitals.geojson'))
vector2_io = VectorFileIO(
uri=os.path.join(testfile_path, 'baghdad_districts.geojson'))
process = geo.WithinProcess(inputs=[vector1_io, vector2_io])
try:
process.compute()
self.assertEquals(len(process.output.data), 19)
finally:
if process:
process.purge()
def test_intersect(self):
"""
Test IntersectsProcess for vector inputs
"""
vector1_io = VectorFileIO(
uri=os.path.join(testfile_path, 'baghdad_districts.geojson'))
vector2_io = VectorFileIO(
uri=os.path.join(testfile_path, 'iraq_roads.geojson'))
process = geo.IntersectsProcess(
inputs=[vector1_io, vector2_io])
try:
process.compute()
with open(os.path.join(
testfile_path,
'intersects_process_results.json')) as exp:
expected_json = json.load(exp)
actual_json = json.loads(process.output.read(
format=geo.formats.JSON))
self.assertEquals(len(expected_json['features']),
len(actual_json['features']))
finally:
if process:
process.purge()
def test_cross(self):
"""
Test IntersectsProcess for vector inputs
"""
vector1_io = VectorFileIO(
uri=os.path.join(testfile_path, 'baghdad_districts.geojson'))
vector2_io = VectorFileIO(
uri=os.path.join(testfile_path, 'iraq_roads.geojson'))
process = geo.CrossesProcess(
inputs=[vector1_io, vector2_io])
try:
process.compute()
with open(os.path.join(
testfile_path,
'crosses_process_results.json')) as exp:
expected_json = json.load(exp)
actual_json = json.loads(process.output.read(
format=geo.formats.JSON))
self.assertEquals(len(expected_json['features']),
len(actual_json['features']))
finally:
if process:
process.purge()
def test_touch(self):
"""
Test IntersectsProcess for vector inputs
"""
vector1_io = VectorFileIO(
uri=os.path.join(testfile_path, 'baghdad_districts.geojson'))
vector2_io = VectorFileIO(
uri=os.path.join(testfile_path, 'iraq_roads.geojson'))
process = geo.TouchesProcess(
inputs=[vector1_io, vector2_io])
try:
process.compute()
with open(os.path.join(
testfile_path,
'touches_process_results.json')) as exp:
expected_json = json.load(exp)
actual_json = json.loads(process.output.read(
format=geo.formats.JSON))
self.assertEquals(len(expected_json['features']),
len(actual_json['features']))
finally:
if process:
process.purge()
def test_union(self):
"""
Test UnionProcess for vector inputs
"""
vector1_io = VectorFileIO(
uri=os.path.join(testfile_path, 'baghdad_districts.geojson'),
filters=[('NNAME', 'contains', '^A')])
vector2_io = VectorFileIO(
uri=os.path.join(testfile_path, 'baghdad_districts.geojson'),
filters=[('NNAME', 'contains', '^B')])
process = geo.UnionProcess(inputs=[vector1_io, vector2_io])
try:
process.compute()
with open(os.path.join(
testfile_path,
'union_process_results.json')) as exp:
expected_json = json.load(exp)
actual_json = json.loads(process.output.read(
format=geo.formats.JSON))
self.assertEquals(len(expected_json['features']),
len(actual_json['features']))
finally:
if process:
process.purge()
def test_disjoint(self):
"""
Test DisjointProcess for vector inputs
"""
vector1_io = VectorFileIO(
uri=os.path.join(testfile_path, 'baghdad_districts.geojson'))
vector2_io = VectorFileIO(
uri=os.path.join(testfile_path, 'iraq_roads.geojson'))
process = geo.DisjointProcess(inputs=[vector1_io, vector2_io])
try:
process.compute()
with open(os.path.join(
testfile_path,
'difference_process_results.json')) as exp:
expected_json = json.load(exp)
actual_json = json.loads(process.output.read(
format=geo.formats.JSON))
self.assertEquals(len(expected_json['features']),
len(actual_json['features']))
finally:
if process:
process.purge()
def test_centroid(self):
"""
Test CentroidProcess for vector inputs
"""
vector1_io = VectorFileIO(
uri=os.path.join(testfile_path, 'baghdad_districts.geojson'))
process = geo.CentroidProcess(inputs=[vector1_io])
try:
process.compute()
with open(os.path.join(
testfile_path,
'centroid_process_results.json')) as exp:
expected_json = json.load(exp)
actual_json = json.loads(process.output.read(
format=geo.formats.JSON))
self.assertEquals(len(expected_json['features']),
len(actual_json['features']))
finally:
if process:
process.purge()
def test_distance(self):
"""
Test DistanceProcess for vector inputs
"""
vector1_io = VectorFileIO(
uri=os.path.join(testfile_path, 'baghdad_districts.geojson'))
vector2_io = VectorFileIO(
uri=os.path.join(testfile_path, 'iraq_hospitals.geojson'))
process = geo.DistanceProcess(inputs=[vector1_io, vector2_io])
try:
process.compute()
with open(os.path.join(
testfile_path,
'distance_process_results.json')) as exp:
expected_json = json.load(exp)
actual_json = json.loads(process.output.read(
format=geo.formats.JSON))
self.assertEquals(len(expected_json['features']),
len(actual_json['features']))
finally:
if process:
process.purge()
def test_raster_bbox(self):
raster_io = RasterFileIO(
uri=os.path.join(testfile_path,
'satellite_test_data',
'LC81070352015218LGN00_B5.TIF'))
bbox = raster_io.get_bbox()
self.assertEquals(bbox, [307366.7298195886, 3869968.931078481,
539974.1151507461, 4107482.3190209507])
def test_raster_footprint(self):
raster_io = RasterFileIO(
uri=os.path.join(testfile_path,
'satellite_test_data',
'LC81070352015218LGN00_B5.TIF'))
footprint = raster_io.get_footprint()
self.assertEquals(footprint, [(354404.6484867488, 4107482.3190209507),
(307366.7298195886, 3915415.660631991),
(492936.19648358587, 3869968.931078481),
(539974.1151507461, 4062035.5894674407),
(354404.6484867488, 4107482.3190209507)])
def test_subset_raster(self):
"""
Test SubsetProcess for vector & raster inputs
"""
zipfile = ZipFile(os.path.join(testfile_path, '2states.zip'), 'r')
zipfile.extract('2states.geojson', testfile_path)
vector_io = VectorFileIO(
uri=os.path.join(testfile_path, '2states.geojson'))
raster_io = RasterFileIO(
uri=os.path.join(testfile_path, 'globalairtemp.tif'))
process = geo.SubsetProcess(inputs=[raster_io, vector_io])
try:
process.compute()
self.assertEquals(type(process.output.data).__name__, 'Dataset')
self.assertTrue(os.path.exists(process.output.uri))
self.assertIsNotNone(process.id)
self.assertIn(process.id, process.output.uri)
finally:
testfile = os.path.join(testfile_path, '2states.geojson')
if os.path.exists(testfile):
os.remove(testfile)
if process:
process.purge()
def test_rastermath_add(self):
"""
Test adding two rasters together
"""
raster1_io = RasterFileIO(
name='A', uri=os.path.join(testfile_path, 'globalairtemp.tif'))
raster2_io = RasterFileIO(
name='B', uri=os.path.join(testfile_path, 'globalprecip.tif'))
calc = 'A + B'
bands = [1, 1]
process = geo.RasterMathProcess(
inputs=[raster1_io, raster2_io], calc=calc, bands=bands)
try:
process.compute()
self.assertTrue(os.path.exists(process.output.uri))
oraster, raster1, raster2 = [x.read() for x in (
process.output, raster1_io, raster2_io)]
# Output raster should be same dimensions as raster 1
self.assertEquals((oraster.RasterXSize, oraster.RasterYSize),
(raster1.RasterXSize, raster1.RasterYSize))
orb, r1b, r2b = [x.GetRasterBand(1)
for x in (oraster, raster1, raster2)]
# Min value of output should be >= the max minimum of inputs
self.assertGreaterEqual(orb.GetStatistics(False, True)[0],
max(r1b.GetStatistics(False, True)[0],
r2b.GetStatistics(False, True)[0]))
# Max value of output >= max(minimum)+min(maximum) of inputs
self.assertGreaterEqual(orb.GetStatistics(False, True)[1],
max(r1b.GetStatistics(False, True)[0],
r2b.GetStatistics(False, True)[0]) +
min(r1b.GetStatistics(False, True)[1],
r2b.GetStatistics(False, True)[1]))
finally:
if process:
process.purge()
def test_rastermath_multiply_by_value(self):
"""
Test multiplying a raster by a value,
and specifying output type (Float32)
"""
raster1_io = RasterFileIO(
name='A', uri=os.path.join(testfile_path, 'globalprecip.tif'))
calc = 'A * 2'
output_type = 'Float32'
process = geo.RasterMathProcess(inputs=[raster1_io, ],
calc=calc,
output_type=output_type)
try:
process.compute()
self.assertTrue(os.path.exists(process.output.uri))
oraster, raster1 = [x.read() for x in (process.output, raster1_io)]
# Output raster should be same dimensions as raster 1
self.assertEquals((oraster.RasterXSize, oraster.RasterYSize),
(raster1.RasterXSize, raster1.RasterYSize))
orb, r1b = [x.GetRasterBand(1) for x in (oraster, raster1)]
# Maximum value of output should be 2x the max of input raster
self.assertEqual(orb.GetStatistics(False, True)[1],
r1b.GetStatistics(False, True)[1] * 2)
# Datatype of band should be Float32 (== gdal.GDT_Float32 == 6)
self.assertEquals(6, orb.DataType)
self.assertEquals(1.175494351E-38, orb.GetNoDataValue())
# Each pixel of output raster should equal 2x input raster
# unless it is a nodata value
ora, r1a = [x.ReadAsArray() for x in (orb, r1b)]
for x in range(raster1.RasterXSize):
for y in range(raster1.RasterYSize):
if r1a[y, x] != r1b.GetNoDataValue():
self.assertEquals(ora[y, x], r1a[y, x] * 2)
finally:
if process:
process.purge()
def test_rastermath_logical_operators(self):
"""
Test creation of a masked raster based on logical operators
"""
raster1_io = RasterFileIO(
name='A', uri=os.path.join(testfile_path, 'globalairtemp.tif'))
calc = 'logical_or(logical_and(A >= 27000, A <= 28000), ' \
'logical_and(A >= 30000, A <= 31000))'
process = geo.RasterMathProcess(inputs=[raster1_io, ], calc=calc)
try:
process.compute()
self.assertTrue(os.path.exists(process.output.uri))
oraster, raster1 = [x.read() for x in (process.output, raster1_io)]
# Output raster should be same dimensions as raster 1
self.assertEquals((oraster.RasterXSize, oraster.RasterYSize),
(raster1.RasterXSize, raster1.RasterYSize))
orb, r1b = [x.GetRasterBand(1) for x in (oraster, raster1)]
# Maximum value of output should be 1
self.assertEqual(orb.GetStatistics(False, True)[1], 1)
# Minimum value of output should be 0
self.assertEqual(orb.GetStatistics(False, True)[0], 0)
# Pixels should be 1 where source is between 27K-28K or 30-31K
ora, r1a = [x.ReadAsArray() for x in (orb, r1b)]
self.assertTrue(ora[90, 10] == 1 and r1a[90, 10] == 30083)
self.assertTrue(ora[160, 10] == 1 and r1a[160, 10] == 27074)
# Pixels should be 0 where source is not between 27K-28K or 30-31K
ora, r1a = [x.ReadAsArray() for x in (orb, r1b)]
self.assertTrue(ora[120, 10] == 0 and r1a[120, 10] == 29623)
self.assertTrue(ora[175, 10] == 0 and r1a[175, 10] == 23928)
finally:
if process:
process.purge()
def test_length(self):
"""
Test LengthProcess for vector inputs
"""
vector_roads = VectorFileIO(
uri=os.path.join(testfile_path, 'iraq_roads.geojson'),
filters=[('type', '=', 'motorway'), ('bridge', '=', 1)])
process = geo.LengthProcess(inputs=[vector_roads])
try:
process.compute()
with open(os.path.join(
testfile_path,
'length_process_results.json')) as exp:
expected_json = json.load(exp)
actual_json = json.loads(process.output.read(
format=geo.formats.JSON))
self.assertEquals(len(expected_json['features']),
len(actual_json['features']))
finally:
if process:
process.purge()
def test_area(self):
"""
Test AreaProcess for vector inputs
"""
vector1_io = VectorFileIO(
uri=os.path.join(testfile_path, 'baghdad_districts.geojson'),
filters=[('NNAME', 'contains', '^B')])
process = geo.AreaProcess(inputs=[vector1_io])
try:
process.compute()
with open(os.path.join(
testfile_path,
'area_process_results.json')) as exp:
expected_json = json.load(exp)
actual_json = json.loads(process.output.read(
format=geo.formats.JSON))
self.assertEquals(len(expected_json['features']),
len(actual_json['features']))
finally:
if process:
process.purge()
def test_validationInputsPass(self):
"""
Test the GaiaProcess.validate() function - pass on valid input
"""
raster_io = RasterFileIO(uri='/fake/path')
vector_io = VectorFileIO(uri='/fake/path')
try:
geo.ZonalStatsProcess(inputs=[raster_io, vector_io])
except geo.GaiaException:
self.fail("ZonalProcess should have passed validation but did not")
def test_validationInputsOrder(self):
"""
Test the GaiaProcess.validate() function - fail on incorrect order
"""
raster_iO = RasterFileIO(uri='/fake/path1')
vector_io = VectorFileIO(uri='/fake/path2')
with self.assertRaises(geo.GaiaException) as ge:
geo.ZonalStatsProcess(inputs=[vector_io, raster_iO])
self.assertIn('Input #1 is of incorrect type.', str(ge.exception))
def test_validationInputsMin(self):
"""
Test the GaiaProcess.validate() function - fail on < minimum input types
"""
vector_io = VectorFileIO(uri='/fake/path1')
with self.assertRaises(geo.GaiaException) as ge:
geo.IntersectsProcess(inputs=[vector_io])
self.assertIn('Not enough inputs for process', str(ge.exception))
def test_validationInputsNoMax(self):
"""
Test the GaiaProcess.validate() function - pass on no max input types
"""
raster_io1 = RasterFileIO(uri='/fake/path1')
raster_io2 = RasterFileIO(uri='/fake/path2')
try:
geo.RasterMathProcess(inputs=[raster_io1, raster_io2], calc='A+B')
except geo.GaiaException:
self.fail("Multiple inputs should have passed validation")
def test_validationInputsMax(self):
"""
Test the GaiaProcess.validate() function - fail on > max input types
"""
vector_io1 = VectorFileIO(uri='/fake/path')
vector_io2 = VectorFileIO(uri='/fake/path')
with self.assertRaises(geo.GaiaException) as ge:
geo.LengthProcess(inputs=[vector_io1, vector_io2])
self.assertIn('Incorrect # of inputs; expected 1', str(ge.exception))
def test_mercator_geojson(self):
vector_io = VectorFileIO(
uri=os.path.join(testfile_path, 'iraq_hospitals_3857.json'))
self.assertEquals(vector_io.get_epsg(), 3857)
jsonwm = json.loads(vector_io.read(format=geo.formats.JSON))
self.assertEquals(jsonwm['crs']['properties']['name'], 'EPSG:3857')
self.assertEquals(jsonwm['features'][0]['geometry']['coordinates'],
[4940150.544527022, 3941210.867854486])
json84 = json.loads(vector_io.read(format=geo.formats.JSON, epsg=4326))
self.assertEquals(json84['crs']['properties']['name'], 'EPSG:4326')
self.assertEquals(json84['features'][0]['geometry']['coordinates'],
[44.378127400000004, 33.34517919999999])
def test_nocrs_wgs84_geojson(self):
vector_io = VectorFileIO(
uri=os.path.join(testfile_path, 'iraq_hospitals.geojson'))
raw_json = json.loads(vector_io.read(format=geo.formats.JSON))
self.assertFalse(hasattr(raw_json, 'crs'))
epsg = vector_io.get_epsg()
self.assertEquals(epsg, 4326)
def test_nocrs_mercator_geojson(self):
with open(os.path.join(testfile_path,
'iraq_hospitals_3857.json')) as injson:
json3857 = json.load(injson)
feature_io = FeatureIO(features=json3857['features'])
epsg = feature_io.get_epsg()
self.assertEquals(epsg, 3857)
feature_json = feature_io.read(format=geo.formats.JSON)
self.assertFalse(hasattr(feature_json, 'crs'))
def test_within_reproject(self):
"""
Test WithinProcess for vector inputs, where output should be in
same projection as first input (in this case, 3857).
"""
vector1_io = VectorFileIO(
uri=os.path.join(testfile_path, 'iraq_hospitals_3857.json'))
vector2_io = VectorFileIO(
uri=os.path.join(testfile_path, 'baghdad_districts.geojson'))
process = geo.WithinProcess(inputs=[vector1_io, vector2_io])
try:
process.compute()
self.assertEquals(process.output.data.crs, {'init': u'epsg:3857'})
self.assertEquals(len(process.output.data), 19)
finally:
if process:
process.purge()