/
georasters.py
executable file
·1548 lines (1349 loc) · 62.4 KB
/
georasters.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
#!/usr/bin/env python
# coding: utf-8
'''
GeoRasters
This program defines functions that are useful for working with GIS data in Python
Copyright (C) 2014-2016 Ömer Özak
Usage:
import georasters as gr
======================================================
Author: Ömer Özak, 2013--2014 (ozak at smu.edu)
Website: http://omerozak.com
GitHub: https://github.com/ozak/
======================================================
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
from __future__ import division
import numpy as np
from osgeo import gdal, gdalnumeric, ogr, osr, gdal_array
try:
from gdalconst import GA_ReadOnly
except:
from osgeo.gdalconst import GA_ReadOnly
from skimage.measure import block_reduce
from skimage.transform import resize
import skimage.graph as graph
import matplotlib.pyplot as plt
import pandas as pd
from fiona.crs import from_string
from pyproj import CRS
import geopandas as gp
from shapely.geometry import Polygon, LineString
from affine import Affine
from rasterstats import zonal_stats
import rasterio
from shapely.geometry import shape
import pysal
if pysal.__version__.startswith('2.1'):
from pysal.explore.esda import G as pysal_G
from pysal.explore.esda import G_Local as pysal_G_Local
from pysal.explore.esda import Gamma as pysal_Gamma
from pysal.explore.esda import Join_Counts as pysal_Join_Counts
from pysal.explore.esda import Moran as pysal_Moran
from pysal.explore.esda import Moran_Local as pysal_Moran_Local
from pysal.explore.esda import Geary as pysal_Geary
from pysal.lib.weights import lat2W as pysal_lat2W
from pysal.lib.weights import W as pysal_W
elif pysal.__version__.startswith('2') and pysal.__version__.startswith('2.1')==False:
from esda import G as pysal_G
from esda import G_Local as pysal_G_Local
from esda import Gamma as pysal_Gamma
from esda import Join_Counts as pysal_Join_Counts
from esda import Moran as pysal_Moran
from esda import Moran_Local as pysal_Moran_Local
from esda import Geary as pysal_Geary
from libpysal.weights import lat2W as pysal_lat2W
from libpysal.weights import W as pysal_W
else:
from pysal import G as pysal_G
from pysal import G_Local as pysal_G_Local
from pysal import Gamma as pysal_Gamma
from pysal import Join_Counts as pysal_Join_Counts
from pysal import Moran as pysal_Moran
from pysal import Moran_Local as pysal_Moran_Local
from pysal import Geary as pysal_Geary
from pysal import lat2W as pysal_lat2W
from pysal import W as pysal_W
# Function to read the original file's projection:
def get_geo_info(filename, band=1):
''' Gets information from a Raster data set
'''
sourceds = gdal.Open(filename, GA_ReadOnly)
ndv = sourceds.GetRasterBand(band).GetNoDataValue()
xsize = sourceds.RasterXSize
ysize = sourceds.RasterYSize
geot = sourceds.GetGeoTransform()
projection = osr.SpatialReference()
projection.ImportFromWkt(sourceds.GetProjectionRef())
datatype = sourceds.GetRasterBand(band).DataType
datatype = gdal.GetDataTypeName(datatype)
return ndv, xsize, ysize, geot, projection, datatype
# Function to map location in pixel of raster array
def map_pixel(point_x, point_y, cellx, celly, xmin, ymax, floor=False):
'''
Usage:
map_pixel(xcoord, ycoord, x_cell_size, y_cell_size, xmin, ymax)
where:
xmin is leftmost X coordinate in system
ymax is topmost Y coordinate in system
Example:
raster = HMISea.tif
ndv, xsize, ysize, geot, projection, datatype = get_geo_info(raster)
row, col = map_pixel(x,y,geot[1],geot[-1], geot[0],geot[3])
'''
point_x = np.asarray(point_x)
point_y = np.asarray(point_y)
if floor:
col = np.floor((point_x - xmin) / cellx).astype(int)
row = np.floor((point_y - ymax) / celly).astype(int)
else:
col = np.round((point_x - xmin) / cellx).astype(int)
row = np.round((point_y - ymax) / celly).astype(int)
return row, col
def map_pixel_inv(row, col, cellx, celly, xmin, ymax):
'''
Usage:
map_pixel(xcoord, ycoord, x_cell_size, y_cell_size, xmin, ymax)
where:
xmin is leftmost X coordinate in system
ymax is topmost Y coordinate in system
Example:
raster = HMISea.tif
ndv, xsize, ysize, geot, projection, datatype = get_geo_info(raster)
row, col = map_pixel(x,y,geot[1],geot[-1], geot[0],geot[3])
'''
col = np.asarray(col)
row = np.asarray(row)
point_x = xmin+col*cellx
point_y = ymax+row*celly
return point_x, point_y
# Aggregate raster to higher resolution using sums
def aggregate(raster, ndv, block_size):
'''
Aggregate raster to smaller resolution, by adding cells.
Usage:
aggregate(raster, ndv, block_size)
where:
raster is a Numpy array created by importing the raster (e.g. geotiff)
ndv is the NoData Value for the raster (can be read using the get_geo_info function)
block_size is a duple of factors by which the raster will be shrinked
Example:
raster = HMISea.tif
ndv, xsize, ysize, geot, projection, datatype = get_geo_info(raster)
costs = load_tiff(raster)
costs2=aggregate(costs, ndv, (10,10))
'''
raster2 = block_reduce(raster, block_size, func=np.ma.sum)
return raster2
# Function to write a new file.
def create_geotiff(name, Array, driver, ndv, xsize, ysize, geot, projection, datatype, band=1):
'''
Creates new geotiff from array
'''
if isinstance(datatype, int) == False:
if datatype.startswith('gdal.GDT_') == False:
datatype = eval('gdal.GDT_'+datatype)
newfilename = name+'.tif'
# Set nans to the original No Data Value
Array[np.isnan(Array)] = ndv
# Set up the dataset
DataSet = driver.Create(newfilename, xsize, ysize, 1, datatype)
# the '1' is for band 1.
DataSet.SetGeoTransform(geot)
DataSet.SetProjection(projection.ExportToWkt())
# Write the array
DataSet.GetRasterBand(band).WriteArray(Array)
DataSet.GetRasterBand(band).SetNoDataValue(ndv)
return newfilename
# Function to aggregate and align rasters
def align_rasters(raster, alignraster, how=np.ma.mean, cxsize=None, cysize=None, masked=False):
'''
Align two rasters so that data overlaps by geographical location
Usage:
(alignedraster_o, alignedraster_a, geot_a) = AlignRasters(raster, alignraster, how=np.mean)
where:
raster: string with location of raster to be aligned
alignraster: string with location of raster to which raster will be aligned
how: function used to aggregate cells (if the rasters have different sizes)
It is assumed that both rasters have the same size
'''
ndv1, xsize1, ysize1, geot1, projection1, datatype1 = get_geo_info(raster)
ndv2, xsize2, ysize2, geot2, projection2, datatype2 = get_geo_info(alignraster)
if projection1.ExportToMICoordSys() == projection2.ExportToMICoordSys():
blocksize = (np.round(geot2[1]/geot1[1]).astype(int), np.round(geot2[-1]/geot1[-1]).astype(int))
mraster = gdalnumeric.LoadFile(raster)
mraster = np.ma.masked_array(mraster, mask=mraster == ndv1, fill_value=ndv1)
mmin = mraster.min()
mraster = block_reduce(mraster, blocksize, func=how)
araster = gdalnumeric.LoadFile(alignraster)
araster = np.ma.masked_array(araster, mask=araster == ndv2, fill_value=ndv2)
amin = araster.min()
if geot1[0] <= geot2[0]:
row3, mcol = map_pixel(geot2[0], geot2[3], geot1[1] *blocksize[0],
geot1[-1]*blocksize[1], geot1[0], geot1[3])
acol = 0
else:
row3, acol = map_pixel(geot1[0], geot1[3], geot2[1], geot2[-1], geot2[0], geot2[3])
mcol = 0
if geot1[3] <= geot2[3]:
arow, col3 = map_pixel(geot1[0], geot1[3], geot2[1], geot2[-1], geot2[0], geot2[3])
mrow = 0
else:
mrow, col3 = map_pixel(geot2[0], geot2[3], geot1[1] *blocksize[0],
geot1[-1]*blocksize[1], geot1[0], geot1[3])
arow = 0
'''
col3,row3 = map_pixel(geot1[0], geot1[3], geot2[1],geot2[-1], geot2[0], geot2[3])
col3 = max(0,col3)
row3 = max(0,row3)
araster = araster[row3:,col3:]
col3,row3 = map_pixel(geot2[0], geot2[3], geot1[1] *blocksize[0],
geot1[-1]*blocksize[1], geot1[0], geot1[3])
col3 = max(0,abs(col3))
row3 = max(0,np.abs(row3))
mraster = mraster[row3:,col3:]
'''
mraster = mraster[mrow:, mcol:]
araster = araster[arow:, acol:]
if cxsize and cysize:
araster = araster[:cysize, :cxsize]
mraster = mraster[:cysize, :cxsize]
else:
rows = min(araster.shape[0], mraster.shape[0])
cols = min(araster.shape[1], mraster.shape[1])
araster = araster[:rows, :cols]
mraster = mraster[:rows, :cols]
#mraster = mraster[row3:rows+row3,col3:cols+col3]
if masked:
mraster = np.ma.masked_array(mraster, mask=mraster < mmin, fill_value=ndv1)
araster = np.ma.masked_array(araster, mask=araster < amin, fill_value=ndv2)
geot = (max(geot1[0], geot2[0]), geot1[1]*blocksize[0], geot1[2],
min(geot1[3], geot2[3]), geot1[4], geot1[-1]*blocksize[1])
return (mraster, araster, geot)
else:
print("Rasters need to be in same projection")
return (-1, -1, -1)
# Load geotif raster data
def load_tiff(file):
"""
Load a geotiff raster keeping ndv values using a masked array
Usage:
data = load_tiff(file)
"""
ndv, xsize, ysize, geot, projection, datatype = get_geo_info(file)
data = gdalnumeric.LoadFile(file)
data = np.ma.masked_array(data, mask=data == ndv, fill_value=ndv)
return data
class RasterGeoTError(Exception):
pass
class RasterGeoError(Exception):
pass
class RasterGeoTWarning(Exception):
pass
# GeoRaster Class
class GeoRaster(object):
'''
GeoRaster class to create and handle GIS rasters.
Eash GeoRaster object is a numpy masked array + geotransfrom + nodata_value
Usage:
geo=GeoRaster(raster, geot, nodata_value=ndv)
where
raster: Numpy masked array with the raster data,
which could be loaded with the load_tiff(file)
geot: GDAL Geotransformation
nodata_value: No data value in raster, optional
'''
def __init__(self, raster, geot, nodata_value=np.nan, fill_value=-1e10, projection=None, datatype=None):
'''
Initialize Georaster
Usage:
geo=GeoRaster(raster, geot, nodata_value=ndv)
where
raster: Numpy masked array with the raster data,
which could be loaded with from_file(file) or load_tiff(file)
geot: GDAL Geotransformation
nodata_value: No data value in raster, optional
'''
super(GeoRaster, self).__init__()
if isinstance(raster, np.ma.core.MaskedArray):
self.raster = raster
else:
self.raster = np.ma.masked_array(raster, mask=raster == nodata_value,
fill_value=fill_value)
self.geot = geot
self.nodata_value = nodata_value
self.shape = raster.shape
self.x_cell_size = geot[1]
self.y_cell_size = geot[-1]
self.xmin = geot[0]
self.ymax = geot[3]
self.xmax = self.xmin + self.x_cell_size * self.shape[1]
self.ymin = self.ymax + self.y_cell_size * self.shape[0]
self.bounds = (self.xmin, self.ymin, self.xmax, self.ymax)
self.projection = projection
self.datatype = datatype
self.mcp_cost = None
self.weights = None
self.G = None
self.Gamma = None
self.Join_Counts = None
self.Moran = None
self.Geary = None
self.Moran_Local = None
def __getitem__(self, indx):
rast = self.raster.__getitem__(indx)
proj = self.projection
nodata = self.nodata_value
datatype = self.datatype
geot = list(self.geot)
geot[0] += indx[0].start*geot[1]
geot[3] += indx[1].start*geot[-1]
geot = tuple(geot)
return GeoRaster(rast, geot,
nodata_value=nodata,
projection=proj,
datatype=datatype)
def __getslice__(self, i, j):
return self.raster.__getslice__(i, j)
# def __getattribute__(self, attr):
# return eval('self.'+attr)
def __lt__(self, other):
if isinstance(other, GeoRaster):
return self.raster < other.raster
elif isinstance(other, np.ndarray):
return self.raster < other
else:
return self.raster < other
def __le__(self, other):
if isinstance(other, GeoRaster):
return self.raster <= other.raster
elif isinstance(other, np.ndarray):
return self.raster <= other
else:
return self.raster <= other
def __gt__(self, other):
if isinstance(other, GeoRaster):
return self.raster > other.raster
elif isinstance(other, np.ndarray):
return self.raster > other
else:
return self.raster > other
def __ge__(self, other):
if isinstance(other, GeoRaster):
return self.raster >= other.raster
elif isinstance(other, np.ndarray):
return self.raster >= other
else:
return self.raster >= other
def __eq__(self, other):
if isinstance(other, GeoRaster):
return self.raster == other.raster
elif isinstance(other, np.ndarray):
return self.raster == other
else:
return self.raster == other
def __ne__(self, other):
if isinstance(other, GeoRaster):
return self.raster != other.raster
elif isinstance(other, np.ndarray):
return self.raster != other
else:
return self.raster != other
def __pos__(self):
return self
def __neg__(self):
return GeoRaster(-self.raster, self.geot, nodata_value=self.nodata_value,
projection=self.projection, datatype=self.datatype)
def __add__(self, other):
if isinstance(other, GeoRaster):
if self.geot != other.geot:
raise RasterGeoTWarning("Rasters do not have same geotransform. \
If needed first create union or allign them.")
if self.nodata_value == other.nodata_value:
ndv = self.nodata_value
else:
ndv = np.nan
return GeoRaster(self.raster+other.raster, self.geot, nodata_value=ndv,
projection=self.projection, datatype=self.datatype)
else:
return GeoRaster(self.raster+other, self.geot, nodata_value=self.nodata_value,
projection=self.projection, datatype=self.datatype)
def __radd__(self, other):
return self.__add__(other)
def __sub__(self, other):
return self+other.__neg__()
def __rsub__(self, other):
return self.__sub__(other)
def __mul__(self, other):
if isinstance(other, GeoRaster):
if self.geot != other.geot:
raise RasterGeoTWarning("Rasters do not have same geotransform. \
If needed first create union or allign them.")
if self.nodata_value == other.nodata_value:
ndv = self.nodata_value
else:
ndv = np.nan
return GeoRaster(self.raster*other.raster, self.geot, nodata_value=ndv,
projection=self.projection, datatype=self.datatype)
else:
return GeoRaster(self.raster*other, self.geot, nodata_value=self.nodata_value,
projection=self.projection, datatype=self.datatype)
def __rmul__(self, other):
return self.__mul__(other)
def __truediv__(self, other):
if isinstance(other, GeoRaster):
if self.geot != other.geot:
raise RasterGeoTWarning("Rasters do not have same geotransform. \
If needed first create union or allign them.")
if self.nodata_value == other.nodata_value:
ndv = self.nodata_value
else:
ndv = np.nan
return GeoRaster(self.raster/other.raster, self.geot, nodata_value=ndv,
projection=self.projection, datatype=self.datatype)
else:
return GeoRaster(self.raster/other, self.geot, nodata_value=self.nodata_value,
projection=self.projection, datatype=self.datatype)
def __rtruediv__(self, other):
if isinstance(other, GeoRaster):
return other.__truediv__(self)
else:
return GeoRaster(other/self.raster, self.geot, nodata_value=self.nodata_value,
projection=self.projection, datatype=self.datatype)
def __floordiv__(self, other):
A = self/other
A.raster = A.raster.astype(int)
return A
def __rfloordiv__(self, other):
if isinstance(other, GeoRaster):
if self.geot != other.geot:
raise RasterGeoTWarning("Rasters do not have same geotransform. \
If needed first create union or allign them.")
if self.nodata_value == other.nodata_value:
ndv = self.nodata_value
else:
ndv = np.nan
return GeoRaster((other.raster/self.raster).astype(int), self.geot,
nodata_value=ndv, projection=self.projection, datatype=self.datatype)
else:
return GeoRaster((other/self.raster).astype(int), self.geot,
nodata_value=self.nodata_value, projection=self.projection,
datatype=self.datatype)
def __pow__(self, other):
if isinstance(other, GeoRaster):
if self.geot != other.geot:
raise RasterGeoTWarning("Rasters do not have same geotransform. \
If needed first create union or allign them.")
if self.nodata_value == other.nodata_value:
ndv = self.nodata_value
else:
ndv = np.nan
return GeoRaster(self.raster**other.raster, self.geot, nodata_value=ndv,
projection=self.projection, datatype=self.datatype)
else:
return GeoRaster(self.raster**other, self.geot, nodata_value=self.nodata_value,
projection=self.projection, datatype=self.datatype)
def copy(self):
"""Returns copy of itself"""
return GeoRaster(self.raster.copy(), self.geot, nodata_value=self.nodata_value,
projection=self.projection, datatype=self.datatype)
def to_tiff(self, filename):
'''
geo.to_tiff(filename)
Saves GeoRaster as geotiff filename.tif with type datatype
If GeoRaster does not have datatype, then it tries to assign a type.
You can assign the type yourself by setting
geo.datatype = 'gdal.GDT_'+type
'''
if self.datatype is None:
self.datatype = gdal_array.NumericTypeCodeToGDALTypeCode(self.raster.data.dtype)
if self.datatype is None:
if self.raster.data.dtype.name.find('int') !=- 1:
self.raster = self.raster.astype(np.int32)
self.datatype = gdal_array.NumericTypeCodeToGDALTypeCode(self.raster.data.dtype)
else:
self.raster = self.raster.astype(np.float64)
self.datatype = gdal_array.NumericTypeCodeToGDALTypeCode(self.raster.data.dtype)
self.raster.data[self.raster.mask] = self.nodata_value
create_geotiff(filename, self.raster, gdal.GetDriverByName('GTiff'), self.nodata_value,
self.shape[1], self.shape[0], self.geot, self.projection, self.datatype)
def to_pandas(self, **kwargs):
"""
Convert GeoRaster to Pandas DataFrame, which can be easily exported to other types of files
The DataFrame has the row, col, value, x, and y values for each cell
"""
df = to_pandas(self, **kwargs)
return df
def to_geopandas(self, **kwargs):
"""
Convert GeoRaster to GeoPandas DataFrame, which can be easily exported to other types
of files and used to do other types of operations.
The DataFrame has the geometry (Polygon), row, col, value, x, and y values for each cell
"""
df = to_geopandas(self, **kwargs)
return df
def plot(self, figsize=None, ax=None, **kwargs):
'''
geo.plot()
Returns plot of raster data
'''
if ax is None:
fig, ax = plt.subplots(figsize=figsize)
ax.set_aspect('equal')
ax.matshow(self.raster, **kwargs)
plt.draw()
return ax
def union(self, other, floor=False):
'''
geo.union(Georaster)
Returns union of GeoRaster with another one
'''
return union([self, other], floor=floor)
def merge(self, other):
'''
geo.merge(Georaster)
Returns merge of GeoRaster with another one
'''
return merge([self, other])
def mean(self, *args, **kwargs):
'''
geo.mean(axis=None, dtype=None, out=None)
Returns the average of the array elements along given axis.
Refer to `numpy.mean` for full documentation.
See Also
--------
numpy.mean : equivalent function
'''
return self.raster.mean(*args, **kwargs)
def max(self, *args, **kwargs):
'''
geo.max(axis=None, out=None)
Return the maximum along a given axis.
Refer to `numpy.amax` for full documentation.
See Also
--------
numpy.amax : equivalent function
'''
return self.raster.max(*args, **kwargs)
def min(self, *args, **kwargs):
'''
geo.min(axis=None, out=None)
Return the minimum along a given axis.
Refer to `numpy.amin` for full documentation.
See Also
--------
numpy.amin : equivalent function
'''
return self.raster.min(*args, **kwargs)
def median(self, *args, **kwargs):
'''
geo.median(axis=None, out=None, overwrite_input=False)
axis : int, optional
Axis along which the medians are computed. The default (axis=None)
is to compute the median along a flattened version of the array.
out : ndarray, optional
Alternative output array in which to place the result. It must have
the same shape and buffer length as the expected output, but the
type (of the output) will be cast if necessary.
overwrite_input : bool, optional
If True, then allow use of memory of input array (a) for
calculations. The input array will be modified by the call to
median. This will save memory when you do not need to preserve the
contents of the input array. Treat the input as undefined, but it
will probably be fully or partially sorted. Default is False. Note
that, if `overwrite_input` is True and the input is not already an
ndarray, an error will be raised.
'''
return np.ma.median(self.raster, *args, **kwargs)
def std(self, *args, **kwargs):
'''
geo.std(axis=None, dtype=None, out=None, ddof=0)
Returns the standard deviation of the array elements along given axis.
Refer to `numpy.std` for full documentation.
See Also
--------
numpy.std : equivalent function
'''
return self.raster.std(*args, **kwargs)
def argmax(self, *args, **kwargs):
'''
geo.argmax(axis=None, out=None)
Return indices of the maximum values along the given axis.
Refer to `numpy.argmax` for full documentation.
See Also
--------
numpy.argmax : equivalent function
'''
return self.raster.argmax(*args, **kwargs)
def argmin(self, *args, **kwargs):
'''
geo.argmin(axis=None, out=None)
Return indices of the minimum values along the given axis of `a`.
Refer to `numpy.argmin` for detailed documentation.
See Also
--------
numpy.argmin : equivalent function
'''
return self.raster.argmin(*args, **kwargs)
def sum(self, *args, **kwargs):
'''
geo.sum(axis=None, dtype=None, out=None)
Return the sum of the array elements over the given axis.
Refer to `numpy.sum` for full documentation.
See Also
--------
numpy.sum : equivalent function
'''
return self.raster.sum(*args, **kwargs)
def prod(self, *args, **kwargs):
'''
geo.prod(axis=None, dtype=None, out=None)
Return the product of the array elements over the given axis
Refer to `numpy.prod` for full documentation.
See Also
--------
numpy.prod : equivalent function
'''
return self.raster.prod(*args, **kwargs)
def var(self, *args, **kwargs):
'''
geo.var(axis=None, dtype=None, out=None, ddof=0)
Returns the variance of the array elements, along given axis.
Refer to `numpy.var` for full documentation.
See Also
--------
numpy.var : equivalent function
'''
return self.raster.var(*args, **kwargs)
def count(self, *args, **kwargs):
'''
geo.count(axis=None)
Count the non-masked elements of the array along the given axis.
'''
return self.raster.count(*args, **kwargs)
def clip(self, shp, keep=False, *args, **kwargs):
'''
Clip raster using shape, where shape is either a GeoPandas DataFrame, shapefile,
or some other geometry format used by python-raster-stats
Returns list of GeoRasters or Pandas DataFrame with GeoRasters and additional information
Usage:
clipped = geo.clip(shape, keep=False)
where:
keep: Boolean (Default False), returns Georasters and Geometry information
'''
df = pd.DataFrame(zonal_stats(shp, self.raster, nodata=self.nodata_value, all_touched=True,
raster_out=True, affine=Affine.from_gdal(*self.geot),
geojson_out=keep,))
if keep:
df['GeoRaster'] = df.properties.apply(lambda x: GeoRaster(x['mini_raster_array'],
Affine.to_gdal(x['mini_raster_affine']),
nodata_value=x['mini_raster_nodata'],
projection=self.projection,
datatype=self.datatype))
cols = list(set([i for i in df.properties[0].keys()]).intersection(set(shp.columns)))
df2 = pd.DataFrame([df.properties.apply(lambda x: x[i]) for i in cols
]).T.merge(df[['GeoRaster']], left_index=True, right_index=True,)
df2.columns = cols+['GeoRaster']
df2 = df2.merge(df[['id']], left_index=True, right_index=True)
df2.set_index('id', inplace=True)
return df2
else:
df['GeoRaster'] = df.apply(lambda x: GeoRaster(x.mini_raster_array,
Affine.to_gdal(x.mini_raster_affine),
nodata_value=x.mini_raster_nodata,
projection=self.projection,
datatype=self.datatype), axis=1)
return df['GeoRaster'].values
def stats(self, shp, stats='mean', add_stats=None, raster_out=True, name=None, *args, **kwargs):
'''
Compute raster statistics for a given geometry in shape, where shape is either
a GeoPandas DataFrame, shapefile, or some other geometry format used by
python-raster-stats. Runs python-raster-stats in background
(additional help and info can be found there)
Returns dataframe with statistics and clipped raster
Usage:
df = geo.stats(shape, stats=stats, add_stats=add_stats)
where:
raster_out: If True (Default), returns clipped Georasters
'''
df = pd.DataFrame(zonal_stats(shp, self.raster, nodata=self.nodata_value,
all_touched=True, raster_out=raster_out,
affine=Affine.from_gdal(*self.geot),
geojson_out=True, stats=stats, add_stats=add_stats))
if raster_out:
df['GeoRaster'] = df.properties.apply(lambda x: GeoRaster(x['mini_raster_array'],
Affine.to_gdal(x['mini_raster_affine']),
nodata_value=x['mini_raster_nodata'],
projection=self.projection,
datatype=self.datatype))
statcols = list(set([i for i in df.properties[0].keys()]).difference(set(shp.columns)))
cols = shp.columns.tolist() + statcols
cols = [i for i in cols if i != 'geometry' and i.find('mini_raster') == -1]
df2 = pd.DataFrame([df.properties.apply(lambda x: x[i]) for i in cols]).T
if name is not None:
cols2 = shp.columns.difference(['geometry', 'mini_raster'], sort=False).tolist()
cols = cols2 + [name + '_' + i for i in cols[len(cols2):]]
df2.columns = cols
if raster_out:
df2 = df2.merge(df[['id', 'GeoRaster']], left_index=True, right_index=True)
else:
df2 = df2.merge(df[['id']], left_index=True, right_index=True)
df2.set_index('id', inplace=True)
return df2
def gini(self):
"""
geo.gini()
Return computed Gini coefficient.
"""
if self.count()>1:
xsort = sorted(self.raster.data[self.raster.mask == False].flatten()) # increasing order
y = np.cumsum(xsort)
B = sum(y) / (y[-1] * len(xsort))
return 1 + 1./len(xsort) - 2*B
else:
return 1
def flatten(self, *args, **kwargs):
'''
geo.flatten(order='C')
Return a copy of the array collapsed into one dimension.
Parameters
----------
order : {'C', 'F', 'A'}, optional
Whether to flatten in C (row-major), Fortran (column-major) order,
or preserve the C/Fortran ordering from `a`.
The default is 'C'.
'''
return self.raster.flatten(*args, **kwargs)
def apply(self, func, *args, **kwargs):
'''
geo.apply(func, *args, **kwargs)
Returns the value of applying function func on the raster data
func: Python function
*args: Arguments of function
**kwargs: Additional arguments of function
'''
return func(self.raster, *args, **kwargs)
def map_pixel(self, point_x, point_y):
'''
geo.map_pixel(point_x, point_y)
Return value of raster in location
Note: (point_x, point_y) must belong to the geographic coordinate system and
the coverage of the raster
'''
row, col = map_pixel(point_x, point_y,
self.x_cell_size, self.y_cell_size, self.xmin, self.ymax)
try:
return self.raster[row, col]
except:
raise RasterGeoError('Make sure the point belongs to the raster coverage \
and it is in the correct geographic coordinate system.')
def map_pixel_location(self, point_x, point_y):
'''
geo.map_pixel(point_x, point_y)
Return value of raster in location
'''
row, col = map_pixel(point_x, point_y, self.x_cell_size, self.y_cell_size,
self.xmin, self.ymax)
return np.array([row, col])
def extract(self, point_x, point_y, radius=0):
'''
geo.extract(x, y, radius=r)
Returns subraster of raster geo around location (x,y) with radius r
where (x,y) and r are in the same coordinate system as geo
'''
row, col = map_pixel(point_x, point_y, self.x_cell_size, self.y_cell_size,
self.xmin, self.ymax)
col2 = np.abs(radius/self.x_cell_size).astype(int)
row2 = np.abs(radius/self.y_cell_size).astype(int)
return GeoRaster(self.raster[max(row-row2, 0):min(row+row2+1, self.shape[0]), \
max(col-col2, 0):min(col+col2+1, self.shape[1])], self.geot,
nodata_value=self.nodata_value,\
projection=self.projection, datatype=self.datatype)
def extent(self, xmin, ymin, xmax, ymax):
'''
geo.extent(xmin, ymin, xmax, ymax)
Returns subraster of raster geo in extent
where (xmin, ymin, xmax, ymax) are in the same coordinate system as geo
usually comes from total_bounds of a geopandas dataframe
'''
row, col = self.map_pixel_location(xmin, ymin)
row2, col2 = self.map_pixel_location(xmax, ymax)
return GeoRaster(self.raster[row2:row, col:col2], self.geot,
nodata_value=self.nodata_value,\
projection=self.projection, datatype=self.datatype)
# Align GeoRasters
def align(self, alignraster, how=np.mean, cxsize=None, cysize=None):
'''
geo.align(geo2, how=np.mean)
Returns both georasters aligned and with the same pixelsize
'''
return align_georasters(self, alignraster, how=how, cxsize=cxsize, cysize=cysize)
def aggregate(self, block_size):
'''
geo.aggregate(block_size)
Returns copy of raster aggregated to smaller resolution, by adding cells.
'''
raster2 = block_reduce(self.raster, block_size, func=np.ma.sum)
geot = self.geot
geot = (geot[0], block_size[0] * geot[1], geot[2], geot[3], geot[4],
block_size[1] * geot[-1])
return GeoRaster(raster2, geot, nodata_value=self.nodata_value,\
projection=self.projection, datatype=self.datatype)
def block_reduce(self, block_size, how=np.ma.mean):
'''
geo.block_reduce(block_size, how=func)
Returns copy of raster aggregated to smaller resolution, by adding cells.
Default: func=np.ma.mean
'''
raster2 = block_reduce(self.raster, block_size, func=how)
geot = self.geot
geot = (geot[0], block_size[0] * geot[1], geot[2], geot[3], geot[4],
block_size[1] * geot[-1])
return GeoRaster(raster2, geot, nodata_value=self.nodata_value,\
projection=self.projection, datatype=self.datatype)
def resize(self, block_size, order=0, mode='constant', cval=False, preserve_range=True):
'''
geo.resize(new_shape, order=0, mode='constant', cval=np.nan, preserve_range=True)
Returns resized georaster
'''
if not cval:
cval = np.nan
raster2 = resize(self.raster.data, block_size, order=order, mode=mode,
cval=cval, preserve_range=preserve_range)
mask = resize(self.raster.mask, block_size, order=order, mode=mode,
cval=cval, preserve_range=preserve_range)
raster2 = np.ma.masked_array(raster2, mask=mask, fill_value=self.raster.fill_value)
raster2[raster2.mask] = self.nodata_value
raster2.mask = np.logical_or(np.isnan(raster2.data), raster2.data == self.nodata_value)
geot = list(self.geot)
[geot[-1],geot[1]] = np.array([geot[-1], geot[1]])*self.shape/block_size
return GeoRaster(raster2, tuple(geot), nodata_value=self.nodata_value,\
projection=self.projection, datatype=self.datatype)
def resize_old(self, block_size, order=0, mode='constant', cval=False):
'''
geo.resize(new_shape, order=0, mode='constant', cval=np.nan, preserve_range=True)
Returns resized georaster
'''
if not cval:
cval = np.nan
if (self.raster.dtype.name.find('float') != -1 and
np.max(np.abs([self.max(), self.min()])) > 1):
raster2 = (self.raster-self.min())/(self.max()-self.min())
else:
raster2 = self.raster.copy()
raster2 = raster2.astype(float)
raster2[self.raster.mask] = np.nan
raster2 = resize(raster2, block_size, order=order, mode=mode, cval=cval)
raster2 = np.ma.masked_array(raster2, mask=np.isnan(raster2),
fill_value=self.raster.fill_value)
raster2 = raster2*(self.max()-self.min())+self.min()
raster2[raster2.mask] = self.nodata_value