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
RevLine 
[64cf353]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.
[d69b677]37
[64cf353]38    Functionality provided:
39        Prepare input 3D-wind fields in hybrid coordinates +
40        surface fields for FLEXPART runs
41"""
42# ------------------------------------------------------------------------------
43# MODULES
44# ------------------------------------------------------------------------------
[d69b677]45from gribapi import *
46import traceback
[64cf353]47import sys, os
[d69b677]48
[64cf353]49# ------------------------------------------------------------------------------
50# CLASS
51# ------------------------------------------------------------------------------
[d69b677]52class GribTools:
[64cf353]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
[02c8c50]88            wherekeynames: list of ???, optional
[64cf353]89                Default value is an empty list.
90
[02c8c50]91            wherekeyvalues: list of ???, optional
[64cf353]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
[d69b677]103        while 1:
[64cf353]104            gid_in = grib_new_from_file(fileid)
[d69b677]105
[64cf353]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
[d69b677]115            for wherekey in wherekeynames:
[64cf353]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
[d69b677]123            if select:
124                llist = []
125                for key in keynames:
126                    llist.extend([str(grib_get(gid_in, key))])
127                return_list.append(llist)
[64cf353]128
[d69b677]129            grib_release(gid_in)
[64cf353]130
[d69b677]131        fileid.close()
[64cf353]132
[d69b677]133        return return_list
[64cf353]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
[02c8c50]156            wherekeynames: list of ???, optional
[64cf353]157                Default value is an empty list.
158
[02c8c50]159            wherekeyvalues: list of ???, optional
[64cf353]160                Default value is an empty list.
161
[02c8c50]162            strict: boolean, optional
[64cf353]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
[02c8c50]167            filemode: string, optional
[64cf353]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
[d69b677]177        while 1:
[64cf353]178            gid_in = grib_new_from_file(fin)
179
180            if gid_in is None:
181                break
[d69b677]182
[64cf353]183            if len(wherekeynames) != len(wherekeyvalues):
184                raise Exception("Give a value for each keyname!")
185
186            select = True
187            i = 0
[d69b677]188            for wherekey in wherekeynames:
[64cf353]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?
[d69b677]197            if select:
[64cf353]198                i = 0
[d69b677]199                for key in keynames:
200                    grib_set(gid_in, key, keyvalues[i])
[64cf353]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#
[d69b677]208            if strict:
209                if select:
[64cf353]210                    grib_write(gid_in, fout)
[d69b677]211            else:
[64cf353]212                grib_write(gid_in, fout)
213#AP end
[d69b677]214            grib_release(gid_in)
[64cf353]215
[d69b677]216        fin.close()
217        fout.close()
218
[64cf353]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
[02c8c50]233            selectWhere: boolean, optional
[64cf353]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
[02c8c50]238            keynames: list of ???, optional
[64cf353]239                List of keynames. Default is an empty list.
240
[02c8c50]241            keyvalues: list of ???, optional
[64cf353]242                List of keynames. Default is an empty list.
243
[02c8c50]244            filemode: string, optional
[64cf353]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
[d69b677]254        while 1:
[64cf353]255            gid_in = grib_new_from_file(fin)
[d69b677]256
[64cf353]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
[d69b677]265            for key in keynames:
[64cf353]266                if not grib_is_defined(gid_in, key):
267                    raise Exception("Key was not defined")
268
[d69b677]269                if selectWhere:
[64cf353]270                    select = (select and (str(keyvalues[i]) ==
271                                          str(grib_get(gid_in, key))))
[d69b677]272                else:
[64cf353]273                    select = (select and (str(keyvalues[i]) !=
274                                          str(grib_get(gid_in, key))))
275                i += 1
276
[d69b677]277            if select:
[64cf353]278                grib_write(gid_in, fout)
279
[d69b677]280            grib_release(gid_in)
[64cf353]281
[d69b677]282        fin.close()
283        fout.close()
284
[64cf353]285        return
286
287    def index(self, index_keys=["mars"], index_file="my.idx"):
288        '''
289        @Description:
[02c8c50]290            Create index file from a list of files if it does not exist or
[64cf353]291            read an index file.
292
293        @Input:
[02c8c50]294            index_keys: list of strings, optional
295                Contains the list of key parameter names from
296                which the index is to be created.
[64cf353]297                Default is a list with a single entry string "mars".
298
[02c8c50]299            index_file: string, optional
[64cf353]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")
[d69b677]308        self.iid = None
[64cf353]309
[d69b677]310        if (os.path.exists(index_file)):
311            self.iid = grib_index_read(index_file)
[64cf353]312            print("Use existing index file: %s " % (index_file))
[d69b677]313        else:
314            for file in self.filename:
[64cf353]315                print("Inputfile: %s " % (file))
316                if self.iid is None:
317                    self.iid = grib_index_new_from_file(file, index_keys)
[d69b677]318                else:
[64cf353]319                    grib_index_add_file(self.iid, file)
[02c8c50]320
[64cf353]321            if self.iid is not None:
322                grib_index_write(self.iid, index_file)
323
[02c8c50]324        print('... index done')
325
[64cf353]326        return self.iid
327
[d69b677]328
329
330
331
Note: See TracBrowser for help on using the repository browser.
hosted by ZAMG