-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathProcessRasters.py
2016 lines (1644 loc) · 72.5 KB
/
ProcessRasters.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 -*-
"""
Created on Mon Jan 18 13:25:52 2024
@author: Gregory A. Greene
"""
import os
import numpy as np
import fiona
import pandas as pd
import geopandas as gpd
from geopandas import GeoDataFrame
import rasterio as rio
from rasterio.mask import mask
# from rasterio import CRS
from rasterio.features import shapes, geometry_window, geometry_mask, rasterize
from rasterio.merge import merge
from rasterio.transform import xy, from_origin, from_bounds, rowcol
from rasterio.warp import calculate_default_transform, reproject, Resampling
from rasterio.windows import Window
# from rasterio.io import MemoryFile
from rasterio.transform import Affine
from pyproj import Transformer
from shapely.geometry import Point, box, shape, mapping
from shapely.affinity import translate
from joblib import Parallel, delayed
from typing import Union, Optional
try:
from rasterio import shutil
except ImportError:
import shutil
def _calculate_cosine_incidence(slope, aspect, zenith, azimuth):
"""
Calculate the cosine of the solar incidence angle.
:param slope: Slope in radians.
:param aspect: Aspect in radians.
:param zenith: Solar zenith angle in radians.
:param azimuth: Solar azimuth angle in radians.
:return: Cosine of the solar incidence angle.
"""
return (
np.sin(zenith) * np.cos(slope)
+ np.cos(zenith) * np.sin(slope) * np.cos(azimuth - aspect)
)
def _process_block(block: np.ndarray,
transform: rio.io.DatasetReaderBase,
window: rio.io.WindowMethodsMixin) -> list:
"""
Process a block of the raster array and return shapes.
:param block:
:param transform:
:param window:
:return: list of shapes
"""
data = block
# Calculate the translation values for the window
dx, dy = transform * (window[1][0], window[0][0])
# Adjust the translation values to account for the original transform's translation
dx -= transform.c
dy -= transform.f
# Convert the block data into shapes and adjust the coordinates
return [(translate(shape(s), xoff=dx, yoff=dy), v) for s, v in shapes(data, transform=transform)]
def arrayToRaster(array: np.ndarray,
out_file: str,
ras_profile: dict,
nodata_val: Optional[Union[int, float]] = None,
dtype: np.dtype = np.float32) -> rio.DatasetReader:
"""
Function to convert a numpy array to a raster.
:param array: input numpy array
:param out_file: path (with name) to save output raster
:param ras_profile: profile of reference rasterio dataset reader object
:param nodata_val: new integer or floating point value to assign as "no data" (default = None)
:param dtype: the numpy data type of new raster
:return: rasterio dataset reader object in r+ mode
"""
# Get profile and verify array shape matches reference raster profile
profile = ras_profile.copy()
# Check if the dimensions match (height, width, bands)
required_shape = (profile['count'], profile['height'], profile['width'])
if array.shape != required_shape:
raise ValueError(f'Array shape {array.shape} does not match required shape {required_shape}')
# Update profile
profile.update(
compress='lzw' # Specify LZW compression
)
if nodata_val:
profile.update(
nodata=nodata_val # Specify nodata value
)
if dtype:
profile.update(
dtype=dtype
)
# Create new raster file
with rio.open(out_file, 'w', **profile) as dst:
# Write data to new raster
dst.write(array)
# Calculate new statistics
calculateStatistics(dst)
# Return new raster as "readonly" rasterio openfile object
return rio.open(out_file, 'r+')
def asciiToTiff(ascii_path: str,
out_file: str,
out_crs: str = 'EPSG:4326') -> rio.DatasetReader:
"""
Function to convert a TIFF to an ASCII file.
:param ascii_path: path to ASCII dataset
:param out_file: path (with name) to save TIF file
:param out_crs: string defining new projection (e.g., 'EPSG:4326')
:return: new rasterio dataset reader object in 'r+' mode
"""
# Read the ASCII file
with open(ascii_path, 'r') as f:
# Skip header lines and get metadata
header = {}
for _ in range(6):
key, value = f.readline().strip().split()
header[key] = float(value)
# Read the raster data
data = np.loadtxt(f)
# Extract metadata
ncols = int(header['ncols'])
nrows = int(header['nrows'])
xllcorner = header['xllcorner']
yllcorner = header['yllcorner']
cellsize = header['cellsize']
nodata_value = header['NODATA_value']
# Define the transformation
# Adjust the yllcorner to the top left y coordinate
yllcorner_top = yllcorner + nrows * cellsize
transform = from_origin(xllcorner, yllcorner_top, cellsize, cellsize)
# Write the data to a GeoTIFF file
with rio.open(out_file,
mode='w',
driver='GTiff',
height=nrows,
width=ncols,
count=1,
dtype=data.dtype,
crs=out_crs,
transform=transform,
nodata=nodata_value
) as dst:
dst.write(data, 1)
return rio.open(out_file, 'r+')
def calcSolarRadiation(
slope: np.ndarray,
aspect: np.ndarray,
elevation: np.ndarray,
lat: float,
lon: float,
start_date: str,
end_date: str,
out_file: str,
transform: Affine,
time_step: int = 60,
nodata: float = -9999
):
"""
Calculate solar radiation using pvlib for a given raster grid.
<<<<NOTE: THIS IS EXPERIMENTAL & UNTESTED>>>>
:param slope: Slope array (degrees).
:param aspect: Aspect array (degrees, clockwise from north).
:param elevation: Elevation array (meters).
:param lat: Latitude of the raster's region (degrees).
:param lon: Longitude of the raster's region (degrees).
:param start_date: Start date in 'YYYY-MM-DD' format.
:param end_date: End date in 'YYYY-MM-DD' format.
:param out_file: Path to save the solar radiation raster.
:param transform: GeoTransform for spatial reference.
:param time_step: Time step in minutes for radiation simulation (default 60).
:param nodata: Nodata value for the input arrays (default -9999).
:return: Path to the output solar radiation raster.
"""
import pvlib
# Mask nodata values
elevation = np.ma.masked_equal(elevation, nodata)
slope = np.ma.masked_equal(slope, nodata)
aspect = np.ma.masked_equal(aspect, nodata)
# Generate a time range
times = pd.date_range(start=start_date, end=end_date, freq=f'{time_step}T', tz='UTC')
# Precompute solar radiation components
solar_radiation = np.zeros(elevation.shape, dtype=np.float32)
for current_time in times:
# Get solar position
solar_position = pvlib.solarposition.get_solarposition(current_time, lat, lon, elevation.mean())
zenith = np.radians(solar_position['apparent_zenith'])
azimuth = np.radians(solar_position['azimuth'])
# Calculate the cosine of the solar incidence angle
cos_incidence = _calculate_cosine_incidence(np.radians(slope), np.radians(aspect), zenith, azimuth)
# Ignore night times (zenith > 90°)
cos_incidence[zenith > np.pi / 2] = 0
# Estimate direct normal irradiance (DNI)
clearsky = pvlib.clearsky.ineichen(solar_position['apparent_zenith'], altitude=elevation.mean())
dni = clearsky['dni'].values
# Calculate solar radiation
direct_radiation = dni[:, None, None] * cos_incidence
diffuse_radiation = 0.3 * direct_radiation # Estimate diffuse as 30% of direct
# Accumulate radiation over time
solar_radiation += np.clip(direct_radiation + diffuse_radiation, 0, None)
# Normalize by time range to get average radiation
solar_radiation /= len(times)
# Save the output raster
profile = {
'driver': 'GTiff',
'dtype': rio.float32,
'nodata': nodata,
'width': elevation.shape[1],
'height': elevation.shape[0],
'count': 1,
'crs': 'EPSG:4326', # Assuming lat/lon input
'transform': transform,
}
with rio.open(out_file, 'w', **profile) as dst:
dst.write(solar_radiation.astype(rio.float32), 1)
return out_file
def calculateStatistics(src: rio.DatasetReader) -> Union[rio.DatasetReader, None]:
"""
Function to recalculate statistics for each band of a rasterio dataset reader object.
:param src: input rasterio dataset reader object in 'r+' mode
:return: rasterio dataset reader object in 'r+' mode
"""
try:
# Calculate statistics for all bands
stats = src.stats()
# Update dataset tags with the new statistics
for i, band in enumerate(src.indexes):
# Convert the Statistics object to a dictionary
stats_dict = {
'min': stats[i].min,
'max': stats[i].max,
'mean': stats[i].mean,
'std': stats[i].std
}
src.update_tags(band, **stats_dict)
return src
except Exception:
for bidx in src.indexes:
try:
src.statistics(bidx, clear_cache=True)
except rio.errors.StatisticsError as e:
print(f'Rasterio Calculate Statistics Error: {e}')
continue
return
def changeDtype(src: rio.DatasetReader,
dtype: np.dtype,
nodata_val: Optional[Union[int, float]] = None) -> rio.DatasetReader:
"""
Function to change a raster's datatype to int or float.
:param src: input rasterio dataset reader object
:param dtype: new numpy data type (e.g., np.int32, np.float32)
:param nodata_val: value to assign as "no data" (default = None)
:return: rasterio dataset reader object in 'r+' mode
"""
if nodata_val is None:
nodata_val = src.profile['nodata']
# Convert array values to integer type
src_array = src.read()
src_array[src_array == src.nodata] = nodata_val
src_array = np.asarray(src_array, dtype=dtype)
# Get file path and profile of the dataset object
src_path = src.name
profile = src.profile
# Specify LZW compression and assign integer datatype
profile.update(
compress='lzw',
nodata=nodata_val,
dtype=dtype)
src.close()
# Create new raster file
with rio.open(src_path, 'w', **profile) as dst:
# Write data to new raster
dst.write(src_array)
# Calculate new statistics
calculateStatistics(dst)
return rio.open(src_path, 'r+')
def clipRaster_wRas(src: rio.DatasetReader,
mask_src: rio.DatasetReader,
out_file: str,
all_touched: Optional[bool] = True,
crop: Optional[bool] = True) -> rio.DatasetReader:
"""
Function to clip a raster with the extent of another raster.
:param src: rasterio dataset reader object being masked
:param mask_src: rasterio dataset reader object used as a mask
:param out_file: location and name to save output raster
:param all_touched: include all cells that touch the raster boundary (in addition to inside the boundary)
(default = True)
:param crop: crop output extent to match the extent of the data (default = True)
:return: rasterio dataset reader object in 'r+' mode
"""
geometry = [box(*mask_src.bounds)]
out_array, out_transform = mask(src, geometry, all_touched=all_touched, crop=crop)
out_profile = src.profile
src.close()
out_profile.update(
height=out_array.shape[1],
width=out_array.shape[2],
transform=out_transform
)
# Create new raster file
with rio.open(out_file, 'w', **out_profile) as dst:
# Write data to new raster
dst.write(out_array)
# Calculate new statistics
calculateStatistics(dst)
return rio.open(out_file, 'r+')
def clipRaster_wShape(src: rio.DatasetReader,
shape_path: str,
out_file: str,
select_field: Optional[str] = None,
select_value: Optional[Union[any, list[any]]] = None,
all_touched: Optional[bool] = True,
crop: Optional[bool] = True,
use_extent: Optional[bool] = False,
new_nodata_val: Optional[float] = None) -> rio.DatasetReader:
"""
Function to clip a raster with a shapefile or its extent.
:param src: input rasterio dataset reader object
:param shape_path: file path to clip shapefile
:param out_file: location and name to save output raster
:param select_field: name of field to use to select specific features for clipping
:param select_value: value(s) in select_field to use for the feature selection
:param all_touched: If True, all cells touching the shapefile boundary are included (default = True)
:param crop: crop output extent to match the extent of the data (default = True)
:param use_extent: If True, clip raster using the shapefile's bounding box (default = False)
:param new_nodata_val: Value to replace the existing no data value in the output raster (default = None)
:return: rasterio dataset reader object in 'r+' mode
"""
if select_field is not None:
if not isinstance(select_field, str):
raise ValueError('Parameter "select_field" must be str type')
if select_value is None:
raise ValueError('Parameter "select_value" requires a value when selecting features')
src_path = src.name
src.close()
# Get the shapefile geometries
with fiona.open(shape_path, 'r') as shapefile:
if select_field is not None:
if isinstance(select_value, list):
filtered_features = [
feature for feature in shapefile
if feature['properties'][select_field] in select_value
]
else:
filtered_features = [
feature for feature in shapefile
if feature['properties'][select_field] == select_value
]
geometries = [feature['geometry'] for feature in filtered_features]
if not geometries:
raise RuntimeWarning(f'No features found with {select_field} = {select_value}')
else:
geometries = [feature['geometry'] for feature in shapefile]
if use_extent:
# Get the bounding box of the shapefile
shp_bounds = shapefile.bounds
extent_geom = {
'type': 'Polygon',
'coordinates': [[
[shp_bounds[0], shp_bounds[1]],
[shp_bounds[0], shp_bounds[3]],
[shp_bounds[2], shp_bounds[3]],
[shp_bounds[2], shp_bounds[1]],
[shp_bounds[0], shp_bounds[1]]
]]
}
geometries = [extent_geom]
# Open the raster file
with rio.open(src_path) as new_src:
if new_src.nodata is None:
nodata_val = np.nan
else:
nodata_val = new_src.nodata
# Clip the raster using the geometries or extent
out_image, out_transform = mask(new_src, geometries, nodata=nodata_val, all_touched=all_touched, crop=crop)
out_meta = new_src.meta.copy()
# Replace the existing no data value if new_nodata_val is specified
if new_nodata_val is not None:
# Convert the existing no data value to the new one
out_image[~np.isfinite(out_image)] = new_nodata_val
out_image[out_image == nodata_val] = new_nodata_val
out_meta['nodata'] = new_nodata_val
# Update the metadata with the new dimensions, transform, and CRS
out_meta.update(
{
'height': out_image.shape[1],
'width': out_image.shape[2],
'transform': out_transform
}
)
with rio.open(out_file, 'w', **out_meta) as dst:
dst.write(out_image)
# Calculate new statistics
calculateStatistics(dst)
return rio.open(out_file, 'r+')
def copyRaster(src: rio.DatasetReader,
out_file: str,
band: int = None) -> rio.DatasetReader:
"""
Function to copy a raster to a new location or export a specific band.
:param src: input rasterio dataset reader object
:param out_file: location and name to save output raster
:param band: specific band number to export (1-based index), optional
:return: rasterio dataset reader object in 'r+' mode
"""
if band is not None:
# Validate band number
if band < 1 or band > src.count:
raise ValueError(f'Band number {band} is out of range. Source has {src.count} bands.')
# Read the specific band
band_data = src.read(band)
# Create a new raster file with the selected band
profile = src.profile
profile.update(count=1) # Set the number of bands to 1
with rio.open(out_file, 'w', **profile) as dst:
dst.write(band_data, 1)
else:
try:
shutil.copyfiles(src.name, out_file)
except AttributeError:
try:
shutil.copyfile(src.name, out_file)
except AttributeError:
raise RuntimeError('Unable to copy file. Both shutil and raster.shutil methods failed.')
return rio.open(out_file, 'r+')
def defineProjection(src: rio.DatasetReader,
crs: Optional[str] = 'EPSG:4326') -> rio.DatasetReader:
"""
Function to define the projection of a raster when the projection is missing (i.e., not already defined).
:param src: input rasterio dataset reader object
:param crs: location and name to save output raster (default = 'EPSG:4326')
:return: rasterio dataset reader object in 'r+' mode
"""
# Get path of input source dataset
src_path = src.name
# Close input source dataset
src.close()
# Reproject raster and write to out_file
with rio.open(src_path, 'r+') as dst:
# Update the CRS in the dataset's metadata
dst.crs = crs
# Calculate new statistics
calculateStatistics(dst)
# Return new raster as "readonly" rasterio openfile object
return rio.open(src_path, 'r+')
def exportRaster(src: rio.DatasetReader,
out_file: str) -> rio.DatasetReader:
"""
Function to export a raster to a new location.
:param src: input rasterio dataset reader object
:param out_file: location and name to save output raster
:return: rasterio dataset reader object
"""
# Get profile
src_profile = src.profile
# Specify LZW compression
src_profile.update(
compress='lzw'
)
# Get raster array
src_array = src.read()
# Create new raster file
with rio.open(out_file, 'w', **src_profile) as dst:
# Write data to new raster
dst.write(src_array)
# Calculate new statistics
calculateStatistics(dst)
return
def extractValuesAtPoints(in_pts: Union[str, GeoDataFrame],
src: rio.DatasetReader,
value_field: str,
out_type: str = 'series',
new_pts_path: Optional[str] = None) -> Union[pd.Series, None]:
"""
Function to extract raster values at shapefile point locations.
:param in_pts: path to, or a GeoDataFrame object of, the point shapefile
:param src: input rasterio dataset reader object
:param value_field: name of field to contain raster values
:param out_type: type of output ("gdf", "series", "shp", "csv")
:param new_pts_path: path to new point shapefile, if out_type == 'shp' (default = None)
:return: a GeoDataFrame object (if out_type is "gdf"),
a pandas series object (if out_type is "series"), or None (if out_type is "shp" or "csv")
"""
# If in_pts is not str or GeoDataFrame type, raise error
if not isinstance(in_pts, (str, GeoDataFrame)):
raise TypeError('Parameter "in_pts" must be a str or GeoPandas GeoDataFrame type')
# If in_pts is str type, get GeoDataFrame object from path
if isinstance(in_pts, str):
gdf = gpd.read_file(in_pts)
elif isinstance(in_pts, GeoDataFrame):
gdf = in_pts
# Extract raster values at point locations, and assign to "value_field"
gdf[f'{value_field}'] = next(src.sample(zip(gdf['geometry'].x, gdf['geometry'].y)))[0]
# Return raster point values
if out_type == 'gdf':
return gdf
elif out_type == 'series':
return gdf[f'{value_field}']
elif out_type == 'shp':
gdf.to_file(new_pts_path)
elif out_type == 'csv':
gdf.to_csv(new_pts_path)
else:
raise TypeError('[ProcessRasters] extractValuesAtPoints() function parameter "out_type" '
'must be either "series", "shp" or "csv"')
return
def extractRowsColsWithPoly(in_poly: Union[str, fiona.Collection],
src: rio.DatasetReader,
id_field: str) -> list:
"""
Function to extract a list of global row and column numbers from a raster (numpy array) with a polygon shapefile.
:param in_poly: path to, or a fiona collection object of, a polygon shapefile
:param src: input rasterio dataset reader object
:param id_field: name of field in shapefile to use as feature ID
:return: a list of row and column numbers [(row1, col1), (row2, col2), ...]
"""
# If in_pts is str type, get fiona dataset object from path
if isinstance(in_poly, str):
in_poly = fiona.open(in_poly)
# Get the transform and projection of the raster file
crs = src.crs
nodata_value = src.nodata
# Check if the shapefile's CRS matches the raster's CRS
shapefile_crs = in_poly.crs
if shapefile_crs != crs:
raise ValueError('Shapefile and raster CRS do not match')
output_list = []
for feature in in_poly:
geom = shape(feature['geometry'])
district_id = feature['properties'][id_field]
# Calculate the window of the raster that intersects with the geometry
window = geometry_window(src, [mapping(geom)], pad_x=1, pad_y=1)
# Read the data in the window
raster_data = src.read(1, window=window, masked=True)
# Skip if the window data is empty
if (raster_data.size == 0) or np.all(raster_data.mask):
continue
# Get the affine transformation for the window
window_transform = src.window_transform(window)
# Create a mask for the geometry
geom_mask = geometry_mask(
geometries=[mapping(geom)],
transform=window_transform,
invert=True,
out_shape=(raster_data.shape[0],
raster_data.shape[1])
)
# Apply the geometry mask and check for NoData values
valid_mask = (raster_data.data != nodata_value) * geom_mask
# Get the row and column indices of the masked cells
rows, cols = np.where(valid_mask)
# Skip if no rows/cols are found
if len(rows) == 0 or len(cols) == 0:
continue
# Convert to global indices
global_rows = rows + window.row_off
global_cols = cols + window.col_off
row_col_pairs = list(zip(global_rows, global_cols))
# Append the district ID and the row/column indices to the output list
output_list.append([district_id, row_col_pairs])
return output_list
def featureToRaster(feature_path: str,
out_path: str,
ref_ras_src: rio.DatasetReader,
value_field: str) -> rio.DatasetReader:
"""
Function creates a raster from a shapefile.
:param feature_path: path to feature dataset
:param out_path: path to output raster
:param ref_ras_src: rasterio DatasetReader object to use as reference
:param value_field: name of the field/column to use for the raster values
:return: rasterio dataset reader object in 'r+' mode
"""
def _infer_raster_dtype(dtype):
"""Map pandas dtype to rasterio dtype."""
if dtype.startswith('int'):
return 'int32'
elif dtype.startswith('float'):
return 'float32'
elif dtype == 'bool':
return 'uint8'
else:
return 'str'
# Get GeoPandas object of the feature dataset
src = gpd.read_file(feature_path)
# Ensure the value_field contains numeric values
if not pd.api.types.is_numeric_dtype(src[value_field]):
raise ValueError(f"The field '{value_field}' contains non-numeric values.")
# Infer the appropriate raster dtype based on the feature data type
pandas_dtype = pd.api.types.infer_dtype(src[value_field])
raster_dtype = _infer_raster_dtype(pandas_dtype)
# Get the schema of the reference raster, including the crs
meta = ref_ras_src.meta.copy()
meta.update(compress='lzw', dtype=raster_dtype)
with rio.open(out_path, 'w+', **meta) as dst:
# Get the raster array with the correct dtype
dst_arr = dst.read(1).astype(raster_dtype)
# Create a generator of geom, value pairs to use while rasterizing
shapes = ((geom, value) for geom, value in zip(src['geometry'], src[value_field]))
# Replace the raster array with new data
burned = rasterize(shapes=shapes,
fill=0,
out=dst_arr,
transform=dst.transform)
# Write the new data to band 1
dst.write_band(1, burned)
return rio.open(out_path, 'r+')
def getArea(src: rio.DatasetReader,
search_value: Union[int, float, list[int, float]]) -> float:
"""
Function to calculate the area of all cells matching a value or values.
:param src: input rasterio dataset reader object
:param search_value: raster value(s) to get area of
:return: area (in units of raster)
"""
if not isinstance(search_value, list):
search_value = [search_value]
x, y = getResolution(src)
src_array = src.read()
value_count = 0
for value in search_value:
value_count += np.count_nonzero(src_array == value)
return x * y * value_count
def getAspect(src: rio.DatasetReader,
out_file: str) -> rio.DatasetReader:
"""
Function to generate a slope aspect raster from an elevation dataset.
:param src: a rasterio dataset reader object
:param out_file: the path and name of the output file
:return: rasterio dataset reader object in r+ mode
"""
from osgeo import gdal
# Enable exceptions in GDAL to handle potential errors
gdal.UseExceptions()
# Get file path of dataset object
src_path = src.name
gdal.DEMProcessing(out_file,
src_path,
'aspect')
# Calculate new statistics
temp_src = getRaster(out_file)
calculateStatistics(temp_src)
temp_src.close()
return rio.open(out_file, 'r+')
def getFirstLast(in_rasters: list[rio.DatasetReader],
out_file: str,
first_last: str,
full_extent: bool = True) -> rio.DatasetReader:
"""
Function creates a new raster using the first valid values per cell across all input rasters.
:param in_rasters: list of rasterio dataset reader objects
:param out_file: the path and name of the output file
:param first_last: output the first or last value (Options: "first", "last")
:param full_extent: boolean indicating whether to use the (True) full extent of all rasters,
or (False) only the overlapping extent
:return: rasterio dataset reader object in 'r+' mode
"""
# Verify inputs
if not isinstance(in_rasters, list):
raise TypeError('[ProcessRasters] getFirstLast() param "in_rasters" must be a list of rasterio objects')
if not isinstance(out_file, str):
raise TypeError('[ProcessRasters] getFirstLast() param "out_file" must be a string data type')
if not isinstance(first_last, str):
raise TypeError('[ProcessRasters] getFirstLast() param "first_last" must be a string data type')
elif first_last not in ['first', 'last']:
raise ValueError('[ProcessRasters] getFirstLast() param "first_last" must be either "first" or "last"')
if not isinstance(full_extent, bool):
raise TypeError('[ProcessRasters] getFirstLast() param "full_extent" must be a boolean data type')
# Use the appropriate bounds option based on full_extent parameter
bounds = None if full_extent else 'intersection'
# Merge rasters to get the first valid values
mosaic, out_trans = merge(in_rasters, method='first', bounds=bounds)
# Update the profile with new dimensions and transform
profile = in_rasters[0].profile
profile.update({
'height': mosaic.shape[1],
'width': mosaic.shape[2],
'transform': out_trans
})
# Create new raster file and write data
with rio.open(out_file, 'w', **profile) as dst:
dst.write(mosaic)
return rio.open(out_file, 'r+')
def getGridCoordinates(src: rio.DatasetReader,
out_file_x: str,
out_file_y: str,
out_crs: str = 'EPSG:4326',
dtype: np.dtype = np.float32) -> tuple[rio.DatasetReader, rio.DatasetReader]:
"""
Function returns two X and Y rasters with cell values matching the grid cell coordinates (one for Xs, one for Ys).
:param src: a rasterio dataset reader object
:param out_file_x: path to output raster for X coordinates
:param out_file_y: path to output raster for Y coordinates
:param out_crs: string defining new projection (e.g., 'EPSG:4326')
:param dtype: numpy data type for output rasters (default is np.float32)
:return: a tuple (X, Y) of rasterio dataset reader objects in 'r+' mode
"""
# Get the affine transformation matrix
transform = src.transform
# Get the coordinate reference system (CRS) of the input raster
src_crs = src.crs
# Get the number of rows and columns in the raster
rows, cols = src.height, src.width
# Get the geolocation of the top-left corner and pixel size
x_start, y_start = transform * (0, 0)
x_end, y_end = transform * (cols, rows)
pixel_size_x = (x_end - x_start) / cols
pixel_size_y = (y_end - y_start) / rows
# Create a new affine transformation matrix for EPSG:4326
transformer = Transformer.from_crs(src_crs, out_crs, always_xy=True)
# Calculate the x & y coordinates for each cell
x_coords = np.linspace(x_start + pixel_size_x / 2, x_end - pixel_size_x / 2, cols)
y_coords = np.linspace(y_start + pixel_size_y / 2, y_end - pixel_size_y / 2, rows)
lon, lat = np.meshgrid(x_coords, y_coords)
lon, lat = transformer.transform(lon.flatten(), lat.flatten())
# Reshape the lon and lat arrays to match the shape of the raster
lon = lon.reshape(rows, cols).astype(dtype)
lat = lat.reshape(rows, cols).astype(dtype)
# Create output profiles for x and y coordinate rasters, setting dtype to the specified parameter
profile = src.profile.copy()
profile.update(dtype=dtype)
# Write X coordinate data to out_path_x
with rio.open(out_file_x, 'w', **profile) as dst:
dst.write(lon, 1)
calculateStatistics(dst)
# Write Y coordinate data to out_path_y
with rio.open(out_file_y, 'w', **profile) as dst:
dst.write(lat, 1)
calculateStatistics(dst)
return rio.open(out_file_x, 'r+'), rio.open(out_file_y, 'r+')
def getHillshade(src: rio.DatasetReader,
out_file: str) -> rio.DatasetReader:
"""
Function to generate a hillshade from an elevation dataset.
:param src: a rasterio dataset reader object
:param out_file: the path and name of the output file
:return: rasterio dataset reader object
"""
from osgeo import gdal
# Get file path of dataset object
src_path = src.name
gdal.DEMProcessing(out_file,
src_path,
'hillshade')
# Calculate new statistics
temp_src = getRaster(out_file)
calculateStatistics(temp_src)
temp_src.close()
return rio.open(out_file, 'r+')
def getMean(in_rasters: list[rio.DatasetReader],
out_file: str,
full_extent: bool = True) -> rio.DatasetReader:
"""
Function creates a new raster from the mean value per cell across all input rasters.
:param in_rasters: list of rasterio dataset reader objects
:param out_file: the path and name of the output file
:param full_extent: boolean indicating whether to use (True) the full extent of all rasters,
or (False) only the overlapping extent (default = True)
:return: rasterio dataset reader object in 'r+' mode
"""
# Verify inputs
if not isinstance(in_rasters, list):
raise TypeError('[ProcessRasters] getMean() param "inrasters" must be a list of rasterio objects')
if not isinstance(out_file, str):
raise TypeError('[ProcessRasters] getMean() param "out_file" must be a string data type')
if not isinstance(full_extent, bool):
raise TypeError('[ProcessRasters] getMean() param "full_extent" must be a boolean data type')
# Use the appropriate bounds option based on full_extent parameter
bounds = None if full_extent else 'intersection'
# Merge rasters to get the mean values
mosaic, out_trans = merge(in_rasters, method='mean', bounds=bounds)
# Update the profile with new dimensions and transform
profile = in_rasters[0].profile
profile.update({
'height': mosaic.shape[1],
'width': mosaic.shape[2],
'transform': out_trans
})
# Create new raster file and write data
with rio.open(out_file, 'w', **profile) as dst:
dst.write(mosaic)
return rio.open(out_file, 'r+')
def getMinMax(in_rasters: Union[list[str], list[rio.DatasetReader]],
out_file: str,
min_max: str,
full_extent: bool = True) -> rio.DatasetReader:
"""
Function creates a new raster from the minimum or maximum values per cell across all input rasters.
:param in_rasters: list of file paths or rasterio dataset reader objects
:param out_file: the path and name of the output file
:param min_max: output the minimum or maximum value (Options: "min", "max")
:param full_extent: boolean indicating whether to use (True) the full extent of all rasters,
or (False) only the overlapping extent (default = True)
:return: rasterio dataset reader object in 'r+' mode
"""
# Verify inputs
if not isinstance(in_rasters, list):
raise TypeError('[ProcessRasters] getMinMax() param "inrasters" must be '
'a list of file paths or rasterio dataset reader objects')
if not isinstance(out_file, str):
raise TypeError('[ProcessRasters] getMinMax() param "out_file" must be a string data type')
if not isinstance(min_max, str):
raise TypeError('[ProcessRasters] getMinMax() param "min_max" must be a string data type')
elif min_max not in ['min', 'max']:
raise ValueError('[ProcessRasters] getMinMax() param "min_max" must be either "min" or "max"')
if not isinstance(full_extent, bool):
raise TypeError('[ProcessRasters] getMinMax() param "full_extent" must be a boolean data type')
# Get list of rasterio dataset reader objects if list of file paths was provided
if isinstance(in_rasters[0], str):
in_rasters = [getRaster(path) for path in in_rasters]
# Use the appropriate bounds option based on full_extent parameter
bounds = None if full_extent else 'intersection'