source: flex_extract.git/python/GribTools.py @ 02c8c50

ctbtodev
Last change on this file since 02c8c50 was 02c8c50, checked in by Anne Philipp <bscannephilipp@…>, 6 years ago

more changes in PEP8 style and slight modifications in coding style and naming. More documentation of functions.

  • Property mode set to 100644
File size: 9.9 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3#************************************************************************
4# TODO AP
5#AP
6# - GribTools name möglicherweise etwas verwirrend.
7# - change self.filename in self.filenames!!!
8# -
9#************************************************************************
10"""
11@Author: Anne Fouilloux (University of Oslo)
12
13@Date: July 2014
14
15@ChangeHistory:
16   February 2018 - Anne Philipp (University of Vienna):
17        - applied PEP8 style guide
18        - added documentation
19        - changed some naming
20
21@License:
22    (C) Copyright 2014 UIO.
23
24    This software is licensed under the terms of the Apache Licence Version 2.0
25    which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
26
27@Requirements:
28    - A standard python 2.6 or 2.7 installation
29    - dateutils
30    - matplotlib (optional, for debugging)
31    - ECMWF specific packages, all available from https://software.ecmwf.int/
32        ECMWF WebMARS, gribAPI with python enabled, emoslib and
33        ecaccess web toolkit
34
35@Description:
36    Further documentation may be obtained from www.flexpart.eu.
37
38    Functionality provided:
39        Prepare input 3D-wind fields in hybrid coordinates +
40        surface fields for FLEXPART runs
41"""
42# ------------------------------------------------------------------------------
43# MODULES
44# ------------------------------------------------------------------------------
45from gribapi import *
46import traceback
47import sys, os
48
49# ------------------------------------------------------------------------------
50# CLASS
51# ------------------------------------------------------------------------------
52class GribTools:
53    '''
54    Class for GRIB utilities (new methods) based on GRIB API
55    '''
56    # --------------------------------------------------------------------------
57    # FUNCTIONS
58    # --------------------------------------------------------------------------
59    def __init__(self, filenames):
60        '''
61        @Description:
62            Initialise an object of GribTools and assign a list
63            of filenames.
64
65        @Input:
66            filenames: list of strings
67                A list of filenames.
68
69        @Return:
70            <nothing>
71        '''
72
73        self.filename = filenames
74
75        return
76
77
78    def getkeys(self, keynames, wherekeynames=[], wherekeyvalues=[]):
79        '''
80        @Description:
81            get keyvalues for a given list of keynames
82            a where statement can be given (list of key and list of values)
83
84        @Input:
85            keynames: list of strings
86                List of keynames.
87
88            wherekeynames: list of ???, optional
89                Default value is an empty list.
90
91            wherekeyvalues: list of ???, optional
92                Default value is an empty list.
93
94        @Return:
95            return_list: list of strings
96                List of keyvalues for given keynames.
97        '''
98
99        fileid = open(self.filename, 'r')
100
101        return_list = []
102
103        while 1:
104            gid_in = grib_new_from_file(fileid)
105
106            if gid_in is None:
107                break
108
109            if len(wherekeynames) != len(wherekeyvalues):
110                raise Exception("Number of key values and key names must be \
111                                 the same. Give a value for each keyname!")
112
113            select = True
114            i = 0
115            for wherekey in wherekeynames:
116                if not grib_is_defined(gid_in, wherekey):
117                    raise Exception("where key was not defined")
118
119                select = (select and (str(wherekeyvalues[i]) ==
120                                      str(grib_get(gid_in, wherekey))))
121                i += 1
122
123            if select:
124                llist = []
125                for key in keynames:
126                    llist.extend([str(grib_get(gid_in, key))])
127                return_list.append(llist)
128
129            grib_release(gid_in)
130
131        fileid.close()
132
133        return return_list
134
135
136    def setkeys(self, fromfile, keynames, keyvalues, wherekeynames=[],
137                wherekeyvalues=[], strict=False, filemode='w'):
138        '''
139        @Description:
140            Opens the file to read the grib messages and then write
141            them to a new output file. By default all messages are
142            written out. Also, the keyvalues of the passed list of
143            keynames are set or only those meeting the where statement.
144            (list of key and list of values).
145
146        @Input:
147            fromfile: string
148                Filename of the input file to read the grib messages from.
149
150            keynames: list of ???
151                List of keynames. Default is an empty list.
152
153            keyvalues: list of ???
154                List of keynames. Default is an empty list.
155
156            wherekeynames: list of ???, optional
157                Default value is an empty list.
158
159            wherekeyvalues: list of ???, optional
160                Default value is an empty list.
161
162            strict: boolean, optional
163                Decides if everything from keynames and keyvalues
164                is written out the grib file (False) or only those
165                meeting the where statement (True). Default is False.
166
167            filemode: string, optional
168                Sets the mode for the output file. Default is "w".
169
170        @Return:
171            <nothing>
172
173        '''
174        fout = open(self.filename, filemode)
175        fin = open(fromfile)
176
177        while 1:
178            gid_in = grib_new_from_file(fin)
179
180            if gid_in is None:
181                break
182
183            if len(wherekeynames) != len(wherekeyvalues):
184                raise Exception("Give a value for each keyname!")
185
186            select = True
187            i = 0
188            for wherekey in wherekeynames:
189                if not grib_is_defined(gid_in, wherekey):
190                    raise Exception("where Key was not defined")
191
192                select = (select and (str(wherekeyvalues[i]) ==
193                                      str(grib_get(gid_in, wherekey))))
194                i += 1
195
196#AP is it secured that the order of keynames is equal to keyvalues?
197            if select:
198                i = 0
199                for key in keynames:
200                    grib_set(gid_in, key, keyvalues[i])
201                    i += 1
202
203#AP this is a redundant code section
204# delete the if/else :
205#
206#           grib_write(gid_in, fout)
207#
208            if strict:
209                if select:
210                    grib_write(gid_in, fout)
211            else:
212                grib_write(gid_in, fout)
213#AP end
214            grib_release(gid_in)
215
216        fin.close()
217        fout.close()
218
219        return
220
221    def copy(self, filename_in, selectWhere=True,
222             keynames=[], keyvalues=[], filemode='w'):
223        '''
224        Add the content of another input grib file to the objects file but
225        only messages corresponding to keys/values passed to the function.
226        The selectWhere switch decides if to copy the keys equal to (True) or
227        different to (False) the keynames/keyvalues list passed to the function.
228
229        @Input:
230            filename_in: string
231                Filename of the input file to read the grib messages from.
232
233            selectWhere: boolean, optional
234                Decides if to copy the keynames and values equal to (True) or
235                different to (False) the keynames/keyvalues list passed to the
236                function. Default is True.
237
238            keynames: list of ???, optional
239                List of keynames. Default is an empty list.
240
241            keyvalues: list of ???, optional
242                List of keynames. Default is an empty list.
243
244            filemode: string, optional
245                Sets the mode for the output file. Default is "w".
246
247        @Return:
248            <nothing>
249        '''
250
251        fin = open(filename_in)
252        fout = open(self.filename, filemode)
253
254        while 1:
255            gid_in = grib_new_from_file(fin)
256
257            if gid_in is None:
258                break
259
260            if len(keynames) != len(keyvalues):
261                raise Exception("Give a value for each keyname!")
262
263            select = True
264            i = 0
265            for key in keynames:
266                if not grib_is_defined(gid_in, key):
267                    raise Exception("Key was not defined")
268
269                if selectWhere:
270                    select = (select and (str(keyvalues[i]) ==
271                                          str(grib_get(gid_in, key))))
272                else:
273                    select = (select and (str(keyvalues[i]) !=
274                                          str(grib_get(gid_in, key))))
275                i += 1
276
277            if select:
278                grib_write(gid_in, fout)
279
280            grib_release(gid_in)
281
282        fin.close()
283        fout.close()
284
285        return
286
287    def index(self, index_keys=["mars"], index_file="my.idx"):
288        '''
289        @Description:
290            Create index file from a list of files if it does not exist or
291            read an index file.
292
293        @Input:
294            index_keys: list of strings, optional
295                Contains the list of key parameter names from
296                which the index is to be created.
297                Default is a list with a single entry string "mars".
298
299            index_file: string, optional
300                Filename where the indices are stored.
301                Default is "my.idx".
302
303        @Return:
304            iid: integer
305                Grib index id.
306        '''
307        print("... index will be done")
308        self.iid = None
309
310        if (os.path.exists(index_file)):
311            self.iid = grib_index_read(index_file)
312            print("Use existing index file: %s " % (index_file))
313        else:
314            for file in self.filename:
315                print("Inputfile: %s " % (file))
316                if self.iid is None:
317                    self.iid = grib_index_new_from_file(file, index_keys)
318                else:
319                    grib_index_add_file(self.iid, file)
320
321            if self.iid is not None:
322                grib_index_write(self.iid, index_file)
323
324        print('... index done')
325
326        return self.iid
327
328
329
330
331
Note: See TracBrowser for help on using the repository browser.
hosted by ZAMG