FV3 Bundle
QGFdb.py
Go to the documentation of this file.
1 # (C) Copyright 2009-2016 ECMWF.
2 #
3 # This software is licensed under the terms of the Apache Licence Version 2.0
4 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
5 # In applying this licence, ECMWF does not waive the privileges and immunities
6 # granted to it by virtue of its status as an intergovernmental organisation nor
7 # does it submit to any jurisdiction.
8 
9 #===============================================================================
10 # QG0db
11 #
12 # A class to handle the observations used in QG model
13 #===============================================================================
14 import numpy as np
15 from dateutil import parser
16 from datetime import tzinfo, timedelta, datetime
17 import glob
18 import os
19 import re
20 import os.path
21 
22 class QGFdb:
23 
24  #=============================================================================
25  # Construct the fdb object, read the filenames and store them in a map
26  #=============================================================================
27  def __init__(self, fdbdir):
28  self.fdbdir = fdbdir
29  self.map = {}
30  l = glob.glob(fdbdir + '/*.*.*')
31  for i in l:
32  file = {}
33  filenameSplitted = os.path.split(i)[1].split('.')
34  if len(filenameSplitted[2]) < 10:
35  continue
36  if i.find(".obt") != -1:
37  continue
38  file["expe"] = filenameSplitted[0]
39  file["type"] = filenameSplitted[1]
40  file["referenceTime"] = filenameSplitted[2]
41  file["refTime"] = parser.parse(filenameSplitted[2])
42  try:
43  term = self.getTerm(filenameSplitted[3])
44  file["term"] = filenameSplitted[3]
45  file["intTerm"] = term
46  file["validTime"] = file["refTime"] + term
47 
48  except:
49  file["intTerm"] = timedelta(seconds=0)
50  file["validTime"] = file["refTime"]
51  file["term"] = None
52  file["filename"] = os.path.split(i)[1]
53  self.map[os.path.split(i)[1]] = file
54 
55  #=============================================================================
56  # getAtValidTime
57  #=============================================================================
58  def getAtValidTime(self, date):
59  ret = []
60  for file in self.map.values():
61  if file["validTime"] == date :
62  ret.append(file)
63  return ret
64 
65  #=============================================================================
66  # ggetAtValidTime
67  #=============================================================================
68  def ggetAtValidTime(self, stringdate):
69  date = parser.parse(stringdate)
70  return self.getAtValidTime(date)
71 
72  #=============================================================================
73  # getData
74  #=============================================================================
75  def getData(self, file):
76  if "psi" in file:
77  psi = file["psi"]
78  pv = file["pv"]
79  else:
80  infile = open(self.fdbdir + "/" + file["filename"], "r")
81 
82  [nx, ny, nl, nf, ns] = [int(i) for i in infile.readline().split()]
83  validity_date = infile.readline()
84  psi = np.fromfile(file=infile,dtype="float64", \
85  count=(2*ny*nx),sep=" ").reshape((2,ny,nx))
86  pv = np.fromfile(file=infile,dtype="float64", \
87  count=(2*ny*nx),sep=" ").reshape((2,ny,nx))
88  infile.close()
89 
90  file["psi"] = psi
91  file["pv"] = pv
92 
93  ret = {}
94  ret['pv'] = pv
95  ret['psi'] = psi
96  return ret
97 
98  #=============================================================================
99  # getMetaData
100  #=============================================================================
101  def getMetaData(self):
102  lst = {}
103  for f in self.map.values():
104  key = f["expe"] + "." + f["type"]
105  if key in lst:
106  arr = lst[key]
107  else:
108  arr = {}
109  lst[key] = arr
110  if f["referenceTime"] in arr:
111  terms = arr[f["referenceTime"]]
112  else:
113  terms = {}
114  arr[f["referenceTime"]] = terms
115  terms[f["intTerm"]] = f["term"]
116  for expe in lst.keys():
117  for date in lst[expe].keys():
118  t = lst[expe][date];
119  k = t.keys()
120  k.sort()
121  newT = []
122  for i in k:
123  newT.append(t[i])
124  lst[expe][date] = newT
125 
126  return lst
127 
128  #=============================================================================
129  # getTimeList
130  #=============================================================================
131  def getTimeList(self, expe):
132  lst = []
133  items = {}
134  for f in self.map.values():
135  key = f["expe"] + "." + f["type"]
136  if key == expe:
137  items[f['refTime']] = f['referenceTime']
138  k = items.keys()
139  k.sort()
140  for i in k:
141  lst.append(items[i])
142  return lst
143 
144  #=============================================================================
145  # getExpeAt
146  #=============================================================================
147  def getExpeAt(self, expe, refTime, validTime):
148  file = None
149  for f in self.map.values():
150  key = f["expe"] + "." + f["type"]
151  if expe == key and refTime == f['refTime'] and validTime == f['validTime'] :
152  file = f
153  return file
154 
155  #=============================================================================
156  # printMetaData
157  #=============================================================================
158  def printMetaData(self):
159  lst = self.getMetaData()
160  for expe in lst.keys():
161  print expe
162  for date in lst[expe].keys():
163  print "-- ", date
164  if len(lst[expe][date]) > 1:
165  for ech in lst[expe][date]:
166  print "---- ", ech
167 
168 
169 
170  #=============================================================================
171  # getTerm
172  #=============================================================================
173  def getTerm(self, term):
174  regex = re.compile('(?P<sign>-?)P(?:(?P<years>\d+)Y)?(?:(?P<months>\d+)M)?(?:(?P<days>\d+)D)?(?:T(?:(?P<hours>\d+)H)?(?:(?P<minutes>\d+)M)?(?:(?P<seconds>\d+)S)?)?')
175  duration = regex.match(term).groupdict(0)
176  delta = timedelta(days=int(duration['days']) + (int(duration['months']) * 30) + (int(duration['years']) * 365),
177  hours=int(duration['hours']),
178  minutes=int(duration['minutes']),
179  seconds=int(duration['seconds']))
180  return delta
181 
def getAtValidTime(self, date)
Definition: QGFdb.py:58
def getTerm(self, term)
Definition: QGFdb.py:173
def getMetaData(self)
Definition: QGFdb.py:101
def ggetAtValidTime(self, stringdate)
Definition: QGFdb.py:68
def getData(self, file)
Definition: QGFdb.py:75
def printMetaData(self)
Definition: QGFdb.py:158
def getTimeList(self, expe)
Definition: QGFdb.py:131
def __init__(self, fdbdir)
Definition: QGFdb.py:27
def getExpeAt(self, expe, refTime, validTime)
Definition: QGFdb.py:147