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已不再更新,GRIB_API的開發者轉為開發ecCodes,因此研究利用ecCodes的Python API讀取GRIB數據。

此外,ecCodes自2.10.0版本以后,支持Python 3接口。可在CMake編譯時,指定‘-DPYTHON_EXECUTABLE=/usr/bin/python3’選項,開啟對Python3 的支持。

PS:編譯完成后,還需要設置eccodes庫路徑(可參考此方法:設置python路徑 - 一步一腳印 ,建議用其中第二種方法,從.pth文件中添加路徑),否則可能運行時會出現"NameError: name ‘xxx’ is not defined"錯誤。

 

Python讀取GRIB文件的流程和fortran類似,只是函數調用方式不一樣。大致思路如下:

基本解碼流程

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 文件.

 

順序訪問方式:

大致思路:

-> codes_open_file 

-> codes_grib_new_from_file -> codes_get -> codes_release

     …

-> codes_grib_new_from_file -> codes_get-> codes_release 

-> codes_close_file

 

索引訪問方式(通常比順序訪問快):

注意,eccodes中的index文件(后綴為.idx)與GrADS中后綴為.idx的文件不能通用!

大致思路:

-> codes_index_create(從grib文件創建index) 或 codes_index_read(讀取已有index)

-> codes_index_select 選取鍵值

-> codes_new_from_index -> codes_get -> codes_release

     …

-> codes_new_from_index -> codes_get -> codes_release

-> codes_index_release

 

——引自  ecCodes 學習 利用ecCodes fortran90 api對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

    #從加載的message中解碼/編碼數據
    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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM