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 | @pyplugs.register
def writer(
id: str,
src: str,
extent: str,
dst: str,
cellsize: float,
dst_srs: str = "EPSG:5070",
):
"""Packager writer plugin
Parameters
----------
id : str
Download ID
src : list
List of objects describing the GeoTiff (COG)
extent : dict
Object with watershed name and bounding box
dst : str
Temporary directory
cellsize : float
Grid resolution
dst_srs : str, optional
Destination Spacial Reference, by default "EPSG:5070"
Returns
-------
str
FQPN to dss file
"""
def _zwrite(dssfilename, gridStructStore, data_flat):
_ = heclib.zwrite_record(
dssfilename=dssfilename,
gridStructStore=gridStructStore,
data_flat=data_flat.astype(numpy.float32),
)
_ = None
return
# convert the strings back to json objects; needed for pyplugs
src = json.loads(src)
gridcount = len(src)
extent = json.loads(extent)
_extent_name = extent["name"]
_bbox = extent["bbox"]
_progress = 0
# assuming destination spacial references are all EPSG
destination_srs = osr.SpatialReference()
epsg_code = dst_srs.split(":")[-1]
destination_srs.ImportFromEPSG(int(epsg_code))
###### this can go away when the payload has the resolution ######
grid_type_name = "SHG"
grid_type = heclib.dss_grid_type[grid_type_name]
zcompression = heclib.compression_method["ZLIB_COMPRESSION"]
srs_definition = heclib.spatial_reference_definition[grid_type_name]
tz_name = "GMT"
tz_offset = heclib.time_zone[tz_name]
is_interval = 1
for idx, tif in enumerate(src):
TifCfg = namedtuple("TifCfg", tif)(**tif)
dsspathname = f"/{grid_type_name}/{_extent_name}/{TifCfg.dss_cpart}/{TifCfg.dss_dpart}/{TifCfg.dss_epart}/{TifCfg.dss_fpart}/"
try:
dssfilename = os.path.join(dst, id + ".dss")
data_type = heclib.data_type[TifCfg.dss_datatype]
ds = gdal.Open(f"/vsis3_streaming/{TifCfg.bucket}/{TifCfg.key}")
if LOGGER_LEVEL.lower == "debug":
log_dataset(ds, "BEFORE")
# GDAL Warp the Tiff to what we need for DSS
filename_ = os.path.basename(TifCfg.key)
mem_raster = f"/vsimem/{filename_}"
warp_ds = gdal.Warp(
mem_raster,
ds,
format="GTiff",
outputBounds=_bbox,
xRes=cellsize,
yRes=cellsize,
targetAlignedPixels=True,
dstSRS=destination_srs.ExportToWkt(),
resampleAlg="bilinear",
copyMetadata=False,
)
if LOGGER_LEVEL.lower == "debug":
log_dataset(warp_ds, "AFTER")
# Read data into 1D array
raster = warp_ds.GetRasterBand(1)
nodata = raster.GetNoDataValue()
data = raster.ReadAsArray(resample_alg=gdal.gdalconst.GRIORA_Bilinear)
if "PRECIP" in TifCfg.dss_cpart.upper() and nodata != 0:
# TODO: Confirm this logic and add comment explaining
data[data == nodata] = 0
nodata = 0
data_flat = data.flatten()
# GeoTransforma and lower X Y
xsize, ysize = warp_ds.RasterXSize, warp_ds.RasterYSize
adfGeoTransform = warp_ds.GetGeoTransform()
llx = int(adfGeoTransform[0] / adfGeoTransform[1])
lly = int(
(adfGeoTransform[5] * ysize + adfGeoTransform[3]) / adfGeoTransform[1]
)
spatialGridStruct = heclib.zStructSpatialGrid()
spatialGridStruct.pathname = c_char_p(dsspathname.encode())
spatialGridStruct._structVersion = c_int(-100)
spatialGridStruct._type = c_int(grid_type)
spatialGridStruct._version = c_int(1)
spatialGridStruct._dataUnits = c_char_p(str.encode(TifCfg.dss_unit))
spatialGridStruct._dataType = c_int(data_type)
spatialGridStruct._dataSource = c_char_p("INTERNAL".encode())
spatialGridStruct._lowerLeftCellX = c_int(llx)
spatialGridStruct._lowerLeftCellY = c_int(lly)
spatialGridStruct._numberOfCellsX = c_int(xsize)
spatialGridStruct._numberOfCellsY = c_int(ysize)
spatialGridStruct._cellSize = c_float(cellsize)
spatialGridStruct._compressionMethod = c_int(zcompression)
spatialGridStruct._srsName = c_char_p(grid_type_name.encode())
spatialGridStruct._srsDefinitionType = c_int(1)
spatialGridStruct._srsDefinition = c_char_p(srs_definition.encode())
spatialGridStruct._xCoordOfGridCellZero = c_float(0)
spatialGridStruct._yCoordOfGridCellZero = c_float(0)
if nodata is not None:
spatialGridStruct._nullValue = c_float(nodata)
spatialGridStruct._timeZoneID = c_char_p(tz_name.encode())
spatialGridStruct._timeZoneRawOffset = c_int(tz_offset)
spatialGridStruct._isInterval = c_int(is_interval)
spatialGridStruct._isTimeStamped = c_int(1)
# Call heclib.zwrite_record() in different process space to release memory after each iteration
_p = multiprocessing.Process(
target=_zwrite,
args=(dssfilename, spatialGridStruct, data_flat.astype(numpy.float32)),
)
_p.start()
_p.join()
_progress = int(((idx + 1) / gridcount) * 100)
# Update progress at predefined interval
if idx % PACKAGER_UPDATE_INTERVAL == 0 or idx == gridcount - 1:
logger.debug(f"Progress: {_progress}")
update_status(
id=id, status_id=PACKAGE_STATUS["INITIATED"], progress=_progress
)
except (RuntimeError, Exception) as ex:
logger.error(f"{type(ex).__name__}: {this}: {ex}")
update_status(id=id, status_id=PACKAGE_STATUS["FAILED"], progress=_progress)
return None
finally:
spatialGridStruct = None
adfGeoTransform = None
raster = None
nodata = None
data = None
data_flat = None
warp_ds = None
gdal.Unlink(mem_raster)
TifCfg = None
data_type = None
ds = None
grid_type = None
zcompression = None
srs_definition = None
tz_offset = None
src = None
return dssfilename
|