3 from __future__
import print_function
10 import bufr2ncCommon
as cm
32 Dval = np.ma.array([])
37 if (Dtype == cm.DTYPE_STRING):
51 ByteList = list(struct.unpack(
'8c', Bval))
54 for j
in range(len(ByteList)):
55 ByteVal = struct.unpack(
'@B', ByteList[j])[0]
56 if ((ByteVal < 1)
or (ByteVal > 127)):
59 TempStr = bytes.join(b
'', ByteList).decode(
'ascii')
60 Dval = np.ma.array(TempStr, mask=Bval.mask, dtype=
'S8')
61 elif (Dtype == cm.DTYPE_INTEGER):
63 Dval = np.ma.array(Bval.data.astype(np.int32),
64 mask=Bval.mask, dtype=np.int32)
65 elif (Dtype == cm.DTYPE_FLOAT):
67 Dval = np.ma.array(Bval.data.astype(np.float32),
68 mask=Bval.mask, dtype=np.float32)
69 elif (Dtype == cm.DTYPE_DOUBLE):
71 Dval = np.ma.array(Bval.data.astype(np.float64),
72 mask=Bval.mask, dtype=np.float64)
74 Dval = np.ma.array(Bval.data.astype(np.float32),
75 mask=Bval.mask, dtype=np.float32)
82 def WriteNcVar(Fid, ObsNum, Vname, Vdata, isProfile=False):
86 if ((Vdata.dtype.char ==
'S')
or (Vdata.dtype.char ==
'U')):
87 StrSpec =
"S{0:d}".format(cm.MAX_STRING_LEN)
88 Value = netCDF4.stringtochar(Vdata.astype(StrSpec))
137 if Value.shape == ():
138 NcVar[ObsNum] = Value
140 NcVar[ObsNum:ObsNum+Value.shape[0]] = Value
142 NcVar[ObsNum] = Value
147 NcVar[ObsNum, 0] = Value
153 if len(Value.shape) == 1:
154 NcVar[ObsNum, 0:N1] = Value[0:N1]
156 for i
in range(Value.shape[0]):
157 NcVar[(ObsNum+i), 0:N1] = Value[0:N1]
159 N1 = min(Value.shape[0], NcVar.shape[1])
161 NcVar[ObsNum, 0:N1] = Value[0:N1]
166 N2 = min(Value.shape[0], NcVar.shape[2])
167 NcVar[ObsNum, 0, 0:N2] = Value[0:N2]
171 N1 = min(Value.shape[0], NcVar.shape[1])
172 N2 = min(Value.shape[1], NcVar.shape[2])
173 NcVar[ObsNum, 0:N1, 0:N2] = Value[0:N1, 0:N2]
179 N2 = min(Value.shape[0], NcVar.shape[2])
180 N3 = min(Value.shape[1], NcVar.shape[3])
181 NcVar[ObsNum, 0, 0:N2, 0:N3] = Value[0:N2, 0:N3]
185 N1 = min(Value.shape[0], NcVar.shape[1])
186 N2 = min(Value.shape[1], NcVar.shape[2])
187 N3 = min(Value.shape[2], NcVar.shape[3])
188 NcVar[ObsNum, 0:N1, 0:N2, 0:N3] = Value[0:N1, 0:N2, 0:N3]
257 [[
'msg_type@MetaData',
'', cm.DTYPE_STRING, [
'nlocs',
'nstring'], [self.
nlocsnlocs, self.
nstringnstring]],
258 [
'msg_date@MetaData',
'', cm.DTYPE_UINT, [
'nlocs'], [self.
nlocsnlocs]]]
270 self.
nlocsnlocs = nlocs
282 for sub_slist
in slist:
283 for var_spec
in sub_slist:
284 for i
in [j
for j, dname
in enumerate(
285 var_spec[3])
if dname ==
'nlocs']:
286 var_spec[4][i] = self.
nlocsnlocs
295 return bufr._subsets()
303 AllDimNames = set([])
306 for sub_slist
in slist:
307 for var_spec
in sub_slist:
309 AllDimNames = AllDimNames | set(var_spec[3])
315 for dname
in AllDimNames:
316 if (dname ==
'nlocs'):
317 dsize = self.
nlocsnlocs
318 elif (dname ==
'nlevs'):
319 dsize = self.
nlevsnlevs
320 elif (dname ==
'nevents'):
322 elif (dname ==
'nstring'):
324 elif (dname ==
'nchans'):
326 elif (dname ==
'nrecs'):
327 dsize = self.
nrecsnrecs
328 elif (dname ==
'nvars'):
329 dsize = self.
nvarsnvars
332 "ERROR: init_dim_spec: Unknown dimension name: {0:s}".format(dname))
334 DimList.append([dname, dname, cm.DTYPE_UINT, [dname], [dsize]])
344 nc.createDimension(
'nrecs', self.
nrecsnrecs)
345 nc.createDimension(
'nvars', self.
nvarsnvars)
346 for sub_slist
in self.
dim_specdim_spec:
347 for dspec
in sub_slist:
349 if dspec[0] ==
"nlocs":
350 nc.createDimension(dspec[0], 0)
352 nc.createDimension(dspec[0], dspec[4][0])
354 nc.createDimension(dspec[0], dspec[4][0])
358 for sub_slist
in slist:
359 for var_spec
in sub_slist:
362 DimNames = var_spec[3]
363 DimSizes = var_spec[4]
366 if (Dtype == cm.DTYPE_STRING):
368 elif (Dtype == cm.DTYPE_INTEGER):
370 elif (Dtype == cm.DTYPE_UINT):
372 elif (Dtype == cm.DTYPE_FLOAT):
374 elif (Dtype == cm.DTYPE_DOUBLE):
379 nc.createVariable(Vname, Vtype, DimNames, zlib=
True,
380 shuffle=
True, complevel=6)
386 for DimSpecs
in self.
dim_specdim_spec:
387 for VarSpec
in DimSpecs:
389 Value = np.arange(VarSpec[4][0]) + 1
396 Sflag=False, Eflag=False):
401 for MnemonicList
in Mlists:
402 Mstring =
" ".join(MnemonicList)
403 BufrValues.append(bufr.read_subset(
404 Mstring, events=Eflag, seq=Sflag, rep=Rflag))
414 OutVals = {key: value
for key, value
in ActualValues.items()}
415 OutValsBufr = {key: value
for key, value
in ActualValues.items()}
416 for SubSpecs, SubBvals
in zip(SpecList, BufrValues):
417 for VarSpec, Bval
in zip(SubSpecs, SubBvals):
421 if (VarSpec[1] !=
'RRSTG'):
426 return [OutVals, OutValsBufr]
433 self, SpecList, BufrValues, ActualValues, ActualValuesBufr):
435 OutVals = {key: value
for key, value
in ActualValues.items()}
436 OutValsBufr = {key: value
for key, value
in ActualValuesBufr.items()}
437 for SubSpecs, SubBvals
in zip(SpecList, BufrValues):
438 for VarSpec, Bval
in zip(SubSpecs, SubBvals):
442 if (VarSpec[1] !=
'RRSTG'):
446 return [OutVals, OutValsBufr]
466 ActualValues.append({})
467 ActualValuesBufr = []
468 ActualValuesBufr.append({})
472 Mlists = [[Mlist[1]
for Mlist
in SubList]
for SubList
in self.
int_specint_spec]
476 ActualValues[0], ActualValuesBufr[0])
479 Mlists = [[Mlist[1]
for Mlist
in SubList]
for SubList
in self.
evn_specevn_spec]
480 BufrValues = self.
read_bufr_dataread_bufr_data(bufr, Mlists, Eflag=
True)
483 ActualValues[0], ActualValuesBufr[0])
486 Mlists = [[Mlist[1]
for Mlist
in SubList]
for SubList
in self.
rep_specrep_spec]
487 BufrValues = self.
read_bufr_dataread_bufr_data(bufr, Mlists, Rflag=
True)
490 ActualValues[0], ActualValuesBufr[0])
493 Mlists = [[Mlist[1]
for Mlist
in SubList]
for SubList
in self.
seq_specseq_spec]
494 BufrValues = self.
read_bufr_dataread_bufr_data(bufr, Mlists, Sflag=
True)
497 ActualValues[0], ActualValuesBufr[0])
499 return [ActualValues, ActualValuesBufr]
522 Year =
int(ActualValues[
'YEAR'].data)
523 Month =
int(ActualValues[
'MNTH'].data)
524 Day =
int(ActualValues[
'DAYS'].data)
525 Hour =
int(ActualValues[
'HOUR'].data)
526 Minute =
int(ActualValues[
'MINU'].data)
527 if (
'SECO' in ActualValues):
529 Second =
int(ActualValues[
'SECO'].data)
539 ObsDtime = dt.datetime(
540 Year, Month, Day, Hour, Minute) + dt.timedelta(seconds=Second)
541 DateTime = np.array(ObsDtime.strftime(
"%Y-%m-%dT%H:%M:%SZ"))
560 while (bufr.advance() == 0):
562 if (re.search(self.
mtype_remtype_re, bufr.msg_type)):
578 Select = Select
and (
605 print(
"Converting BUFR to netcdf:")
610 MsgType = np.ma.array(bufr.msg_type)
611 MsgDate = np.ma.array([bufr.msg_date])
612 while (bufr.load_subset() == 0):
619 [ActualValues, ActualValuesBufr] = self.
extract_bufrextract_bufr(bufr)
622 for k
in ActualValues[0].keys():
623 if len(ActualValues[0][k].shape) >= 1
and \
624 ActualValues[0][k].shape[0] > maxLength:
625 maxLength = ActualValues[0][k].shape[0]
627 for i
in range(len(ActualValues)):
630 ActualValues[i][
'msg_type@MetaData'] = MsgType
631 ActualValues[i][
'msg_date@MetaData'] = MsgDate
632 [ActualValues[i][
'datetime@MetaData']] = self.
calc_obs_date_timecalc_obs_date_time(ActualValuesBufr[i])
636 for Vname, Vdata
in ActualValues[i].items():
638 if Vdata.shape == ():
640 Vdata = np.ma.array(maxLength*[Vdata],
644 Vdata = Vdata.squeeze()
647 WriteNcVar(nc, ObsNum, Vname, Vdata, isProfile)
655 if ((ObsNum % 100) == 0):
656 print(
" Converted {0:d} observations".format(ObsNum))
660 if (self.
bufr_ftypebufr_ftype == cm.BFILE_PREPBUFR):
661 nc.virtmp_code = bufr.get_program_code(
'VIRTMP')
664 print(
" Total converted observations: ", ObsNum)
def bufr_float_to_actual_bufr(self, SpecList, BufrValues, ActualValues, ActualValuesBufr)
This method will convert bufr float data to the specified actual format.
def convert(self, bufr, nc, isProfile=False)
This method will convert the BUFR data into netcdf data.
def msg_obs_count(self, bufr)
This method is a default routine for counting the number of observations in the current BUFR message.
def extract_bufr(self, bufr)
This method will take the four input spec lists and read the mnemonics from the bufr file.
def fill_coords(self, nc)
This method will fill in the dimension variables with coordinate values.
def set_nlocs(self, nlocs)
This method will set the number of observations.
def init_dim_spec(self)
This method will set the dimension specs (data memeber self.dim_spec).
def start_msg_selector(self)
This method will start the message selector.
def select_next_msg(self, bufr)
This method is the message selector.
def read_bufr_data(self, bufr, Mlists, Rflag=False, Sflag=False, Eflag=False)
This method will read in a list of bufr mnemonics and return a list of the corresponding data values.
def bufr_float_to_actual(self, SpecList, BufrValues, ActualValues)
This method will convert bufr float data to the specified actual format.
def create_nc_datasets(self, nc, isProfile=False)
This method will create dimensions and variables in the netcdf file according to the obs type variabl...
def calc_obs_date_time(self, ActualValues)
This method will calculate the absolute date and time values from the BUFR mnemonic values.
def BufrFloatToActual(Bval, Dtype)
SUBROUTINES.
def WriteNcVar(Fid, ObsNum, Vname, Vdata, isProfile=False)