-
Notifications
You must be signed in to change notification settings - Fork 136
/
test_engine.py
1859 lines (1482 loc) · 69.4 KB
/
test_engine.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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf-8
"""Tests for engine."""
import unittest
import cPickle
import numpy
import os
from os.path import join
# Import InaSAFE modules
from safe.engine.core import calculate_impact
from safe.engine.interpolation import (
interpolate_polygon_raster,
interpolate_raster_vector_points,
assign_hazard_values_to_exposure_data,
tag_polygons_by_grid)
from safe.storage.core import (
read_layer,
write_vector_data,
write_raster_data)
from safe.storage.vector import Vector
from safe.storage.utilities import DEFAULT_ATTRIBUTE
from safe.gis.polygon import (
separate_points_by_polygon,
is_inside_polygon,
inside_polygon,
clip_lines_by_polygon,
clip_grid_by_polygons,
line_dictionary_to_geometry)
from safe.gis.interpolation2d import interpolate_raster
from safe.gis.numerics import (
normal_cdf,
log_normal_cdf,
erf,
ensure_numeric)
from safe.common.utilities import (
VerificationError,
unique_filename,
format_int)
from safe.common.testing import TESTDATA, HAZDATA, EXPDATA
from safe.common.exceptions import InaSAFEError
from safe.impact_functions import get_plugins, get_plugin
from safe.impact_functions.core import population_rounding
# These imports are needed for impact function registration - dont remove
# If any of these get reinstated as "official" public impact functions,
# remove from here and update test to use the real one.
# pylint: disable=W0611
# noinspection PyUnresolvedReferences
from safe.impact_functions.earthquake.pager_earthquake_fatality_model import (
PAGFatalityFunction)
# pylint: enable=W0611
def linear_function(x, y):
"""Auxiliary function for use with interpolation test
:param y:
:param x:
:returns: Average
"""
return x + y / 2.0
class TestEngine(unittest.TestCase):
"""Tests for engine module."""
def setUp(self):
"""Run before each test."""
# ensure we are using english by default
os.environ['LANG'] = 'en'
# This one currently fails because the clipped input data has
# different resolution to the full data. Issue #344
#
# This test is not finished, but must wait 'till #344 has been sorted
@unittest.expectedFailure
def test_polygon_hazard_raster_exposure_clipped_grids(self):
"""Rasters clipped by polygons irrespective of pre-clipping.
Double check that a raster clipped by the QGIS front-end
produces the same results as when full raster is used.
"""
# Read test files
hazard_filename = '%s/donut.shp' % TESTDATA
exposure_filename_clip = ('%s/pop_merapi_clip.tif' % TESTDATA)
exposure_filename_full = ('%s/pop_merapi_prj_problem.asc'
% TESTDATA)
H = read_layer(hazard_filename)
E_clip = read_layer(exposure_filename_clip)
E_full = read_layer(exposure_filename_full)
# Establish whether full and clipped grids coincide
# in clipped area
gt_clip = E_clip.get_geotransform()
gt_full = E_full.get_geotransform()
msg = ('Resolutions were different. Geotransform full grid: %s, '
'clipped grid: %s' % (gt_full, gt_clip))
assert numpy.allclose(gt_clip[1], gt_full[1]), msg
assert numpy.allclose(gt_clip[5], gt_full[5]), msg
polygons = H.get_geometry(as_geometry_objects=True)
# Clip
res_clip = clip_grid_by_polygons(E_clip.get_data(),
E_clip.get_geotransform(),
polygons)
# print res_clip
# print len(res_clip)
res_full = clip_grid_by_polygons(E_full.get_data(),
E_full.get_geotransform(),
polygons)
assert len(res_clip) == len(res_full)
for i in range(len(res_clip)):
# print
x = res_clip[i][0]
y = res_full[i][0]
# print x
# print y
msg = ('Got len(x) == %i, len(y) == %i. Should be the same'
% (len(x), len(y)))
assert len(x) == len(y), msg
# Check that they are inside the respective polygon
P = polygons[i]
idx = inside_polygon(x, # pylint: disable=W0612
P.outer_ring,
holes=P.inner_rings)
# print idx
msg = ('Expected point locations to be the same in clipped '
'and full grids, Got %s and %s' % (x, y))
assert numpy.allclose(x, y)
def test_polygon_hazard_and_raster_exposure_big(self):
"""Rasters can be converted to points and clipped by polygons
This is a test for the basic machinery needed for issue #91
It uses over 400,000 gridpoints and 2704 complex polygons,
each with 10-200 vertices, and serves a test for optimising
the polygon clipping algorithm. With the optimisations requested
in https://github.com/AIFDR/inasafe/issues/222 it takes about 100
seconds on a good workstation while it takes over 2000 seconds
without it.
This test also runs the high level interpolation routine which assigns
attributes to the new point layer. The runtime is virtually the same as
the underlying function.
"""
# Name input files
polyhazard = join(TESTDATA, 'rw_jakarta_singlepart.shp')
population = join(TESTDATA, 'Population_Jakarta_geographic.asc')
# Get layers using API
H = read_layer(polyhazard)
E = read_layer(population)
N = len(H)
assert N == 2704
# Run and test the fundamental clipping routine
# import time
# t0 = time.time()
res = clip_grid_by_polygons(E.get_data(),
E.get_geotransform(),
H.get_geometry(as_geometry_objects=True))
# print 'Engine took %i seconds' % (time.time() - t0)
assert len(res) == N
# Characterisation test
assert H.get_data()[0]['RW'] == 'RW 01'
assert H.get_data()[0]['KAB_NAME'] == 'JAKARTA UTARA'
assert H.get_data()[0]['KEC_NAME'] == 'TANJUNG PRIOK'
assert H.get_data()[0]['KEL_NAME'] == 'KEBON BAWANG'
geom = res[0][0]
vals = res[0][1]
assert numpy.allclose(vals[17], 1481.98)
assert numpy.allclose(geom[17][0], 106.88746869) # LON
assert numpy.allclose(geom[17][1], -6.11493812) # LAT
# Then run and test the high level interpolation function
# t0 = time.time()
P = interpolate_polygon_raster(H, E,
layer_name='poly2raster_test',
attribute_name='grid_value')
# print 'High level function took %i seconds' % (time.time() - t0)
# P.write_to_file('polygon_raster_interpolation_example_big.shp')
# Characterisation tests (values verified using QGIS)
attributes = P.get_data()[17]
geometry = P.get_geometry()[17]
assert attributes['RW'] == 'RW 01'
assert attributes['KAB_NAME'] == 'JAKARTA UTARA'
assert attributes['KEC_NAME'] == 'TANJUNG PRIOK'
assert attributes['KEL_NAME'] == 'KEBON BAWANG'
assert attributes['polygon_id'] == 0
assert numpy.allclose(attributes['grid_value'], 1481.984)
assert numpy.allclose(geometry[0], 106.88746869) # LON
assert numpy.allclose(geometry[1], -6.11493812) # LAT
# A second characterisation test
attributes = P.get_data()[10000]
geometry = P.get_geometry()[10000]
assert attributes['RW'] == 'RW 06'
assert attributes['KAB_NAME'] == 'JAKARTA UTARA'
assert attributes['KEC_NAME'] == 'PENJARINGAN'
assert attributes['KEL_NAME'] == 'KAMAL MUARA'
assert attributes['polygon_id'] == 93
assert numpy.allclose(attributes['grid_value'], 715.6508)
assert numpy.allclose(geometry[0], 106.74092731) # LON
assert numpy.allclose(geometry[1], -6.1081538) # LAT
# A third characterisation test
attributes = P.get_data()[99000]
geometry = P.get_geometry()[99000]
assert attributes['RW'] == 'RW 08'
assert attributes['KAB_NAME'] == 'JAKARTA TIMUR'
assert attributes['KEC_NAME'] == 'CAKUNG'
assert attributes['KEL_NAME'] == 'CAKUNG TIMUR'
assert attributes['polygon_id'] == 927
assert numpy.allclose(attributes['grid_value'], 770.7628)
assert numpy.allclose(geometry[0], 106.9675237) # LON
assert numpy.allclose(geometry[1], -6.16966499) # LAT
test_polygon_hazard_and_raster_exposure_big.slow = True
def test_polygon_hazard_and_raster_exposure_small(self):
"""Exposure rasters can be clipped by polygon exposure
This is a test for the basic machinery needed for issue #91
"""
# Name input files
polyhazard = join(TESTDATA, 'test_polygon_on_test_grid.shp')
population = join(TESTDATA, 'test_grid.asc')
# Get layers using API
H = read_layer(polyhazard)
E = read_layer(population)
N = len(H)
assert N == 4
# Run underlying clipping routine
res0 = clip_grid_by_polygons(E.get_data(),
E.get_geotransform(),
H.get_geometry(as_geometry_objects=True))
assert len(res0) == N
# Run higher level interpolation routine
P = interpolate_polygon_raster(H, E,
layer_name='poly2raster_test',
attribute_name='grid_value')
# Verify result (numbers obtained from using QGIS)
# P.write_to_file('poly2raster_test.shp')
attributes = P.get_data()
geometry = P.get_geometry()
# Polygon 0
assert attributes[0]['id'] == 0
assert attributes[0]['name'] == 'A'
assert numpy.allclose(attributes[0]['number'], 31415)
assert numpy.allclose(attributes[0]['grid_value'], 50.8147)
assert attributes[0]['polygon_id'] == 0
assert attributes[1]['id'] == 0
assert attributes[1]['name'] == 'A'
assert numpy.allclose(geometry[1][0], 96.97137053) # Lon
assert numpy.allclose(geometry[1][1], -5.349657148) # Lat
assert numpy.allclose(attributes[1]['number'], 31415)
assert numpy.allclose(attributes[1]['grid_value'], 3)
assert attributes[1]['polygon_id'] == 0
assert attributes[3]['id'] == 0
assert attributes[3]['name'] == 'A'
assert numpy.allclose(attributes[3]['number'], 31415)
assert numpy.allclose(attributes[3]['grid_value'], 50.127)
assert attributes[3]['polygon_id'] == 0
# Polygon 1
assert attributes[6]['id'] == 1
assert attributes[6]['name'] == 'B'
assert numpy.allclose(attributes[6]['number'], 13)
assert numpy.allclose(attributes[6]['grid_value'], -15)
assert attributes[6]['polygon_id'] == 1
assert attributes[11]['id'] == 1
assert attributes[11]['name'] == 'B'
assert numpy.allclose(attributes[11]['number'], 13)
assert numpy.isnan(attributes[11]['grid_value'])
assert attributes[11]['polygon_id'] == 1
assert attributes[13]['id'] == 1
assert attributes[13]['name'] == 'B'
assert numpy.allclose(geometry[13][0], 97.063559372) # Lon
assert numpy.allclose(geometry[13][1], -5.472621404) # Lat
assert numpy.allclose(attributes[13]['number'], 13)
assert numpy.allclose(attributes[13]['grid_value'], 50.8258)
assert attributes[13]['polygon_id'] == 1
# Polygon 2 (overlapping)
assert attributes[16]['id'] == 2
assert attributes[16]['name'] == 'Intersecting'
assert numpy.allclose(attributes[16]['number'], 100)
assert numpy.allclose(attributes[16]['grid_value'], 50.9574)
assert attributes[16]['polygon_id'] == 2
assert attributes[21]['id'] == 2
assert attributes[21]['name'] == 'Intersecting'
assert numpy.allclose(attributes[21]['number'], 100)
assert numpy.allclose(attributes[21]['grid_value'], 50.2238)
# Polygon 3
assert attributes[23]['id'] == 3
assert attributes[23]['name'] == 'D'
assert numpy.allclose(geometry[23][0], 97.0021116) # Lon
assert numpy.allclose(geometry[23][1], -5.503362468) # Lat
assert numpy.allclose(attributes[23]['number'], -50)
assert numpy.allclose(attributes[23]['grid_value'], 50.0377)
assert attributes[23]['polygon_id'] == 3
def test_tagging_polygons_by_raster_values(self):
"""Polygons can be tagged by raster values
This is testing a simple application of clip_grid_by_polygons
"""
# Name input files
polygon = join(TESTDATA, 'test_polygon_on_test_grid.shp')
grid = join(TESTDATA, 'test_grid.asc')
# Get layers using API
G = read_layer(grid)
P = read_layer(polygon)
# Run tagging routine
R = tag_polygons_by_grid(P, G, threshold=50.85, tag='tag')
assert len(R) == len(P)
data = R.get_data()
for d in data:
assert 'tag' in d
# Check against inspection with QGIS. Only polygon 1 and 2
# contain grid points with values greater than 50.85
assert data[0]['tag'] is False
assert data[1]['tag'] is True
assert data[2]['tag'] is True
assert data[3]['tag'] is False
def test_polygon_hazard_with_holes_and_raster_exposure(self):
"""Rasters can be clipped by polygons (with holes)
This is testing that a collection of polygons - some with holes -
can correctly clip and tag raster points.
"""
# Name input files
polyhazard = join(TESTDATA, 'donut.shp')
population = join(TESTDATA, 'pop_merapi_clip.tif')
# Get layers using API
H = read_layer(polyhazard)
E = read_layer(population)
N = len(H)
assert N == 10
# Characterisation test
assert H.get_data()[9]['KRB'] == 'Kawasan Rawan Bencana II'
# Then run and test the high level interpolation function
P = interpolate_polygon_raster(H, E,
layer_name='poly2raster_test',
attribute_name='grid_value')
# Possibly write result to file for visual inspection, e.g. with QGIS
# P.write_to_file('polygon_raster_interpolation_example_holes.shp')
# Characterisation tests (values verified using QGIS)
# In internal polygon
attributes = P.get_data()[43]
# geometry = P.get_geometry()[43]
assert attributes['KRB'] == 'Kawasan Rawan Bencana III'
assert attributes['polygon_id'] == 8
# In polygon ring
attributes = P.get_data()[222]
# geometry = P.get_geometry()[222]
assert attributes['KRB'] == 'Kawasan Rawan Bencana II'
assert attributes['polygon_id'] == 9
# In one of the outer polygons
attributes = P.get_data()[26]
# geometry = P.get_geometry()[26]
assert attributes['KRB'] == 'Kawasan Rawan Bencana I'
assert attributes['polygon_id'] == 4
test_polygon_hazard_with_holes_and_raster_exposure.slow = True
def test_data_sources_are_carried_forward(self):
"""Data sources are carried forward to impact layer
"""
haz_filename = 'Flood_Current_Depth_Jakarta_geographic.asc'
# File names for hazard level and exposure
hazard_filename = '%s/%s' % (HAZDATA, haz_filename)
exposure_filename = ('%s/OSM_building_polygons_20110905.shp'
% TESTDATA)
# Calculate impact using API
H = read_layer(hazard_filename)
E = read_layer(exposure_filename)
H_tit = H.get_keywords()['title']
E_tit = E.get_keywords()['title']
H_src = H.get_keywords()['source']
E_src = E.get_keywords()['source']
plugin_name = 'FloodBuildingImpactFunction'
plugin_list = get_plugins(plugin_name)
assert len(plugin_list) == 1
assert plugin_list[0].keys()[0] == plugin_name
IF = plugin_list[0][plugin_name]
impact_vector = calculate_impact(layers=[H, E],
impact_fcn=IF)
assert impact_vector.get_keywords()['hazard_title'] == H_tit
assert impact_vector.get_keywords()['exposure_title'] == E_tit
assert impact_vector.get_keywords()['hazard_source'] == H_src
assert impact_vector.get_keywords()['exposure_source'] == E_src
test_data_sources_are_carried_forward.slow = True
def test_raster_vector_interpolation_exception(self):
"""Exceptions are caught by interpolate_raster_points
"""
hazard_filename = (
'%s/tsunami_max_inundation_depth_4326.tif' % TESTDATA)
exposure_filename = ('%s/tsunami_building_exposure.shp' % TESTDATA)
# Calculate impact using API
H = read_layer(hazard_filename)
E = read_layer(exposure_filename)
try:
interpolate_raster_vector_points(H, E, mode='oexoeua')
except InaSAFEError:
pass
else:
msg = 'Should have raised InaSAFEError'
raise Exception(msg)
# FIXME (Ole): Try some other error conditions
def test_interpolation_wrapper(self):
"""Interpolation library works for linear function
"""
# Create test data
lon_ul = 100 # Longitude of upper left corner
lat_ul = 10 # Latitude of upper left corner
numlon = 8 # Number of longitudes
numlat = 5 # Number of latitudes
# Define array where latitudes are rows and longitude columns
A = numpy.zeros((numlat, numlon))
# Establish coordinates for lower left corner
lat_ll = lat_ul - numlat
lon_ll = lon_ul
# Define pixel centers along each direction
longitudes = numpy.linspace(lon_ll + 0.5,
lon_ll + numlon - 0.5, numlon)
latitudes = numpy.linspace(lat_ll + 0.5,
lat_ll + numlat - 0.5, numlat)
# Define raster with latitudes going bottom-up (south to north).
# Longitudes go left-right (west to east)
for i in range(numlat):
for j in range(numlon):
A[numlat - 1 - i, j] = linear_function(
longitudes[j], latitudes[i])
# Test first that original points are reproduced correctly
for i, eta in enumerate(latitudes):
for j, xi in enumerate(longitudes):
val = interpolate_raster(longitudes, latitudes, A,
[(xi, eta)], mode='linear')[0]
assert numpy.allclose(val,
linear_function(xi, eta),
rtol=1e-12, atol=1e-12)
# Then test that genuinly interpolated points are correct
xis = numpy.linspace(lon_ll + 1, lon_ll + numlon - 1, 10 * numlon)
etas = numpy.linspace(lat_ll + 1, lat_ll + numlat - 1, 10 * numlat)
for xi in xis:
for eta in etas:
val = interpolate_raster(longitudes, latitudes, A,
[(xi, eta)], mode='linear')[0]
assert numpy.allclose(val,
linear_function(xi, eta),
rtol=1e-12, atol=1e-12)
test_interpolation_wrapper.slow = True
def test_interpolation_functions(self):
"""Interpolation using Raster and Vector objects
"""
# Create test data
lon_ul = 100 # Longitude of upper left corner
lat_ul = 10 # Latitude of upper left corner
numlon = 8 # Number of longitudes
numlat = 5 # Number of latitudes
dlon = 1
dlat = -1
# Define array where latitudes are rows and longitude columns
A = numpy.zeros((numlat, numlon))
# Establish coordinates for lower left corner
lat_ll = lat_ul - numlat
lon_ll = lon_ul
# Define pixel centers along each direction
longitudes = numpy.linspace(lon_ll + 0.5,
lon_ll + numlon - 0.5,
numlon)
latitudes = numpy.linspace(lat_ll + 0.5,
lat_ll + numlat - 0.5,
numlat)
# Define raster with latitudes going bottom-up (south to north).
# Longitudes go left-right (west to east)
for i in range(numlat):
for j in range(numlon):
A[numlat - 1 - i, j] = linear_function(longitudes[j],
latitudes[i])
# Write array to a raster file
geotransform = (lon_ul, dlon, 0, lat_ul, 0, dlat)
projection = ('GEOGCS["GCS_WGS_1984",'
'DATUM["WGS_1984",'
'SPHEROID["WGS_1984",6378137.0,298.257223563]],'
'PRIMEM["Greenwich",0.0],'
'UNIT["Degree",0.0174532925199433]]')
raster_filename = unique_filename(suffix='.tif')
write_raster_data(A,
projection,
geotransform,
raster_filename)
# Write test interpolation point to a vector file
coordinates = []
for xi in longitudes:
for eta in latitudes:
coordinates.append((xi, eta))
vector_filename = unique_filename(suffix='.shp')
write_vector_data(data=None,
projection=projection,
geometry=coordinates,
filename=vector_filename)
# Read both datasets back in
R = read_layer(raster_filename)
V = read_layer(vector_filename)
# Then test that axes and data returned by R are correct
x, y = R.get_geometry() # pylint: disable=W0633,W0632
msg = 'X axes was %s, should have been %s' % (longitudes, x)
assert numpy.allclose(longitudes, x), msg
msg = 'Y axes was %s, should have been %s' % (latitudes, y)
assert numpy.allclose(latitudes, y), msg
AA = R.get_data()
msg = 'Raster data was %s, should have been %s' % (AA, A)
assert numpy.allclose(AA, A), msg
# Test interpolation function with default layer_name
I = assign_hazard_values_to_exposure_data(R, V, attribute_name='value')
# msg = 'Got name %s, expected %s' % (I.get_name(), V.get_name())
# assert V.get_name() == I.get_name(), msg
Icoordinates = I.get_geometry()
Iattributes = I.get_data()
assert numpy.allclose(Icoordinates, coordinates)
# Test that interpolated points are correct
for i, (xi, eta) in enumerate(Icoordinates):
z = Iattributes[i]['value']
# print xi, eta, z, linear_function(xi, eta)
assert numpy.allclose(z, linear_function(xi, eta),
rtol=1e-12)
# FIXME (Ole): Need test for values outside grid.
# They should be NaN or something
# Cleanup
# FIXME (Ole): Shape files are a collection of files. How to remove?
os.remove(vector_filename)
def test_interpolation_lembang(self):
"""Interpolation using Lembang data set
"""
# Name file names for hazard level, exposure and expected fatalities
hazard_filename = '%s/lembang_mmi_hazmap.asc' % TESTDATA
exposure_filename = '%s/test_buildings.shp' % TESTDATA
# Read input data
hazard_raster = read_layer(hazard_filename)
mmi_min, mmi_max = hazard_raster.get_extrema()
exposure_vector = read_layer(exposure_filename)
coordinates = exposure_vector.get_geometry()
attributes = exposure_vector.get_data()
# Test interpolation function
I = assign_hazard_values_to_exposure_data(hazard_raster,
exposure_vector,
attribute_name='MMI')
Icoordinates = I.get_geometry()
Iattributes = I.get_data()
assert numpy.allclose(Icoordinates, coordinates)
# Check that interpolated MMI was done as expected
fid = open('%s/test_buildings_percentage_loss_and_mmi.txt' % TESTDATA)
reference_points = []
MMI = []
for line in fid.readlines()[1:]:
fields = line.strip().split(',')
lon = float(fields[4][1:-1])
lat = float(fields[3][1:-1])
mmi = float(fields[-1][1:-1])
reference_points.append((lon, lat))
MMI.append(mmi)
# Verify that coordinates are consistent
msg = 'Interpolated coordinates do not match those of test data'
assert numpy.allclose(Icoordinates, reference_points), msg
# Verify interpolated MMI with test result
for i in range(len(MMI)):
calculated_mmi = Iattributes[i]['MMI']
# Check that interpolated points are within range
msg = ('Interpolated MMI %f was outside extrema: '
'[%f, %f]. ' % (calculated_mmi, mmi_min, mmi_max))
assert mmi_min <= calculated_mmi <= mmi_max, msg
# Check that result is within 2% - this is good enough
# as this was calculated using EQRM and thus different.
assert numpy.allclose(calculated_mmi, MMI[i], rtol=0.02)
# Check that all original attributes were carried through
# according to issue #101
for key in attributes[i]:
msg = 'Expected key %s in interpolated attributes' % key
assert key in Iattributes[i], msg
Ival = Iattributes[i][key]
val = attributes[i][key]
msg = ('Interpolated attribute %s did not have the '
'expected value %s. I got %s' % (key, val, Ival))
try:
assert Ival == val, msg
except AssertionError:
assert numpy.allclose(Ival, val, rtol=1.0e-6), msg
test_interpolation_lembang.slow = True
def test_interpolation_tsunami(self):
"""Interpolation using tsunami data set works
This is test for issue #19 about interpolation overshoot
"""
# Name file names for hazard level, exposure and expected fatalities
hazard_filename = (
'%s/tsunami_max_inundation_depth_4326.tif' % TESTDATA)
exposure_filename = ('%s/tsunami_building_exposure.shp' % TESTDATA)
# Read input data
hazard_raster = read_layer(hazard_filename)
depth_min, depth_max = hazard_raster.get_extrema()
exposure_vector = read_layer(exposure_filename)
coordinates = exposure_vector.get_geometry()
# Test interpolation function
I = assign_hazard_values_to_exposure_data(
hazard_raster, exposure_vector, attribute_name='depth')
Icoordinates = I.get_geometry()
Iattributes = I.get_data()
assert numpy.allclose(Icoordinates, coordinates)
# Verify interpolated values with test result
for i in range(len(Icoordinates)):
interpolated_depth = Iattributes[i]['depth']
# Check that interpolated points are within range
msg = ('Interpolated depth %f at point %i was outside extrema: '
'[%f, %f]. ' % (interpolated_depth, i,
depth_min, depth_max))
if not numpy.isnan(interpolated_depth):
assert depth_min <= interpolated_depth <= depth_max, msg
def test_interpolation_tsunami_maumere(self):
"""Interpolation using tsunami data set from Maumere
This is a test for interpolation (issue #19)
"""
# Name file names for hazard level, exposure and expected fatalities
hazard_filename = ('%s/maumere_aos_depth_20m_land_wgs84.asc'
% HAZDATA)
exposure_filename = ('%s/maumere_pop_prj.shp' % TESTDATA)
# Read input data
H = read_layer(hazard_filename)
depth_min, depth_max = H.get_extrema()
# Compare extrema to values read off QGIS for this layer
assert numpy.allclose([depth_min, depth_max], [0.0, 16.68],
rtol=1.0e-6, atol=1.0e-10)
E = read_layer(exposure_filename)
coordinates = E.get_geometry()
attributes = E.get_data()
# Test the interpolation function
I = assign_hazard_values_to_exposure_data(H, E, attribute_name='depth')
Icoordinates = I.get_geometry()
Iattributes = I.get_data()
assert numpy.allclose(Icoordinates, coordinates)
N = len(Icoordinates)
assert N == 891
# Verify interpolated values with test result
for i in range(N):
interpolated_depth = Iattributes[i]['depth']
pointid = attributes[i]['POINTID']
if pointid == 263:
# print i, pointid, attributes[i],
# print interpolated_depth, coordinates[i]
# Check that location is correct
assert numpy.allclose(coordinates[i],
[122.20367299, -8.61300358])
# This is known to be outside inundation area so should
# near zero
print
assert numpy.allclose(interpolated_depth, 0.0,
rtol=1.0e-12, atol=1.0e-12)
if pointid == 148:
# Check that location is correct
assert numpy.allclose(coordinates[i],
[122.2045912, -8.608483265])
# This is in an inundated area with a surrounding depths of
# 4.531, 3.911
# 2.675, 2.583
assert interpolated_depth < 4.531
assert interpolated_depth < 3.911
assert interpolated_depth > 2.583
assert interpolated_depth > 2.675
# This is a characterisation test for bilinear interpolation
# Akbar - 20 Feb 2014:
# I changed the tolerance between interpolated_depth and the
# expected result. The expected result when we do the full
# safe test is 3.62477202599, while it is 3.62477204455 when
# we do single test (computer also needs to rest?). The rtol
# and atol was 1.0e-12
print 'Interpolated depth is: %.12f' % interpolated_depth
assert numpy.allclose([interpolated_depth], [3.62477204455],
rtol=1.0e-8, atol=1.0e-8)
# Check that interpolated points are within range
msg = ('Interpolated depth %f at point %i was outside extrema: '
'[%f, %f]. ' % (interpolated_depth, i,
depth_min, depth_max))
if not numpy.isnan(interpolated_depth):
assert depth_min <= interpolated_depth <= depth_max, msg
test_interpolation_tsunami_maumere.slow = True
def test_polygon_clipping(self):
"""Clipping using real polygon and point data from Maumere
"""
# Test data
polygon_filename = ('%s/test_poly.txt' % TESTDATA) # Polygon 799
points_filename = ('%s/test_points.txt' % TESTDATA)
# Read
polygon = []
fid = open(polygon_filename)
for line in fid.readlines():
fields = line.strip().split(',')
polygon.append([float(fields[0]), float(fields[1])])
polygon = ensure_numeric(polygon)
points = []
fid = open(points_filename)
for line in fid.readlines():
fields = line.strip().split(',')
points.append([float(fields[0]), float(fields[1])])
points = ensure_numeric(points)
# Clip
inside, outside = separate_points_by_polygon(points, polygon)
# Expected number of points inside
assert len(inside) == 458
# First 10 inside
assert numpy.alltrue(inside[:10] == [2279, 2290, 2297, 2306, 2307,
2313, 2316, 2319, 2321, 2322])
# Last 10 outside
assert numpy.alltrue(outside[-10:] == [3519, 3520, 3521, 3522, 3523,
3524, 3525, 3526, 3527, 3528])
# Store for viewing in e.g. QGis
if False: # True:
Vector(geometry=[polygon]).write_to_file('test_poly.shp')
pts_inside = points[inside]
Vector(geometry=pts_inside).write_to_file('test_points_in.shp')
pts_outside = points[outside]
Vector(geometry=pts_outside).write_to_file('test_points_out.shp')
test_polygon_clipping.slow = True
def test_interpolation_from_polygons_one_poly(self):
"""Point interpolation using one polygon from Maumere works
This is a test for interpolation (issue #48)
"""
# Name file names for hazard level and exposure
hazard_filename = ('%s/tsunami_polygon_WGS84.shp' % TESTDATA)
exposure_filename = ('%s/building_Maumere.shp' % TESTDATA)
# Read input data
H = read_layer(hazard_filename)
H_attributes = H.get_data()
H_geometry = H.get_geometry()
# Cut down to make test quick
# Polygon #799 is the one used in separate test
H = Vector(data=H_attributes[799:800],
geometry=H_geometry[799:800],
projection=H.get_projection())
# H.write_to_file('MM_799.shp') # E.g. to view with QGis
E = read_layer(exposure_filename)
E_attributes = E.get_data()
# Test interpolation function
I = assign_hazard_values_to_exposure_data(H, E,
layer_name='depth')
I_attributes = I.get_data()
msg = 'Expected "depth", got %s' % I.get_name()
assert I.get_name() == 'depth', msg
N = len(I_attributes)
assert N == len(E_attributes)
# Assert that expected attribute names exist
I_names = I.get_attribute_names()
H_names = H.get_attribute_names()
E_names = E.get_attribute_names()
for name in H_names:
msg = 'Did not find hazard name "%s" in %s' % (name, I_names)
assert name in I_names, msg
for name in E_names:
msg = 'Did not find exposure name "%s" in %s' % (name, I_names)
assert name in I_names, msg
# Verify interpolated values with test result
count = 0
for i in range(N):
category = I_attributes[i]['Category']
if category is not None:
count += 1
msg = ('Expected 458 points tagged with category, '
'but got only %i' % count)
assert count == 458, msg
test_interpolation_from_polygons_one_poly.slow = True
def test_interpolation_from_polygons_multiple(self):
"""Point interpolation using multiple polygons from Maumere works
This is a test for interpolation (issue #48)
"""
# FIXME (Ole): Really should move this and subsequent tests to
# test_io.py
# Name file names for hazard and exposure
hazard_filename = ('%s/tsunami_polygon_WGS84.shp' % TESTDATA)
exposure_filename = ('%s/building_Maumere.shp' % TESTDATA)
# Read input data
H = read_layer(hazard_filename)
H_attributes = H.get_data()
H_geometry = H.get_geometry()
# Full version
H = Vector(data=H_attributes,
geometry=H_geometry,
projection=H.get_projection())
E = read_layer(exposure_filename)
E_attributes = E.get_data()
# Test interpolation function
I = assign_hazard_values_to_exposure_data(H, E,
layer_name='depth')
I_attributes = I.get_data()
N = len(I_attributes)
assert N == len(E_attributes)
# Assert that expected attribute names exist
I_names = I.get_attribute_names()
H_names = H.get_attribute_names()
E_names = E.get_attribute_names()
for name in H_names:
msg = 'Did not find hazard name "%s" in %s' % (name, I_names)
assert name in I_names, msg
for name in E_names:
msg = 'Did not find exposure name "%s" in %s' % (name, I_names)
assert name in I_names, msg
# Verify interpolated values with test result
counts = {}
for i in range(N):
attrs = I_attributes[i]
msg = ('Did not find default attribute %s in %s'
% (DEFAULT_ATTRIBUTE, attrs.keys()))
assert DEFAULT_ATTRIBUTE in attrs, msg
# Count items using default attribute
if DEFAULT_ATTRIBUTE not in counts:
counts[DEFAULT_ATTRIBUTE] = 0
counts['Not ' + DEFAULT_ATTRIBUTE] = 0
if attrs[DEFAULT_ATTRIBUTE]:
counts[DEFAULT_ATTRIBUTE] += 1
else:
counts['Not ' + DEFAULT_ATTRIBUTE] += 1
# Count items in each specific category
category = attrs['Category']