-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathdem.py
4284 lines (3353 loc) · 189 KB
/
dem.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
#Functions for demMethods calculations typical of geomorphology
#Developed by Sam Johnstone, January 2015, samuelj@stanford.edu , johnsamstone@gmail.com
#Not all functions are benchmarked
#If you somehow have this, and have never spoken to me, please reach out
#- I'd be curious to hear what you are doing (maybe I can even help with something!)
from osgeo import gdal, ogr, osr # Used to load gis in files
import os # Used to join file paths, iteract with os in other ways..
import glob # Used for finding files that I want to mosaic (by allowing wildcard searches of the filesystem)
import heapq # Used for constructing priority queue, which is used for filling dems
import numpy as np # Used for tons o stuff, keeping most data stored as numpy arrays
import subprocess # Used to run gdal_merge.py from the command line
from numpy import uint8, int8, float64
from matplotlib import pyplot as plt
import sys
from scipy import stats
from . import error as Error
try:
import statsmodels.api as sm
except:
print('Warning: no statsmodels present. If you want to compute steepness, you will need to install this.')
sys.setrecursionlimit(1000000)
class GDALMixin(object):
def _get_projection_from_EPSG_projection_code(self, EPSGprojectionCode):
# Get raster projection
srs = osr.SpatialReference()
srs.ImportFromEPSG(EPSGprojectionCode)
return srs.ExportToWkt()
def _get_gdal_type_for_numpy_type(self, numpy_type):
from numpy import float64, uint8, uint16, int16, uint32, int32, float32, complex64
from osgeo.gdal import GDT_Byte, GDT_UInt16, GDT_Int16, GDT_UInt32, GDT_Int32, GDT_Float32, GDT_Float64, GDT_CFloat64, GDT_Unknown
type_map = { uint8: GDT_Byte,
uint16: GDT_UInt16,
int16: GDT_Int16,
uint32: GDT_UInt32,
int32: GDT_Int32,
float32: GDT_Float32,
float64: GDT_Float64,
complex64: GDT_CFloat64 }
gdal_type = type_map.get(numpy_type)
if gdal_type is None:
return GDT_Unknown
else:
return gdal_type
def _get_numpy_type_for_gdal_type(self, gdal_type):
from numpy import float64, uint8, uint16, int16, uint32, int32, float32, complex64
from osgeo.gdal import GDT_Byte, GDT_UInt16, GDT_Int16, GDT_UInt32, GDT_Int32, GDT_Float32, GDT_Float64, GDT_CFloat64
type_map = { GDT_Byte: uint8,
GDT_UInt16: uint16,
GDT_Int16: int16,
GDT_UInt32: uint32,
GDT_Int32: int32,
GDT_Float32: float32,
GDT_Float64: float64,
GDT_CFloat64: complex64}
numpy_type = type_map.get(gdal_type)
if numpy_type is None:
return float64
else:
return numpy_type
def _readGDALFile(self, filename, dtype):
gdal_file = gdal.Open(filename)
geoTransform, nx, ny, data = self._read_GDAL_dataset(gdal_file, dtype)
gdal_file = None
return geoTransform, nx, ny, data
def _read_GDAL_dataset(self, gdal_dataset, dtype):
band = gdal_dataset.GetRasterBand(1)
nodata = band.GetNoDataValue()
data = band.ReadAsArray().astype(dtype)
nodata_elements = np.where(data == nodata)
from numpy import uint8
if dtype is not uint8:
data[nodata_elements] = np.NAN
geoTransform = gdal_dataset.GetGeoTransform()
nx = gdal_dataset.RasterXSize
ny = gdal_dataset.RasterYSize
return geoTransform, nx, ny, data
def _getGeoRefInfo(self, gdalDataset):
#Get info needed to initialize new dataset
nx = gdalDataset.RasterXSize
ny = gdalDataset.RasterYSize
#Write geographic information
geoTransform = gdalDataset.GetGeoTransform() # Steal the coordinate system from the old dataset
projection = gdalDataset.GetProjection() # Steal the Projections from the old dataset
return nx, ny, projection, geoTransform
def getDEMcoords(self, GdalData, dx):
#Get grid size
nx, ny = GdalData.RasterXSize, GdalData.RasterYSize
#Get information about the spatial reference
(upper_left_x, x_size, x_rotation, upper_left_y, y_rotation, y_size) = GdalData.GetGeoTransform()
xllcenter = upper_left_x + dx/2.0 # x coordinate center of lower left pxl
yllcenter = upper_left_y - (ny-0.5)*dx # y coordinate center of lower left pxl
#Create arrays of the x and y coordinates of each pixel (the axes)
xcoordinates = [x*dx + xllcenter for x in range(nx)]
ycoordinates = [y*dx + yllcenter for y in range(ny)][::-1] #Flip the ys so that the first row corresponds to the first entry of this array
return xcoordinates, ycoordinates
def _create_gdal_representation_from_array(self, georef_info, GDALDRIVERNAME, array_data, dtype, outfile_path='name', dst_options = [], multiple_bands = False):
#A function to write the data in the numpy array arrayData into a georeferenced dataset of type
# specified by GDALDRIVERNAME, a string, options here: http://www.gdal.org/formats_list.html
# This is accomplished by copying the georeferencing information from an existing GDAL dataset,
# provided by createDataSetFromArray
#Initialize new data
drvr = gdal.GetDriverByName(GDALDRIVERNAME) # Get the desired driver
bands = 1 if multiple_bands is False else len(array_data)
outRaster = drvr.Create(outfile_path, georef_info.nx, georef_info.ny, bands , self._get_gdal_type_for_numpy_type(dtype), dst_options) # Open the file
#Write geographic information
outRaster.SetGeoTransform(georef_info.geoTransform) # Steal the coordinate system from the old dataset
if georef_info.projection != 0:
outRaster.SetProjection(georef_info.projection) # Steal the Projections from the old dataset
#Write the array
if not multiple_bands:
outRaster.GetRasterBand(1).WriteArray(array_data) # Writes my array to the raster
else:
for i in range(len(array_data)):
print('writing band ' + str(i) + "/" + str(bands))
outRaster.GetRasterBand(i+1).WriteArray(array_data[i])
return outRaster
def _clipRasterToRaster(self, input_gdal_dataset, clipping_gdal_dataset, dtype):
# Source
src_proj = input_gdal_dataset.GetProjection()
src_geotrans = input_gdal_dataset.GetGeoTransform()
# We want a section of source that matches this:
match_proj = clipping_gdal_dataset.GetProjection()
match_geotrans = clipping_gdal_dataset.GetGeoTransform()
wide = clipping_gdal_dataset.RasterXSize
high = clipping_gdal_dataset.RasterYSize
# Output / destination
dst = gdal.GetDriverByName('MEM').Create('name', wide, high, 1, dtype)
dst.SetGeoTransform( match_geotrans )
dst.SetProjection( match_proj)
# Do the work
gdal.ReprojectImage(input_gdal_dataset, dst, src_proj, match_proj, gdal.GRA_Bilinear)
# gdal.ReprojectImage(src, dst, None, None, GRA_Bilinear)
# gdal.ReprojectImage(dst, src, None, None, GRA_Bilinear)
#
return dst
def _clipRasterToShape(self, raster, shape):
# TODO: This needs implementation to write out the raster and shape files, execute the warp, read in the resulting file, and delete the filenames. What a hack.
pass
# drvr = gdal.GetDriverByName(GdalDriver)
# drvr.Create(outputFilename,1,1,1)
# warp= 'gdalwarp -cutline \'%s\' -crop_to_cutline -dstalpha \'%s\' \'%s\'' % (shpFilename, srcFilename, outputFilename)
#warp= 'gdalwarp -cutline \'%s\' -crop_to_cutline \'%s\' \'%s\'' % (shpFilename, srcFilename, outputFilename)
#os.system(warp)
def _convertToUTM(self, dataset, dx, utmZone):
#Get Spatial reference info
oldRef = osr.SpatialReference() # Initiate a spatial reference
oldRef.ImportFromWkt(dataset.GetProjectionRef()) # Clone the spatial reference from the dataset
newRef = osr.SpatialReference()
newRef.SetUTM(abs(utmZone), utmZone > 0)
#Set up the transform
transform = osr.CoordinateTransformation(oldRef, newRef) # Create the coordinate transform object
tVect = dataset.GetGeoTransform() # Get the coordinate transform vector
nx, ny = dataset.RasterXSize, dataset.RasterYSize # Size of the original raster
(ulx, uly, ulz ) = transform.TransformPoint(tVect[0], tVect[3])
(lrx, lry, lrz ) = transform.TransformPoint(tVect[0] + tVect[1]*nx, tVect[3] + tVect[5]*ny)
memDrv = gdal.GetDriverByName('MEM') # Create a gdal driver in memory
dataOut = memDrv.Create('name', int((lrx - ulx)/dx), int((uly - lry)/dx), 1, gdal.GDT_Float32)
newtVect = (ulx, dx, tVect[2], uly, tVect[4], -dx)
dataOut.SetGeoTransform(newtVect) # Set the new geotransform
dataOut.SetProjection(newRef.ExportToWkt())
# Perform the projection/resampling
res = gdal.ReprojectImage(dataset, dataOut, oldRef.ExportToWkt(), newRef.ExportToWkt(), gdal.GRA_Cubic)
return dataOut
def _getRasterGeoTransformFromAsciiRaster(self, fileName):
#Read in the components of the geotransform from the raster, BEWARE! This
#is specific to how some matlab/ C scripts I have write these rasters. I believe
#this is that standard arc ascii raster export format, but could be wrong
georef_data = dict()
with open(fileName, "r") as ascii_file:
for _ in range(6):
line = ascii_file.readline()
(key, value) = (line.split()[0], float(line.split()[-1]))
georef_data[key.lower()] = value
required_values = ('ncols', 'nrows', 'cellsize')
if len(set(required_values).difference(set(georef_data.keys()))) != 0:
raise Error.InputError('A/I ASCII grid error','The following properties are missing: ' + str(set(required_values).difference(set(georef_data.keys()))))
if georef_data.get('xllcorner') is None and georef_data.get('xllcenter') is None:
raise Error.InputError('A/I ASCII grid error','Neither XLLCorner nor XLLCenter is present.')
if georef_data.get('yllcorner') is None and georef_data.get('yllcenter') is None:
raise Error.InputError('A/I ASCII grid error','Neither YLLCorner nor YLLCenter is present.')
dx = georef_data.get('cellsize')
nx = int(georef_data.get('ncols'))
ny = int(georef_data.get('nrows'))
if georef_data.get('xllcenter') is not None:
xUL = georef_data.get('xllcenter') - (dx/2.0)
else:
xUL = georef_data.get('xllcorner');
if georef_data.get('yllcenter') is not None:
yUL = (georef_data.get('yllcenter') - (dx/2.0)) + dx*ny
else:
yUL = georef_data.get('yllcorner') + dx*ny
return (xUL, dx, 0, yUL, 0, -dx), nx, ny
def _writeArcAsciiRaster(self, georef_info, outfile_path, np_array_data, nodata_value, format_string):
#A function to write the data stored in the numpy array npArrayData to a ArcInfo Text grid. Gdal doesn't
#allow creation of these types of data for whatever reason
header = "ncols %s\n" % georef_info.nx
header += "nrows %s\n" % georef_info.ny
header += "xllcenter %s\n" % georef_info.xllcenter
header += "yllcenter %s\n" % georef_info.yllcenter
header += "cellsize %s\n" % georef_info.dx
header += "NODATA_value %s" % nodata_value
np.savetxt(outfile_path, np_array_data, header=header, fmt=format_string, comments='')
def _asciiRasterToMemory(self, fileName):
# the geotransfrom structured as (xUL, dx, skewX, yUL, scewY, -dy)
gt, nx, ny = self._getRasterGeoTransformFromAsciiRaster(fileName)
#Open gdal dataset
ds = gdal.Open(fileName)
#Prep output
memDrv = gdal.GetDriverByName('MEM') # Create a gdal driver in memory
dataOut = memDrv.CreateCopy('name', ds, 0) #Copy data to gdal driver
data = dataOut.ReadAsArray()
dataOut = None
data = self.dtype(data)
return gt, nx, ny, data
class GeographicGridMixin(object):
def _getUTMZone(self, dataset):
#Function to get the approximate UTM zone %NOTE: I need to check how east and west are handled...
#Utm zone boundary (zones are numbered in order, 1:60) #NEED TO DOUBLE CHECK THIS
westBound = np.array([-180 + x*6 for x in range(60)]) #west boundary of 6 degree UTM zone bounds
eastBound = np.array([-174 + x*6 for x in range(60)]) #east boundary of 6 degree UTM zone bounds
#Midpoint of dataset
tVect = dataset.GetGeoTransform() # Get the coordinate transform vector, (ulx, dx, xRot, uly, yRot, -dx)
nx, ny = dataset.RasterXSize, dataset.RasterYSize #Get the number of colums and rows
midLat = tVect[3]-tVect[1]*ny/2.0 #half way down the dataset
midLong = tVect[0]+tVect[1]*nx/2.0 #half way across the dataset
#Convert UTM zone to negative to distinguish it as south (if appropriate)
southMultiplier = 1
if midLat < 0:
southMultiplier = -1
#The utm zone, the index of the boundaries that surround the point incremented to account for pythons 0 indexing
zone = np.nonzero(np.logical_and(midLong > westBound, midLong < eastBound))[0] + 1
return zone*southMultiplier
def _getLatsLongsFromGeoTransform(self, geoTransform, nx, ny):
dLong = geoTransform[1]
dLat = geoTransform[5]
#Determine the location of the center of the first pixel of the data
xllcenter = geoTransform[0]+dLong/2.0
yllcenter = geoTransform[3]+dLat/2.0
#Assign the latitudinal (i.e. y direction) coordinates
lats = np.zeros(ny)
for i in range(len(lats)):
lats[i] = yllcenter + i*dLat
#Assign the longitudinal (i.e. x direction) coordinates
longs = np.zeros(nx)
for i in range(len(longs)):
longs[i] = xllcenter + i*dLong
return lats,longs
def _approximateDxFromGeographicData(self, geoTransform):
#Function to return the approximate grid spacing in Meters. Will return the closest integer value
dTheta = geoTransform[1] #Angular grid spacing
metersPerDegree = 110000 #110 km per degree (approximation)
return int(dTheta*metersPerDegree) #convert degrees to meters
def _area_per_pixel(self, *args, **kwargs):
if hasattr(self, '_GeographicGridMixin__app'):
return self._GeographicGridMixin__app
#Returns a grid of the area of each pixel within the domain specified by the gdalDataset
re = 6371.0 * 1000.0 #radius of the earth in meters
dLong = np.abs(self._georef_info.geoTransform[1])
dLat = np.abs(self._georef_info.geoTransform[5])
lats = self._georef_info.yllcenter + np.float64(range(self._georef_info.ny))*dLat
longs = self._georef_info.xllcenter + np.float64(range(self._georef_info.nx))*dLong
#Get the size of pixels in the lat and long direction
[LONG, LAT] = np.meshgrid(longs, lats)
LAT1 = np.radians(LAT - dLat / 2.0)
LAT2 = np.radians(LAT + dLat / 2.0)
LONG1 = np.radians(LONG - dLong / 2.0)
LONG2 = np.radians(LONG + dLong / 2.0)
initialAreas = np.flipud(np.abs((re**2)*(LONG1 - LONG2)*(np.sin(LAT2) - np.sin(LAT1))))
self.__app = initialAreas
return self.__app
def _mean_pixel_dimension(self, *args, **kwargs):
return np.sqrt(self._area_per_pixel())
class CalculationMixin(object):
def _calcFiniteSlopes(self, grid, dx, nx, ny):
# sx,sy = calcFiniteDiffs(elevGrid,dx)
# calculates finite differences in X and Y direction using the
# 2nd order/centered difference method.
# Applies a boundary condition such that the size and location
# of the grids in is the same as that out.
# Assign boundary conditions
Zbc = self.assignBCs(grid, nx, ny)
#Compute finite differences
Sx = (Zbc[1:-1, 2:] - Zbc[1:-1, :-2])/(2*dx)
Sy = (Zbc[2:,1:-1] - Zbc[:-2, 1:-1])/(2*dx)
return Sx, Sy
def assignBCs(self, grid, nx, ny):
# Pads the boundaries of a grid
# Boundary condition pads the boundaries with equivalent values
# to the data margins, e.g. x[-1,1] = x[1,1]
# This creates a grid 2 rows and 2 columns larger than the input
Zbc = np.zeros((ny + 2, nx + 2)) # Create boundary condition array
Zbc[1:-1,1:-1] = grid # Insert old grid in center
#Assign boundary conditions - sides
Zbc[0, 1:-1] = grid[0, :]
Zbc[-1, 1:-1] = grid[-1, :]
Zbc[1:-1, 0] = grid[:, 0]
Zbc[1:-1, -1] = grid[:,-1]
#Assign boundary conditions - corners
Zbc[0, 0] = grid[0, 0]
Zbc[0, -1] = grid[0, -1]
Zbc[-1, 0] = grid[-1, 0]
Zbc[-1, -1] = grid[-1, 0]
return Zbc
def calcFiniteCurv(self, grid, dx):
#C = calcFiniteCurv(elevGrid, dx)
#calculates finite differnces in X and Y direction using the centered difference method.
#Applies a boundary condition such that the size and location of the grids in is the same as that out.
#Assign boundary conditions
Zbc = self.assignBCs(grid,grid.shape[1],grid.shape[0])
#Compute finite differences
Cx = (Zbc[1:-1, 2:] - 2*Zbc[1:-1, 1:-1] + Zbc[1:-1, :-2])/dx**2
Cy = (Zbc[2:, 1:-1] - 2*Zbc[1:-1, 1:-1] + Zbc[:-2, 1:-1])/dx**2
return Cx+Cy
def calcContourCurvature(self, grid,dx):
# kt = (fxx*fy^2 - 2*fxyfxfy + fyy*fx^2)/((fx^2 + fy^2)*sqrt((fx^2 + fy^2)+1)
#Preallocate
Kt = np.zeros_like(grid)*np.nan
#First derivatives, 2nd order centered difference
fx = (grid[1:-1,2:] - grid[1:-1,:-2])/(dx*2)
fy = (grid[2:,1:-1] - grid[:-2,1:-1])/(dx*2)
#Second derivatives, 2nd order centered differece
fxx = (grid[1:-1,2:] - 2*grid[1:-1,1:-1] + grid[1:-1,:-2])/(dx**2)
fyy = (grid[2:,1:-1] - 2*grid[1:-1,1:-1] + grid[:-2,1:-1])/(dx**2);
#Partial derivative
fxy = (grid[2:,2:] - grid[2:,1:-1] - grid[1:-1,2:] + 2*grid[1:-1,1:-1] - grid[:-2,1:-1] - grid[1:-1,:-2] + grid[:-2,:-2])
fxy = fxy/(4*dx**2)
#Contour curvature
Kt[1:-1, 1:-1] = (fxx*fy**2 - 2*fxy*fx*fy + fyy*fx**2)/((fx**2 + fy**2)*np.sqrt((fx**2 + fy**2)+1))
return Kt
def calcAverageSlopeOfGridSubset(self, gridSubset,dx):
## Sx,Sy = calcAverageSlopeOfGridSubset(numpy matrix, dx)
#Compute the average slope over a subset of a grid (or a whole grid if you're into that),
#by fitting a plane to the elevation data stored in grid subset
nx,ny = len(gridSubset[1,:]), len(gridSubset[:,1])
xs = (0.5+np.arange(nx))*dx - (nx*dx)/2.0
ys = (0.5+np.arange(ny))*dx - (ny*dx)/2.0
X,Y = np.meshgrid(xs,ys)
#Fit a plane of the form z = ax + by + c, where beta = [a b c]
M=np.vstack((X.flatten(),Y.flatten(),np.ones((1,nx*ny)))).T
beta = np.linalg.lstsq(M,gridSubset.flatten())[0]
return beta[0], beta[1] #Return the slope in the x and y directions respecticely
class Georef_info(object):
def __init__(self):
self.geoTransform = 0
self.projection = 0
self.dx = 0
self.xllcenter = 0
self.yllcenter = 0
self.nx = 0
self.ny = 0
def __deepcopy__(self, memo):
import copy
cls = self.__class__
result = cls.__new__(cls)
memo[id(self)] = result
for k, v in self.__dict__.items():
setattr(result, k, copy.deepcopy(v, memo))
return result
class BaseSpatialShape(object):
# Wrapper for GDAL shapes.
def __init__(self, *args, **kwargs):
if kwargs.get('shapefile_name') is None:
raise Error.InputError('Input Error', 'Inputs not satisfied')
self.shapedata = ogr.Open(kwargs.get('shapefile_name'))
def createMaskFromShape(self, geoRefInfo, projection, dtype, noDataValue = 0):
#Open Shapefile
source_ds = self.shapedata
source_layer = source_ds.GetLayer()
maskSrc = gdal.GetDriverByName('MEM').Create('name',geoRefInfo.nx,geoRefInfo.ny, 1, dtype)
maskSrc.SetGeoTransform(geoRefInfo.geoTransform)
maskBand = maskSrc.GetRasterBand(1)
maskBand.SetNoDataValue(noDataValue)
# 5. Rasterize why is the burn value 0... isn't that the same as the background?
gdal.RasterizeLayer(maskSrc, [1], source_layer, burn_values=[1])
grid = maskSrc.ReadAsArray().astype(dtype)
maskSrc = None
return BaseSpatialGrid(nx = geoRefInfo.nx, ny = geoRefInfo.ny, projection = projection, geo_transform = geoRefInfo.geoTransform, grid= grid)
class BaseSpatialGrid(GDALMixin):
required_inputs_and_actions = ((('nx', 'ny', 'projection', 'geo_transform',),'_create'),
(('ai_ascii_filename','EPSGprojectionCode'),'_read_ai'),
(('gdal_filename',), '_read_gdal'),
(('nx', 'ny', 'dx'), '_create_random_grid'),
(('dx', 'grid'), '_create_from_grid'))
dtype = float64
# BaseSpatialGrid is a class for all rasters
def __deepcopy__(self, memo):
import copy
cls = self.__class__
result = cls.__new__(cls)
memo[id(self)] = result
for k, v in self.__dict__.items():
setattr(result, k, copy.deepcopy(v, memo))
return result
def __init__(self, *args, **kwargs):
super(BaseSpatialGrid,self).__init__()
self._georef_info = Georef_info()
self._sorted = False
if len(kwargs.keys()) == 0:
return
evaluative_action = self.__get_evaluative_action(*args, **kwargs)
if evaluative_action == None:
raise Error.InputError('Input Error', 'Inputs not satisfied')
eval('self.' + evaluative_action + '(*args, **kwargs)')
def __setitem__(self, key, value):
i, j = key
if i < 0 or j < 0 or i > self._georef_info.ny or j > self._georef_info.nx:
return
self._griddata[i, j] = value
def __getitem__(self, key):
i, j = key
i = int(i)
j = int(j)
if i >= 0 and j >= 0 and i < self._georef_info.ny and j < self._georef_info.nx:
try:
return self._griddata[i, j]
except:
print('error: '+ str(i) + str(j))
return None
def __get_evaluative_action(self, *args, **kwargs):
for required_input_set, evaluative_action in self.required_inputs_and_actions:
these_kw = set(kwargs.keys())
required_kw = set(required_input_set)
if required_kw.issubset(these_kw):
return evaluative_action
return None
def __populate_georef_info_using_geoTransform(self, nx, ny):
self._georef_info.dx = self._georef_info.geoTransform[1]
self._georef_info.xllcenter = self._georef_info.geoTransform[0]+self._georef_info.dx/2.0
self._georef_info.yllcenter = self._georef_info.geoTransform[3]-(self._georef_info.dx*(self._georef_info.ny-0.5))
self._georef_info.nx = nx
self._georef_info.ny = ny
def _create(self, *args, **kwargs):
self._georef_info.geoTransform = kwargs.get('geo_transform')
self._georef_info.projection = kwargs.get('projection')
self.__populate_georef_info_using_geoTransform(kwargs['nx'], kwargs['ny'])
if kwargs.get('grid') is None:
self._griddata = np.zeros(shape = (self._georef_info.ny,self._georef_info.nx), dtype = self.dtype)
else:
self._griddata = kwargs.get('grid')
def _create_random_grid(self, *args, **kwargs):
self._georef_info.dx = kwargs['dx']
self._georef_info.nx = kwargs['nx']
self._georef_info.ny = kwargs['ny']
self._georef_info.xllcenter = 0
self._georef_info.yllcenter = 0
self._randomize_grid_values(*args, **kwargs)
def _create_from_grid(self, *args, **kwargs):
self._georef_info.dx = kwargs['dx']
(ny, nx) = kwargs['grid'].shape
self._georef_info.nx = nx
self._georef_info.ny = ny
self._georef_info.xllcenter = 0
self._georef_info.yllcenter = 0
self._griddata = kwargs['grid']
def _randomize_grid_values(self, *args, **kwargs):
if kwargs.get('mask') is not None:
i = np.where(kwargs.get('mask')._griddata == 1)
self._griddata[i] = np.random.rand(len(i[0]))
else:
self._griddata = np.random.rand(self._georef_info.ny, self._georef_info.nx)
def _read_ai(self, *args, **kwargs):
self._georef_info.projection = self._get_projection_from_EPSG_projection_code(kwargs['EPSGprojectionCode'])
self._georef_info.geoTransform, self._georef_info.nx, self._georef_info.ny, self._griddata = self._asciiRasterToMemory(kwargs['ai_ascii_filename'])
self.__populate_georef_info_using_geoTransform(self._georef_info.nx, self._georef_info.ny)
def _read_gdal(self, *args, **kwargs):
self._georef_info.geoTransform, self._georef_info.nx, self._georef_info.ny, self._griddata = self._readGDALFile(kwargs['gdal_filename'], self.dtype)
self.__populate_georef_info_using_geoTransform(self._georef_info.nx, self._georef_info.ny)
def _copy_info_from_grid(self, grid, set_zeros = False):
import copy
self._georef_info = copy.deepcopy(grid._georef_info)
if not set_zeros:
self._griddata = grid._griddata.copy()
else:
self._griddata = np.zeros_like(grid._griddata, self.dtype)
def _getNeighborIndices(self, row, col):
#Search kernel for D8 flow routing, the relative indices of each of the 8 points surrounding a pixel
# |i-1,j-1 i-1,j i-1,j+1|
# |i,j-1 i,j i,j+1|
# |i+1,j-1 i+1,j i+1,j+1|
rowKernel = np.array([1, 1, 1, 0, 0, -1, -1, -1])
colKernel = np.array([-1, 0, 1, -1, 1, -1, 0, 1])
rt2 = np.sqrt(2)
dxMults = np.array([rt2, 1.0, rt2, 1.0, 1.0, rt2, 1.0, rt2]) # Unit Distance from pixel to surrounding coordinates
#Find all the surrounding indices
outRows = (rowKernel + row).astype(int)
outCols = (colKernel + col).astype(int)
#Determine which indices are out of bounds
inBounds = (outRows >= 0)*(outRows < self._georef_info.ny)*(outCols >= 0)*(outCols < self._georef_info.nx)
return (outRows[inBounds], outCols[inBounds], dxMults[inBounds])
def _xy_to_rowscols(self, v):
l = list()
for (x,y) in v:
col = int(round((x-self._georef_info.xllcenter)/self._georef_info.dx))
row = int((self._georef_info.ny - 1) - round((y-self._georef_info.yllcenter)/self._georef_info.dx))
if col > self._georef_info.nx or row > self._georef_info.ny or col < 0 or row < 0:
l.append((None, None))
else:
l.append((row,col))
return tuple(l)
def _rowscols_to_xy(self, l):
v = list()
for(row,col) in l:
x = float64(col)*self._georef_info.dx + self._georef_info.xllcenter
y = (float64(self._georef_info.ny - 1.0) - float64(row))*self._georef_info.dx + self._georef_info.yllcenter
v.append((x,y))
return tuple(v)
def _area_per_pixel(self, *args, **kwargs):
return self._georef_info.dx**2 * np.ones((self._georef_info.ny, self._georef_info.nx))
def _mean_pixel_dimension(self, *args, **kwargs):
return self._georef_info.dx * np.ones_like(self._griddata, dtype = float64)
def get_XY_matricies(self):
xllc, yllc, nx, ny, dx = (self._georef_info.xllcenter, self._georef_info.yllcenter, self._georef_info.nx, self._georef_info.ny, self._georef_info.dx)
x = np.arange(xllc, xllc+(nx-1)*dx, dx)
y = np.arange(yllc, yllc+(ny-1)*dx, dx)
return np.meshgrid(x,y)
def resample(self, de, interpolation = 'quintic'):
return_grid = self.__class__()
return_grid._copy_info_from_grid(self, set_zeros=True)
import copy
geoTransform = (self._georef_info.geoTransform[0],
np.sign(self._georef_info.geoTransform[1])*de,
self._georef_info.geoTransform[2],
self._georef_info.geoTransform[3],
self._georef_info.geoTransform[4],
np.sign(self._georef_info.geoTransform[5])*de)
georef = copy.deepcopy(self._georef_info)
georef.geoTransform = geoTransform
georef.dx = de
georef.nx = int(np.round(self._georef_info.nx * self._georef_info.dx / de))
georef.ny = int(np.round(self._georef_info.ny * self._georef_info.dx / de))
return_grid._georef_info = georef
xo = np.linspace(self._georef_info.xllcenter,(self._georef_info.nx-1)*(self._georef_info.dx), num = self._georef_info.nx)
yo = np.linspace(self._georef_info.yllcenter,(self._georef_info.ny-1)*(self._georef_info.dx), num = self._georef_info.ny)
xf = np.linspace(georef.xllcenter,(georef.nx-1)*georef.dx, num = georef.nx)
yf = np.linspace(georef.yllcenter,(georef.ny-1)*georef.dx, num = georef.ny)
from scipy.interpolate import interp2d
interp_grid = copy.deepcopy(self._griddata)
if geoTransform[1] > 0:
interp_grid = np.fliplr(interp_grid)
if geoTransform[5] < 0:
interp_grid = np.flipud(interp_grid)
f = interp2d(xo, yo, interp_grid, kind=interpolation)
return_grid._griddata = f(xf, yf)
return return_grid
def location_in_grid(self, xo):
index = self._xy_to_rowscols((xo,))[0]
return index[0] is not None and index[1] is not None and self[index[0], index[1]] is not None and self[index[0], index[1]] != 0 and not np.isnan(self[index[0], index[1]])
def tile(self, tile_xdim = 400, tile_ydim=400, tile_xpadding = 10, tile_ypadding = 10):
num_xtiles = int(np.ceil(float(self._georef_info.nx) / float(tile_xdim)))
num_ytiles = int(np.ceil(float(self._georef_info.ny) / float(tile_ydim)))
tiles = []
import copy
for x_left in range(num_xtiles):
for y_top in range(num_ytiles):
left = x_left*tile_xdim-tile_xpadding if (x_left*tile_xdim-tile_xpadding) >= 0 else 0
right = (x_left+1)*tile_xdim+tile_xpadding if ((x_left+1)*tile_xdim+tile_xpadding) <= (self._georef_info.nx-1) else self._georef_info.nx
top = y_top*tile_ydim-tile_ypadding if (y_top*tile_ydim-tile_ypadding) >= 0 else 0
bottom = (y_top+1)*tile_ydim+tile_ypadding if ((y_top+1)*tile_ydim+tile_ypadding) <= (self._georef_info.ny-1) else self._georef_info.ny
new_tile = self.__class__()
needs_left_padding = (x_left == 0)
needs_right_padding = (x_left == (num_xtiles-1))
needs_top_padding = (y_top == 0)
needs_bottom_padding = (y_top == (num_ytiles-1))
griddata = self._griddata[top:bottom,left:right]
xllcenter = self._georef_info.xllcenter + left*self._georef_info.dx
yllcenter = self._georef_info.yllcenter + (self._georef_info.ny - bottom)*self._georef_info.dx
nx = right-left
ny = bottom - top
if needs_left_padding:
griddata = np.concatenate((np.fliplr(griddata[:,0:tile_xpadding]), griddata), axis = 1)
xllcenter -= tile_xpadding*self._georef_info.dx
nx += tile_xpadding
if needs_right_padding:
griddata = np.concatenate((griddata, np.fliplr(griddata[:,-tile_xpadding:])), axis = 1)
nx += tile_xpadding
if needs_top_padding:
griddata = np.concatenate((np.flipud(griddata[0:tile_ypadding,:]), griddata), axis = 0)
ny += tile_ypadding
if needs_bottom_padding:
griddata = np.concatenate((griddata, np.flipud(griddata[-tile_ypadding:,:])), axis = 0)
ny += tile_ypadding
yllcenter -= tile_ypadding*self._georef_info.dx
new_tile._georef_info.geoTransform = (xllcenter - 0.5*self._georef_info.dx, self._georef_info.dx, 0, yllcenter + (ny + 0.5)*self._georef_info.dx, 0, -self._georef_info.dx)
new_tile._georef_info.xllcenter = xllcenter
new_tile._georef_info.yllcenter = yllcenter
new_tile._georef_info.dx = self._georef_info.dx
new_tile._georef_info.nx = nx
new_tile._georef_info.ny = ny
new_tile._griddata = griddata
tiles += [copy.deepcopy(new_tile)]
return tiles
def remove_padding(self, xpadding = 10, ypadding = 10):
import copy
unpadded = copy.deepcopy(self)
unpadded._griddata = unpadded._griddata[ypadding:-ypadding,xpadding:-xpadding]
unpadded._georef_info.xllcenter += xpadding*unpadded._georef_info.dx
unpadded._georef_info.yllcenter += ypadding*unpadded._georef_info.dx
unpadded._georef_info.nx -= 2*xpadding
unpadded._georef_info.ny -= 2*ypadding
unpadded._georef_info.geoTransform = (unpadded._georef_info.xllcenter - 0.5*unpadded._georef_info.dx, unpadded._georef_info.dx, 0, unpadded._georef_info.yllcenter + (float(unpadded._georef_info.ny-0.5))*self._georef_info.dx, 0, -self._georef_info.dx)
return unpadded
def sort(self, reverse=True, force = False, mask = None):
if force:
self._sorted = False
if not self._sorted:
if mask is not None:
sort_indexes = self._griddata.argsort(axis = None)
unraveled_sort_indexes = np.unravel_index(sort_indexes, mask.shape)
query_indexes = np.where(mask._griddata[unraveled_sort_indexes] == 1)
query_indexes_raveled = np.ravel_multi_index(query_indexes,mask.shape)
self._sort_indexes = sort_indexes[query_indexes_raveled]
else:
self._sort_indexes = self._griddata.argsort(axis = None)
self._sorted = True
if reverse:
return self._sort_indexes[::-1]
else:
return self._sort_indexes
def apply_moving_window(self, moving_window):
out_grid = None
out_grid._georef_info = self._georef_info
out_grid._griddata = moving_window.apply_moving_window(self._griddata, self._georef_info.dx, self.dtype)
return out_grid
def average_over_distance(self, distance, grid = None):
(nx, ny) = (self._georef_info.nx, self._georef_info.ny)
(dx, dy) = (self._georef_info.dx, self._georef_info.dx)
(xmin, xmax) = (self._georef_info.xllcenter, nx*dx+self._georef_info.xllcenter)
(ymin, ymax) = (self._georef_info.yllcenter, ny*dy+self._georef_info.yllcenter)
(xcenter, ycenter) = ((xmin+xmax) / 2.0, (ymin+ymax) / 2.0)
[x,y] = np.meshgrid(np.arange(xmin, xmax, dx),np.arange(ymin, ymax, dy))
D = np.sqrt(np.power((x - xcenter),2) + np.power((y - ycenter), 2))
template = (D <= distance).astype(float)
template /= np.sum(template[:])
if grid is None:
grid = self._griddata
from numpy.fft import fft2 as fft2
from numpy.fft import ifft2 as ifft2
from numpy.fft import ifftshift
return np.real(ifftshift(ifft2(fft2(grid)*fft2(template))))
def clip_to_bounds(self, bounds):
extent = (bounds[0][0], bounds[0][1], bounds[1][0], bounds[1][1])
return self.clip_to_extent(extent)
def clip_to_extent(self, extent):
import copy
return_grid = copy.deepcopy(self)
return_grid._georef_info = copy.deepcopy(self._georef_info)
lower_left = (extent[0]+self._georef_info.dx, extent[2]+self._georef_info.dx)
upper_right = (extent[1]-self._georef_info.dx, extent[3]-self._georef_info.dx)
idx = self._xy_to_rowscols((lower_left, upper_right))
return_grid._griddata = return_grid._griddata[idx[1][0]+1:idx[0][0]+1,idx[0][1]:idx[1][1]]
return_grid._georef_info.nx = return_grid._griddata.shape[1]
return_grid._georef_info.ny = return_grid._griddata.shape[0]
return_grid._georef_info.xllcenter = self._rowscols_to_xy((idx[0],))[0][0]
return_grid._georef_info.yllcenter = self._rowscols_to_xy((idx[0],))[0][1]
return_grid._georef_info.geoTransform = (return_grid._georef_info.xllcenter, return_grid._georef_info.geoTransform[1], return_grid._georef_info.geoTransform[2], return_grid._georef_info.yllcenter + (return_grid._georef_info.dx*(return_grid._georef_info.ny-1)), return_grid._georef_info.geoTransform[4], return_grid._georef_info.geoTransform[5],)
return return_grid
def extent_of_data(self):
top = 0
bottom = self._georef_info.ny - 1
left = 0
right = self._georef_info.nx - 1
while np.sum(np.isnan(self._griddata[top,:])) == self._georef_info.nx:
top = top + 1
while np.sum(np.isnan(self._griddata[bottom,:])) == self._georef_info.nx:
bottom = bottom - 1
while np.sum(np.isnan(self._griddata[left,:])) == self._georef_info.ny:
left = left + 1
while np.sum(np.isnan(self._griddata[right,:])) == self._georef_info.ny:
right = right - 1
(ll, ur) = self._rowscols_to_xy(((bottom, left), (top, right)))
return (ll[0], ur[0], ll[1], ur[1])
def clip_to_mask_grid(self, mask_grid):
gdal_source = self._create_gdal_representation_from_array(self._georef_info, 'MEM', self._griddata, self.dtype)
gdal_mask = mask_grid._create_gdal_representation_from_array(mask_grid._georef_info, 'MEM', mask_grid._griddata, mask_grid.dtype)
gdal_clip = self._clipRasterToRaster(gdal_source, gdal_mask, self.dtype)
self._georef_info.geoTransform, self._georef_info.nx, self._georef_info.ny, self._griddata = self._read_GDAL_dataset(gdal_clip, self.dtype)
self.__populate_georef_info_using_geoTransform(self._georef_info.nx, self._georef_info.ny)
def clip_to_shapefile(self, shapefile):
gdal_source = self._create_gdal_representation_from_array(self._georef_info, 'MEM', self._griddata, self.dtype)
gdal_clip = shapefile.shapedata
gdal_result = self._clipRasterToShape(gdal_source, gdal_clip)
self._georef_info.geoTransform, self._georef_info.nx, self._georef_info.ny, self._griddata = self._read_GDAL_dataset(gdal_result, self.dtype)
self.__populate_georef_info_using_geoTransform(self._georef_info.nx, self._georef_info.ny)
def calculate_gradient_over_length_scale(self,length_scale):
# sx,sy = calcFiniteDiffs(elevGrid,dx)
# calculates finite differences in X and Y direction using a finite difference
# kernel that extends N cells from the center. The width of the kernel is then
# 2N + 1 by 2N + 1. Applies a boundary condition such that the size and location
# of the grids in is the same as that out. However, the larger N is, the more NoData
#Will be around the edges .
#Compute finite differences
elevGrid = self._griddata
dx = self._georef_info.dx
N = np.ceil(length_scale / dx)
Sx = (elevGrid[N:-N, (2*N):] - elevGrid[N:-N, :-(2*N)])/(((2*N)+1)*dx)
Sy = (elevGrid[(2*N):,N:-N] - elevGrid[:-(2*N), N:-N])/(((2*N)+1)*dx)
#Create two new arrays of the original DEMs size
SxPadded = np.empty(elevGrid.shape)
SxPadded[:] = np.NAN
SyPadded = np.empty(elevGrid.shape)
SyPadded[:] = np.NAN
SyPadded[N:-N, N:-N] = Sy
SxPadded[N:-N, N:-N] = Sx
return SxPadded, SyPadded
def calculate_laplacian_over_length_scale(self, length_scale):
#C = calcFiniteCurv(elevGrid, dx)
#calculates finite differnces in X and Y direction using the centered difference method.
#Applies a boundary condition such that the size and location of the grids in is the same as that out.
dx = self._georef_info.dx
grid = self._griddata
winRad = np.ceil(length_scale / dx)
#Assign boundary conditions
Curv = np.zeros_like(grid)*np.nan
#Compute finite differences
Cx = (grid[winRad:-winRad, (2*winRad):] - 2*grid[winRad:-winRad, winRad:-winRad] + grid[winRad:-winRad, :-(2*winRad)])/(2*dx*winRad)**2
Cy = (grid[(2*winRad):, winRad:-winRad] - 2*grid[winRad:-winRad, winRad:-winRad] + grid[:-(2*winRad), winRad:-winRad])/(2*dx*winRad)**2
Curv[winRad:-winRad,winRad:-winRad] = Cx+Cy
return Curv
def principal_curvatures(self):
Zy, Zx = np.gradient(self._griddata, self._georef_info.dx)
Zxy, Zxx = np.gradient(Zx, self._georef_info.dx)
Zyy, _ = np.gradient(Zy, self._georef_info.dx)
H = (Zx**2 + 1)*Zyy - 2*Zx*Zy*Zxy + (Zy**2 + 1)*Zxx
H = -H/(2*(Zx**2 + Zy**2 + 1)**(1.5))
K = (Zxx * Zyy - (Zxy ** 2)) / (1 + (Zx ** 2) + (Zy **2)) ** 2
k1 = H + np.sqrt(np.power(H,2) - K)
k2 = H - np.sqrt(np.power(H,2) - K)
k1re = BaseSpatialGrid()
k1re._copy_info_from_grid(self, True)
k2re = BaseSpatialGrid()
k2re._copy_info_from_grid(self, True)
k1re._griddata = k1
k2re._griddata = k2
return (k1re, k2re)
def plot(self, **kwargs):
interactive = kwargs.pop('interactive', True)
colorbar = kwargs.pop('colorbar', True)
extent = [self._georef_info.xllcenter, self._georef_info.xllcenter+(self._georef_info.nx-0.5)*self._georef_info.dx, self._georef_info.yllcenter, self._georef_info.yllcenter+(self._georef_info.ny-0.5)*self._georef_info.dx]
fig = plt.figure()
plt.axis(extent)
if interactive:
plt.ion()
plt.show(block = False)
else:
plt.ioff()
im = plt.imshow(self._griddata, extent = extent, **kwargs)
if colorbar:
plt.colorbar(im)
plt.draw()
plt.pause(0.001)
if interactive:
plt.show()
return fig
def find_nearest_cell_with_value(self, index, value, pixel_radius):
(i, j) = index
nearest = tuple()
minimum_difference = np.nan
for y in range(int(i-pixel_radius),int(i+pixel_radius)):
for x in range(int(j-pixel_radius),int(j+pixel_radius)):
if x is not None and y is not None and np.sqrt( (y-i)**2 + (x-j)**2) <= pixel_radius and x < self._griddata.shape[1] and y < self._griddata.shape[0]:
value_difference = np.abs(value - self._griddata[y,x])
if np.isnan(minimum_difference) or minimum_difference > value_difference:
minimum_difference = value_difference
nearest = (y,x)
(y,x) = nearest
return y, x
def find_nearest_cell_with_value_greater_than(self, index, value, pixel_radius):