IODA Bundle
cryosat_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 import subprocess
18 import os
19 from pathlib import Path
20 
21 IODA_CONV_PATH = Path(__file__).parent/"@SCRIPT_LIB_PATH@"
22 if not IODA_CONV_PATH.is_dir():
23  IODA_CONV_PATH = Path(__file__).parent/'..'/'lib-python'
24 sys.path.append(str(IODA_CONV_PATH.resolve()))
25 
26 from orddicts import DefaultOrderedDict
27 import ioda_conv_ncio as iconv
28 
29 
30 class Observation(object):
31 
32  def __init__(self, filename, thin, date, writer):
33  print(date)
34 
35  if os.path.exists("cryosat_nc4classic.nc"):
36  os.remove("cryosat_nc4classic.nc")
37 
38  self.filenamesfilenames = filename
39  self.thinthin = thin
40  self.datedate = date
41  self.datadata = DefaultOrderedDict(lambda: DefaultOrderedDict(dict))
42  self.writerwriter = writer
43  self._read_read()
44 
45  def _read(self):
46  valKey = vName, self.writerwriter.OvalName()
47  errKey = vName, self.writerwriter.OerrName()
48  qcKey = vName, self.writerwriter.OqcName()
49 
50  for f in self.filenamesfilenames:
51  print(f)
52  subprocess.call('nccopy -k nc7 '+f+' cryosat_nc4classic.nc', shell=True)
53  self.filenamefilename = "cryosat_nc4classic.nc"
54  ncd = nc.MFDataset(self.filenamefilename, aggdim='time_20_ku')
55  time = ncd.variables['time_20_ku'][:]
56  lons = ncd.variables['lon_poca_20_ku'][:]
57  lats = ncd.variables['lat_poca_20_ku'][:]
58  vals = ncd.variables['freeboard_20_ku'][:]
59  qc = ncd.variables['flag_prod_status_20_ku'][:]
60  # get base date for file
61  s = ' '.join(ncd.variables['time_20_ku'].units.split(' ')[2:3])
62  reftime = dateutil.parser.parse(s)
63  ncd.close()
64 
65  # apply thinning mask
66  if self.thinthin > 0.0:
67  mask_thin = np.random.uniform(size=len(lons)) > self.thinthin
68  datein = datein[mask_thin]
69  timein = timein[mask_thin]
70  lons = lons[mask_thin]
71  lats = lats[mask_thin]
72  vals = vals[mask_thin]
73  qc = qc[mask_thin]
74 
75  for i in range(len(lons)):
76  obs_date = reftime + timedelta(seconds=float(time[i]))
77  locKey = lats[i], lons[i], obs_date.strftime("%Y-%m-%dT%H:%M:%SZ")
78  self.datadata[0][locKey][valKey] = vals[i]
79  self.datadata[0][locKey][errKey] = 0.1
80  self.datadata[0][locKey][qcKey] = qc[i]
81 
82  os.remove("cryosat_nc4classic.nc")
83 
84 
85 vName = "sea_ice_freeboard"
86 
87 locationKeyList = [
88  ("latitude", "float"),
89  ("longitude", "float"),
90  ("datetime", "string")
91 ]
92 
93 AttrData = {
94  'odb_version': 1,
95 }
96 
97 
98 def main():
99 
100  parser = argparse.ArgumentParser(
101  description=('Reads ESA Cryosat-2 Ice and converts into IODA NetCDF')
102  )
103 
104  required = parser.add_argument_group(title='required arguments')
105  required.add_argument(
106  '-i', '--input',
107  help="Cryosat-2 ice freeboard obs input file(s)",
108  type=str, nargs='+', required=True)
109  required.add_argument(
110  '-o', '--output',
111  help="name of ioda output file",
112  type=str, required=True)
113  required.add_argument(
114  '-d', '--date',
115  help="base date for the center of the window",
116  metavar="YYYYMMDDHH", type=str, required=True)
117 
118  optional = parser.add_argument_group(title='optional arguments')
119  optional.add_argument(
120  '-t', '--thin',
121  help="percentage of random thinning, from 0.0 to 1.0. Zero indicates"
122  " no thinning is performed. (default: %(default)s)",
123  type=float, default=0.0)
124 
125  args = parser.parse_args()
126  fdate = datetime.strptime(args.date, '%Y%m%d%H')
127  writer = iconv.NcWriter(args.output, locationKeyList)
128 
129  # Read in
130  ice = Observation(args.input, args.thin, fdate, writer)
131 
132  # write them out
133  AttrData['date_time_string'] = fdate.strftime("%Y-%m-%dT%H:%M:%SZ")
134 
135  (ObsVars, LocMdata, VarMdata) = writer.ExtractObsData(ice.data)
136  writer.BuildNetcdf(ObsVars, LocMdata, VarMdata, AttrData)
137 
138 
139 if __name__ == '__main__':
140  main()
def __init__(self, filename, thin, date, writer)