FV3 Bundle
L95Fdb.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 # L950db
11 #
12 # A class to handle the observations used in L95 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 L95Fdb:
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 
54  if file["term"] is None:
55  key = file["expe"]+"."+file["type"]+"."+file["referenceTime"]
56  else:
57  key = file["expe"]+"."+file["type"]+"."+file["referenceTime"]+"."+file["term"]
58  self.map[key] = file
59 
60  #=============================================================================
61  # getAtValidTime
62  #=============================================================================
63  def getAtValidTime(self, date):
64  ret = []
65  for file in self.map.values():
66  if file["validTime"] == date :
67  ret.append(file)
68  return ret
69 
70  #=============================================================================
71  # ggetAtValidTime
72  #=============================================================================
73  def ggetAtValidTime(self, stringdate):
74  date = parser.parse(stringdate)
75  return self.getAtValidTime(date)
76 
77  #=============================================================================
78  # getData
79  #=============================================================================
80  def getData(self, file):
81  if "data" in file:
82  d = file["data"]
83  else:
84  infile = open(self.fdbdir + "/" + file["filename"], "r")
85  n = infile.readline()
86  validity_date = infile.readline()
87  d = np.fromfile(file=infile, dtype="float64", \
88  count=int(n), sep=" ")
89  infile.close()
90  file["data"] = d
91  return d
92 
93  #=============================================================================
94  # getMetaData
95  #=============================================================================
96  def getMetaData(self):
97  lst = {}
98  for f in self.map.values():
99  key = f["expe"] + "." + f["type"]
100  if key in lst:
101  arr = lst[key]
102  else:
103  arr = {}
104  lst[key] = arr
105  if f["referenceTime"] in arr:
106  terms = arr[f["referenceTime"]]
107  else:
108  terms = {}
109  arr[f["referenceTime"]] = terms
110  terms[f["intTerm"]] = f["term"]
111  for expe in lst.keys():
112  for date in lst[expe].keys():
113  t = lst[expe][date];
114  k = t.keys()
115  k.sort()
116  newT = []
117  for i in k:
118  newT.append(t[i])
119  lst[expe][date] = newT
120 
121  return lst
122 
123  #=============================================================================
124  # getTimeList
125  #=============================================================================
126  def getTimeList(self, expe):
127  lst = []
128  items = {}
129  for f in self.map.values():
130  key = f["expe"] + "." + f["type"]
131  if key == expe:
132  items[f['refTime']] = f['referenceTime']
133  k = items.keys()
134  k.sort()
135  for i in k:
136  lst.append(items[i])
137  return lst
138 
139  #=============================================================================
140  # getExpeAt
141  #=============================================================================
142  def getExpeAt(self, expe, refTime, validTime):
143  file = None
144  for f in self.map.values():
145  key = f["expe"] + "." + f["type"]
146  if expe == key and refTime == f['refTime'] and validTime == f['validTime'] :
147  file = f
148  return file
149 
150  #=============================================================================
151  # printMetaData
152  #=============================================================================
153  def printMetaData(self):
154  lst = self.getMetaData()
155  for expe in lst.keys():
156  print expe
157  for date in lst[expe].keys():
158  print "-- ", date
159  if len(lst[expe][date]) > 1:
160  for ech in lst[expe][date]:
161  print "---- ", ech
162 
163 
164 
165  #=============================================================================
166  # getTerm
167  #=============================================================================
168  def getTerm(self, term):
169  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)?)?')
170  duration = regex.match(term).groupdict(0)
171  delta = timedelta(days=int(duration['days']) + (int(duration['months']) * 30) + (int(duration['years']) * 365),
172  hours=int(duration['hours']),
173  minutes=int(duration['minutes']),
174  seconds=int(duration['seconds']))
175  return delta
176 
def getTimeList(self, expe)
Definition: L95Fdb.py:126
def getAtValidTime(self, date)
Definition: L95Fdb.py:63
def __init__(self, fdbdir)
Definition: L95Fdb.py:27
def getExpeAt(self, expe, refTime, validTime)
Definition: L95Fdb.py:142
def printMetaData(self)
Definition: L95Fdb.py:153
def getMetaData(self)
Definition: L95Fdb.py:96
def ggetAtValidTime(self, stringdate)
Definition: L95Fdb.py:73
def getTerm(self, term)
Definition: L95Fdb.py:168
def getData(self, file)
Definition: L95Fdb.py:80