IODA Bundle
emc_ice2ioda.py
Go to the documentation of this file.
1 #!/usr/bin/env python3
2 
3 #
4 # (C) Copyright 2019 UCAR
5 #
6 # This software is licensed under the terms of the Apache Licence Version 2.0
7 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
8 #
9 
10 from __future__ import print_function
11 import sys
12 import argparse
13 import netCDF4 as nc
14 from datetime import datetime, timedelta
15 import dateutil.parser
16 import numpy as np
17 from pathlib import Path
18 
19 IODA_CONV_PATH = Path(__file__).parent/"@SCRIPT_LIB_PATH@"
20 if not IODA_CONV_PATH.is_dir():
21  IODA_CONV_PATH = Path(__file__).parent/'..'/'lib-python'
22 sys.path.append(str(IODA_CONV_PATH.resolve()))
23 
24 from orddicts import DefaultOrderedDict
25 import ioda_conv_ncio as iconv
26 
27 
28 class Observation(object):
29 
30  def __init__(self, filename, thin, date, writer):
31  print(date)
32  self.filenamefilename = filename
33  self.thinthin = thin
34  self.datedate = date
35  self.datadata = DefaultOrderedDict(lambda: DefaultOrderedDict(dict))
36  self.writerwriter = writer
37  self._read_read(date)
38 
39  def _read(self, date):
40 
41  ncd = nc.MFDataset(self.filenamefilename)
42  datein = ncd.variables['dtg_yyyymmdd'][:]
43  timein = ncd.variables['dtg_hhmm'][:]
44  lons = ncd.variables['longitude'][:]
45  lats = ncd.variables['latitude'][:]
46  vals = ncd.variables['ice_concentration'][:]
47  qc = ncd.variables['quality'][:]
48  ncd.close()
49 
50  valKey = vName, self.writerwriter.OvalName()
51  errKey = vName, self.writerwriter.OerrName()
52  qcKey = vName, self.writerwriter.OqcName()
53 
54  # apply thinning mask
55  if self.thinthin > 0.0:
56  mask_thin = np.random.uniform(size=len(lons)) > self.thinthin
57  datein = datein[mask_thin]
58  timein = timein[mask_thin]
59  lons = lons[mask_thin]
60  lats = lats[mask_thin]
61  vals = vals[mask_thin]
62  qc = qc[mask_thin]
63 
64  date2 = int(date.strftime("%Y%m%d"))
65  for i in range(len(lons)):
66  if datein[i] == date2:
67  obs_date = datetime.combine(
68  datetime.strptime(
69  np.array2string(
70  datein[i]), "%Y%m%d"), datetime.strptime(
71  np.array2string(
72  timein[i]).zfill(4), "%H%M").time())
73  locKey = lats[i], lons[i], obs_date.strftime("%Y-%m-%dT%H:%M:%SZ")
74  self.datadata[0][locKey][valKey] = vals[i]
75  self.datadata[0][locKey][errKey] = 0.1
76  self.datadata[0][locKey][qcKey] = qc[i]
77 
78 
79 vName = "sea_ice_area_fraction"
80 
81 locationKeyList = [
82  ("latitude", "float"),
83  ("longitude", "float"),
84  ("datetime", "string")
85 ]
86 
87 AttrData = {
88  'odb_version': 1,
89 }
90 
91 
92 def main():
93 
94  parser = argparse.ArgumentParser(
95  description=('')
96  )
97 
98  required = parser.add_argument_group(title='required arguments')
99  required.add_argument(
100  '-i', '--input',
101  help="EMC ice fraction obs input file(s)",
102  type=str, nargs='+', required=True)
103  required.add_argument(
104  '-o', '--output',
105  help="name of ioda output file",
106  type=str, required=True)
107  required.add_argument(
108  '-d', '--date',
109  help="base date for the center of the window",
110  metavar="YYYYMMDDHH", type=str, required=True)
111 
112  optional = parser.add_argument_group(title='optional arguments')
113  optional.add_argument(
114  '-t', '--thin',
115  help="percentage of random thinning, from 0.0 to 1.0. Zero indicates"
116  " no thinning is performed. (default: %(default)s)",
117  type=float, default=0.0)
118 
119  args = parser.parse_args()
120  fdate = datetime.strptime(args.date, '%Y%m%d%H')
121  writer = iconv.NcWriter(args.output, locationKeyList)
122 
123  # Read in
124  ice = Observation(args.input, args.thin, fdate, writer)
125 
126  # write them out
127  AttrData['date_time_string'] = fdate.strftime("%Y-%m-%dT%H:%M:%SZ")
128 
129  (ObsVars, LocMdata, VarMdata) = writer.ExtractObsData(ice.data)
130  writer.BuildNetcdf(ObsVars, LocMdata, VarMdata, AttrData)
131 
132 
133 if __name__ == '__main__':
134  main()
def __init__(self, filename, thin, date, writer)
Definition: emc_ice2ioda.py:30
def _read(self, date)
Definition: emc_ice2ioda.py:39