5 from netCDF4
import Dataset
as NC
9 from datetime
import datetime
10 from datetime
import datetime, timedelta
18 __version__ =
"1.0 2024-05-20"
32 SDC.FLOAT32: np.float32,
46 print(f
"l1aconvert_czcs {__version__}")
51 parser = argparse.ArgumentParser(description=
"Given a HDF4 Scientific Dataset (SD), convert it into NetCDF format with the same name.")
54 parser.add_argument(
"iFile", type=str, help=
"HDF4 file")
55 parser.add_argument(
"oFile", nargs=
'?', type=str, help=
"Optional Output file name")
59 args = parser.parse_args()
61 oFileName = fileName +
".nc" if args.oFile
is None else args.oFile
63 print(f
"\nInput file:\t{fileName}")
64 print(f
"Output file:\t{oFileName}\n")
68 hdfFile = HDF(fileName, HDF_MODE)
69 print(f
"Opening file:\t{fileName}")
71 print(f
"\n-E- Error opening file named: {fileName}.\n Make sure the filetype is hdf4.\n")
76 ncFile =
NC(oFileName, NC_MODE, NC_FORMAT)
92 print(
"Closing HDF4 File...")
94 print(
"Closing NetCDF File...")
105 return "vector_elements"
106 elif (string ==
"6"):
107 return "calibration_elements"
108 return string.lower().replace(
" ",
"_")
122 "Pixel per Scan Line",
123 "Number of Scan Lines",
124 "Number of Pixel Control Points",
125 "Number of Scan Control Points",
136 "Calibration Intercept",
141 print(
"Copying global attributes...")
143 gloablAttr = hdfFile.attributes()
145 for name, val
in gloablAttr.items():
154 if (isinstance(val, str)):
159 val = np.float32(val)
if isinstance(val, float)
else np.int32(val)
165 errorAt =
"time_coverage_start"
166 year = gloablAttr.get(
"Start Year")
167 day = gloablAttr.get(
"Start Day")
168 msec = gloablAttr.get(
"Start Millisec")
170 start_of_year = datetime(year, 1, 1)
171 time = start_of_year + timedelta(days=(day-1), seconds=(msec/1000))
173 ncFile.setncattr(
"time_coverage_start",
str(time.isoformat()))
176 errorAt =
"time_coverage_end"
177 year = gloablAttr.get(
"End Year")
178 day = gloablAttr.get(
"End Day")
179 msec = gloablAttr.get(
"End Millisec")
181 start_of_year = datetime(year, 1, 1)
182 time = start_of_year + timedelta(days=(day-1), seconds=(msec/1000))
184 ncFile.setncattr(
"time_coverage_end",
str(time.isoformat()))
188 ncFile.setncattr(
"history", f
"python3 l1acovert_czcs {iFile} {oFile}")
191 ncFile.setncattr(
"l1aconvert_czcs_version", __version__)
195 print(f
"-E- Error copying global attributes. Was processing <{errorAt}> from HDF4 when error was caught.")
210 print(
"Copying dimensions...")
214 ncFile.createDimension(
"calibration_elements", 6)
215 ncFile.createDimension(
"vector_elements", 3)
218 ncFile.createDimension(
"num_qual", 5)
219 ncFile.createDimension(
"number_of_bands", 6)
222 errorAt =
"Number of Scan Lines & Pixel per Scan Line"
223 currSet = hdfFile.select(
"band1")
224 dims = currSet.dimensions()
225 ncFile.createDimension(
"number_of_scan_lines", dims[
"Number of Scan Lines"])
226 ncFile.createDimension(
"pixels_per_scan_line", dims[
"Pixels per Scan Line"])
230 errorAt =
"Number of Pixel Control Points"
231 currSet = hdfFile.select(
"cntl_pt_cols")
232 dims = currSet.dimensions()
233 ncFile.createDimension(
"number_of_pixel_control_points", dims[
"Number of Pixel Control Points"])
237 print(f
"-E- Error copying dimensions. Was trying to copy the dimension(s) <{errorAt}> when error was caught.")
250 for attr
in attrDict.keys():
251 if (attr ==
"long_name"):
252 ncVar.long_name = attrDict.get(attr)
253 if (attr ==
"units"):
254 ncVar.units = attrDict.get(attr)
257 if (attr ==
"valid range" or attr ==
"valid_range"):
261 validRange = attrDict.get(attr)[1:-2].split(
",")
264 if (dataType == np.float32):
265 ncVar.valid_min = np.float32(validRange[0])
266 ncVar.valid_max = np.float32(validRange[1])
267 elif (dataType == np.uint8):
268 ncVar.valid_min = np.uint8(validRange[0])
269 ncVar.valid_max = np.uint8(validRange[1])
270 elif (dataType == np.int16):
271 ncVar.valid_min = np.int16(validRange[0])
272 ncVar.valid_max = np.int16(validRange[1])
274 ncVar.valid_min = np.int32(validRange[0])
275 ncVar.valid_max = np.int32(validRange[1])
287 print(
"Copying datasets/variables...")
289 datasetNames = hdfFile.datasets().keys()
290 for name
in datasetNames:
293 currSet = hdfFile.select(name)
294 hdfDataType = currSet.info()[3];
295 hdfDims = currSet.dimensions().keys()
296 setAttrs = currSet.attributes()
298 hdfDatasetAttr = currSet.attributes()
301 ncDatatype = GET_NC_TYPES.get(hdfDataType)
303 newVariable = ncFile.createVariable(name, ncDatatype, ncDims)
304 newVariable[:] = data
312 print(f
"-E- Error copying datasets/variables. Error occured with HDF4 dataset named <{errorAt}>")
317 if __name__ ==
'__main__':