-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclassify_MODIS_hdf_SST.py
More file actions
357 lines (290 loc) · 18.3 KB
/
Copy pathclassify_MODIS_hdf_SST.py
File metadata and controls
357 lines (290 loc) · 18.3 KB
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
Created on Wed Oct 21 14:38:31 2020
@author: guitar79
created by Kevin
#Open hdf file
NameError: name 'SD' is not defined
conda install -c conda-forge pyhdf
runfile('./classify_MODIS_hdf_MP-01.py', 'daily 2011', wdir='./KOSC_MODIS_SST_Python/')
len(npy_data[795,183])
np.mean(npy_data[795,183])
hdf_data = np.load(f_name1, allow_pickle=True)
'''
from glob import glob
from datetime import datetime
import numpy as np
import os
import sys
from sys import argv
import _MODIS_AOD_utilities
#script, L3_perid, yr = argv # Input L3_perid : 'weekly' 'monthly' 'daily'
print("argv: {}".format(argv))
if len(argv) < 3 :
print ("len(argv) < 2\nPlease input L3_perid and year \n ex) aaa.py daily 2016\n ex) aaa.py weekly 2016\n ex) aaa.py monthly 2016")
sys.exit()
elif len(argv) > 3 :
print ("len(argv) > 2\nPlease input L3_perid and year \n ex) aaa.py daily 2016\n ex) aaa.py weekly 2016\n ex) aaa.py monthly 2016")
sys.exit()
elif argv[1] == 'daily' or argv[1] == 'weekly' or argv[1] == 'monthly' :
L3_perid, yr = argv[1], int(argv[2])
print("{}, {} processing started...".format(argv[1], argv[2]))
else :
print("Please input L3_perid and year \n ex) aaa.py daily 2016\n ex) aaa.py weekly 2016\n ex) aaa.py monthly 2016")
sys.exit()
#L3_perid, yr = "daily", 2019
add_log = True
if add_log == True :
log_file = 'MODIS_SST_python.log'
err_log_file = 'MODIS_SST_python.log'
DATAFIELD_NAME = "sst"
#Set lon, lat, resolution
Llon, Rlon = 110, 150
Slat, Nlat = 10, 60
resolution = 0.1
base_dir_name = '../MODIS_L2_SST/'
save_dir_name = "../{0}_L3/{0}_{1}_{2}_{3}_{4}_{5}_{6}/".format(DATAFIELD_NAME, str(Llon), str(Rlon),
str(Slat), str(Nlat), str(resolution), L3_perid)
if not os.path.exists(save_dir_name):
os.makedirs(save_dir_name)
print ('*'*80)
print (save_dir_name, 'is created')
else :
print ('*'*80)
print (save_dir_name, 'is exist')
years = range(yr, yr+1)
proc_dates = []
#make processing period tuple
for year in years:
dir_name = base_dir_name + str(year) + '/'
from dateutil.relativedelta import relativedelta
s_start_date = datetime(year, 1, 1) #convert startdate to date type
s_end_date = datetime(year+1, 1, 1)
k=0
date1 = s_start_date
date2 = s_start_date
while date2 < s_end_date :
k += 1
if L3_perid == 'daily' :
date2 = date1 + relativedelta(days=1)
elif L3_perid == 'weekly' :
date2 = date1 + relativedelta(days=8)
elif L3_perid == 'monthly' :
date2 = date1 + relativedelta(months=1)
date = (date1, date2, k)
proc_dates.append(date)
date1 = date2
#### make dataframe from file list
fullnames = sorted(glob(os.path.join(base_dir_name, '*.hdf')))
fullnames_dt = []
for fullname in fullnames :
fullnames_dt.append(MODIS_hdf_utilities.fullname_to_datetime_for_KOSC_MODIS_SST(fullname))
import pandas as pd
len(fullnames)
len(fullnames_dt)
# Calling DataFrame constructor on list
df = pd.DataFrame({'fullname':fullnames,'fullname_dt':fullnames_dt})
df.index = df['fullname_dt']
df
for proc_date in proc_dates:
df_proc = df[(df['fullname_dt'] >= proc_date[0]) & (df['fullname_dt'] < proc_date[1])]
if os.path.exists('{0}{1}_{2}_{3}_{4}_{5}_{6}_{7}_{8}_alldata.npy'\
.format(save_dir_name, DATAFIELD_NAME, proc_date[0].strftime('%Y%m%d'), proc_date[1].strftime('%Y%m%d'),
str(Llon), str(Rlon), str(Slat), str(Nlat), str(resolution)))\
and os.path.exists('{0}{1}_{2}_{3}_{4}_{5}_{6}_{7}_{8}_info.txt'\
.format(save_dir_name, DATAFIELD_NAME, proc_date[0].strftime('%Y%m%d'), proc_date[1].strftime('%Y%m%d'),
str(Llon), str(Rlon), str(Slat), str(Nlat), str(resolution))) :
print(('{0}{1}_{2}_{3}_{4}_{5}_{6}_{7}_{8} files are exist...'\
.format(save_dir_name, DATAFIELD_NAME, proc_date[0].strftime('%Y%m%d'), proc_date[1].strftime('%Y%m%d'),
str(Llon), str(Rlon), str(Slat), str(Nlat), str(resolution))))
else :
if len(df_proc) != 0 :
print("df_proc: {}".format(df_proc))
processing_log = "#This file is created using Python : https://github.com/guitar79/KOSC_MODIS_SST_Python\n"
processing_log += "#L3_perid = {}, start date = {}, end date = {}\n"\
.format(L3_perid, proc_date[0].strftime('%Y%m%d'), proc_date[1].strftime('%Y%m%d'))
processing_log += "#Llon = {}, Rlon = {}, Slat = {}, Nlat = {}, resolution = {}\n"\
.format(str(Llon), str(Rlon), str(Slat), str(Nlat), str(resolution))
# make lat_array, lon_array, array_data
print("{0}-{1} Start making grid arrays...\n".\
format(proc_date[0].strftime('%Y%m%d'), proc_date[1].strftime('%Y%m%d')))
array_data = MODIS_hdf_utilities.make_grid_array(Llon, Rlon, Slat, Nlat, resolution)
print('Grid arrays are created...........\n')
total_data_cnt = 0
file_no = 0
processing_log += '#processing file list\n'
processing_log += '#file No, data_count, filename, hdf_attribute\n'
for fullname in df_proc["fullname"] :
fullname_el = fullname.split("/")
array_alldata = array_data.copy()
print("Reading hdf file {0}\n".format(fullname))
hdf_raw, latitude, longitude, cntl_pt_cols, cntl_pt_rows \
= MODIS_hdf_utilities.read_MODIS_hdf_to_ndarray(fullname, DATAFIELD_NAME)
hdf_value = hdf_raw[:,:]
if 'bad_value_scaled' in hdf_raw.attributes() :
#hdf_value[hdf_value == hdf_raw.attributes()['bad_value_scaled']] = np.nan
hdf_value = np.where(hdf_value == hdf_raw.attributes()['bad_value_scaled'], np.nan, hdf_value)
print("'bad_value_scaled' data is changed to np.nan...\n")
elif 'fill_value' in hdf_raw.attributes() :
#hdf_value[hdf_value == hdf_raw.attributes()['fill_value']] = np.nan
hdf_value = np.where(hdf_value == hdf_raw.attributes()['fill_value'], np.nan, hdf_value)
print("'fill_value' data is changed to np.nan...\n")
elif '_FillValue' in hdf_raw.attributes() :
#hdf_value[hdf_value == hdf_raw.attributes()['_FillValue']] = np.nan
hdf_value = np.where(hdf_value == hdf_raw.attributes()['_FillValue'], np.nan, hdf_value)
print("'_FillValue' data is changed to np.nan...\n")
else :
hdf_value = np.where(hdf_value == hdf_value.min(), np.nan, hdf_value)
print("Minium value of hdf data is changed to np.nan ...\n")
if 'valid_range' in hdf_raw.attributes() :
#hdf_value[hdf_value < hdf_raw.attributes()['valid_range'][0]] = np.nan
#hdf_value[hdf_value > hdf_raw.attributes()['valid_range'][1]] = np.nan
hdf_value = np.where(hdf_value < hdf_raw.attributes()['valid_range'][0], np.nan, hdf_value)
hdf_value = np.where(hdf_value > hdf_raw.attributes()['valid_range'][1], np.nan, hdf_value)
print("invalid_range data changed to np.nan...\n")
if 'scale_factor' in hdf_raw.attributes() and 'add_offset' in hdf_raw.attributes() :
scale_factor = hdf_raw.attributes()['scale_factor']
offset = hdf_raw.attributes()['add_offset']
elif 'slope' in hdf_raw.attributes() and 'intercept' in hdf_raw.attributes() :
scale_factor = hdf_raw.attributes()['slope']
offset = hdf_raw.attributes()['intercept']
else :
scale_factor, offset = 1, 0
hdf_value = np.asarray(hdf_value)
hdf_value = hdf_value * scale_factor + offset
#print("latitude: {}".format(latitude))
#print("longitude: {}".format(longitude))
print("hdf_value: {}".format(hdf_value))
print("str(hdf_raw.attributes()): {}".format(str(hdf_raw.attributes())))
print("np.shape(latitude): {}".format(np.shape(latitude)))
print("np.shape(longitude): {}".format(np.shape(longitude)))
print("np.shape(hdf_value): {}".format(np.shape(hdf_value)))
print("len(cntl_pt_cols): {}".format(len(cntl_pt_cols)))
print("len(cntl_pt_rows): {}".format(len(cntl_pt_rows)))
if np.shape(latitude) == np.shape(longitude) :
if np.shape(longitude)[0] != np.shape(hdf_value)[0] :
print("np.shape(longitude)[0] != np.shape(hdf_value)[0] is true...")
row = 0
longitude_new = np.empty(shape=(np.shape(hdf_value)))
for row in range(len(longitude[0])) :
for i in range(len(cntl_pt_rows)-1) :
longitude_value = np.linspace(longitude[row,i], longitude[row,i+1], cntl_pt_rows[i])
for j in range(i) :
longitude_new[row, row+j] = longitude_value[j]
#print("np.shape(longitude_new): {}".format(np.shape(longitude_new)))
longitude = longitude_new.copy()
elif np.shape(longitude)[1] != np.shape(hdf_value)[1] :
print("np.shape(longitude)[1] != np.shape(hdf_value)[1] is true...")
col = 0
longitude_new = np.empty(shape=(np.shape(hdf_value)))
for row in range(len(longitude[1])) :
for i in range(len(cntl_pt_cols)-1) :
longitude_value = np.linspace(longitude[row,i], \
longitude[row,i+1], \
cntl_pt_cols[i+1]-cntl_pt_cols[i]+1)
#print("longitude_value {}: {}".format(i, latitude_value))
#print("{0}, cntl_pt_cols[{1}]-cntl_pt_cols[{0}] : {2})"\
# .format(i, i+1, cntl_pt_cols[i+1]-cntl_pt_cols[i]))
for j in range(len(longitude_value)-1) :
longitude_new[row, cntl_pt_cols[i]-1+j] = longitude_value[j]
longitude_new[row, np.shape(longitude_new)[1]-1] = longitude[row, np.shape(longitude)[1]-1]
#print("np.shape(longitude_new): {}".format(np.shape(longitude_new)))
longitude = longitude_new.copy()
longitude = np.asarray(longitude)
#print("type(longitude): {}".format(type(longitude)))
print("np.shape(longitude): {}".format(np.shape(longitude)))
if np.shape(latitude)[0] != np.shape(hdf_value)[0] :
print("np.shape(latitude)[0] != np.shape(hdf_value)[0] is not same...")
row = 0
latitude_new = np.empty(shape=(np.shape(hdf_value)))
for row in range(len(latitude[0])) :
for i in range(len(cntl_pt_rows)-1) :
latitude_value = np.linspace(latitude[row,i], latitude[row,i+1], cntl_pt_rows[i])
for j in range(i) :
latitude_new[row, row+j] = latitude_value[j]
print("np.shape(latitude_new): {}".format(np.shape(latitude_new)))
latitude = latitude_new.copy()
elif np.shape(latitude)[1] != np.shape(hdf_value)[1] :
print("np.shape(latitude)[1] != np.shape(hdf_value)[1] is true...")
col = 0
latitude_new = np.empty(shape=(np.shape(hdf_value)))
for row in range(len(latitude[1])) :
for i in range(len(cntl_pt_cols)-1) :
latitude_value = np.linspace(latitude[row,i], \
latitude[row,i+1], \
cntl_pt_cols[i+1]-cntl_pt_cols[i]+1)
#print("latitude_value {}: {}".format(i, latitude_value))
#print("{0}, cntl_pt_cols[{1}]-cntl_pt_cols[{0}] : {2})"\
# .format(i, i+1, cntl_pt_cols[i+1]-cntl_pt_cols[i]))
for j in range(len(latitude_value)-1) :
latitude_new[row, cntl_pt_cols[i]-1+j] = latitude_value[j]
latitude_new[row, np.shape(latitude_new)[1]-1] = latitude[row, np.shape(latitude)[1]-1]
print("np.shape(latitude_new): {}".format(np.shape(latitude_new)))
latitude = latitude_new.copy()
latitude = np.asarray(latitude)
#print("type(latitude): {}".format(type(latitude)))
print("np.shape(latitude): {}".format(np.shape(latitude)))
if np.shape(latitude) == np.shape(hdf_value) \
and np.shape(longitude) == np.shape(hdf_value) :
#longitude[longitude < Llon] = np.nan
#longitude[longitude > Rlon] = np.nan
#latitude[latitude > Nlat] = np.nan
#latitude[latitude < Slat] = np.nan
longitude = np.where(longitude < Llon, np.nan, longitude)
longitude = np.where(longitude > Rlon, np.nan, longitude)
latitude = np.where(latitude > Nlat, np.nan, latitude)
latitude = np.where(latitude < Slat, np.nan, latitude)
#lon_cood = np.array((((longitude-Llon)/resolution*100)//100), dtype=np.uint16)
#lat_cood = np.array((((Nlat-latitude)/resolution*100)//100), dtype=np.uint16)
lon_cood = np.array(((longitude-Llon)/resolution*100)//100)
lat_cood = np.array(((Nlat-latitude)/resolution*100)//100)
#print("longitude: {}".format(longitude))
print("np.shape(lon_cood): {}".format(np.shape(lon_cood)))
#print("lon_cood: {}".format(lon_cood))
#print("latitude: {}".format(latitude))
print("np.shape(lat_cood): {}".format(np.shape(lat_cood)))
#print("lat_cood: {}".format(lat_cood))
print("hdf_value: {}".format(hdf_value))
data_cnt = 0
NaN_cnt = 0
for i in range(np.shape(lon_cood)[0]) :
for j in range(np.shape(lon_cood)[1]) :
if longitude[i,j] <= Rlon and longitude[i,j] >= Llon \
and latitude[i,j] <= Nlat and latitude[i,j] >= Slat \
and not np.isnan(hdf_value[i][j]) :
data_cnt += 1
#array_alldata[int(lon_cood[i][j])][int(lat_cood[i][j])].append(hdf_value[i][j])
array_alldata[int(lon_cood[i][j])][int(lat_cood[i][j])].append((fullname_el[-1], hdf_value[i][j]))
#print("array_alldata[{}][{}].append({})"\
# .format(int(lon_cood[i][j]), int(lat_cood[i][j]), hdf_value[i][j]))
#print("{} data added...".format(data_cnt))
file_no += 1
total_data_cnt += data_cnt
processing_log += "{0}, {1}, {2}, {3}\n"\
.format(str(file_no), str(data_cnt), str(fullname), str(hdf_raw.attributes()))
else :
print("np.shape(latitude) == np.shape(hdf_value) and np.shape(longitude == np.shape(hdf_value) is not true...")
processing_log += '#total data number =' + str(total_data_cnt) + '\n'
#print("array_alldata: {}".format(array_alldata))
#print("prodessing_log: {}".format(processing_log))
np.save('{0}{1}_{2}_{3}_{4}_{5}_{6}_{7}_{8}_alldata.npy'\
.format(save_dir_name, DATAFIELD_NAME,
proc_date[0].strftime('%Y%m%d'), proc_date[1].strftime('%Y%m%d'),
str(Llon), str(Rlon), str(Slat), str(Nlat), str(resolution)), array_alldata)
with open('{0}{1}_{2}_{3}_{4}_{5}_{6}_{7}_{8}_info.txt'\
.format(save_dir_name, DATAFIELD_NAME, \
proc_date[0].strftime('%Y%m%d'), proc_date[1].strftime('%Y%m%d'), \
str(Llon), str(Rlon), str(Slat), str(Nlat), str(resolution)), 'w') as f:
f.write(processing_log)
print('#'*60)
MODIS_hdf_utilities.write_log(log_file, \
'{0}{1}_{2}_{3}_{4}_{5}_{6}_{7}_{8} files are is created.'\
.format(save_dir_name, DATAFIELD_NAME, \
proc_date[0].strftime('%Y%m%d'), proc_date[1].strftime('%Y%m%d'), \
str(Llon), str(Rlon), str(Slat), str(Nlat), str(resolution)))
else :
print("There is no data in {0} - {1} ...\n"\
.format(proc_date[0].strftime('%Y%m%d'), proc_date[1].strftime('%Y%m%d')))