ecCodes 学习 利用ecCodes Python API对GRIB文件进行读写

参考 https://www.ecmwf.int/assets/elearning/eccodes/eccodes2/story_html5.html
https://confluence.ecmwf.int/display/ECC/GRIB+examples
https://confluence.ecmwf.int/download/attachments/97363968/eccodes_grib_python_2018.pdf

近期需要实现Python下对GRIB数据的读取。Kallan写过一篇“基于Python的Grib数据可视化”,介绍了如何利用pygrib读取GRIB数据。

但是pygrib所依赖的GRIB_API已经不再更新,原开发者转为开发ecCodes。因此研究用ecCodes的Python接口读取GRIB数据。

好消息是,自2.10.0版本以后,ecCodes支持Python 3接口。可在CMake编译时指定“-DPYTHON_EXECUTABLE=/usr/bin/python3”选项开启对Python3 支持。

PS:编译完成后,还需要设置eccodes库路径(可参考此方法:设置python路径 - 一步一脚印 - CSDN博客),否则可能运行时会出现"NameError: name ‘xxx’ is not defined"错误。

Python读取GRIB的流程基本的流程和fortran的(参见ecCodes 学习 利用ecCodes fortran90 api对GRIB文件进行读写)一样,只是函数调用方式不一样。大致思路如下:

基本解码流程

1. 指定打开方式(“读”或“写”),打开一个或多个GRIB文件;

2. 根据不同加载方式,加载一个或多个GRIB messages到内存:
  有两种函数:codes_grib_new_from_file 和 codes_new_from_index。调用后会返回一个唯一的identifier,用于对已加载的GRIB messages进行操纵。

3. 调用codes_get函数对已加载的GRIB messages进行解码; (可以解码需要的数据)

4. 释放已经加载的GRIB messages:
  codes_release  

5. 关闭打开的 GRIB 文件.

下面是一段读取GRIB数据的示例代码

#!/usr/bin/env python
# -*- coding:utf-
from eccodes import *

#打开文件
ifile = open('example.grib')
while 1:
    igrib = codes_grib_new_from_file(ifile)
    if igrib is None: break

    #从加载的mes中解码/编码数据
    date = codes_get(igrib,"dataDate")
    levtype = codes_get(igrib,"typeOfLevel")
    level = codes_get(igrib,"level")
    values = codes_get_values(igrib)
    print (date,levtype,level,values[0],values[len(values)-1])

    #释放
    codes_release(igrib)
ifile.close()

注:Python版本的函数与Fortran版本类似,所有函数列表参考http://download.ecmwf.int/test-data/eccodes/html/namespaceec_codes.html

猜你喜欢

转载自www.cnblogs.com/jiangleads/p/10668819.html
今日推荐