如何读取netcdf4 格式necep资料

Python023

如何读取netcdf4 格式necep资料,第1张

NetCDF文件是一种科学数据存储格式,广泛用于大气、海洋和地球科学。NetCDF也是一个函数库集合,提供给用户一整套使用和操作该种格式数据的方法。该格式是跨平台的,且可以使用C、Fortran和Matlab等多种语言进行操作。

安装过程如下:

(1)从http://www.unidata.ucar.edu/downloads/netcdf/index.jsp官方网站下载源程序包。最新版为4.0.1,安装的是3.6.3,测试成功。

(2)假设源程序包保存在/home/fengwei/netcdf-3.6.3文件夹下,打算安装在/usr/local/netcdf路径里。进入root后,操作如下:

mkdir /usr/local/netcdf

cd /home/fengwei/netcdf-3.6.3

./configure --prefix=/usr/local/netcdf

make check

make

make install

(3)安装完成后,/usr/local/netcdf/文件夹下存在4个文件,分别为bin,include,lib和share。

(4)针对感兴趣的某一nc文件,编写相应的fortran代码(如test.f90),其中应包括include

'netcdf.inc',并调用NetCDF给定的函数对nc文件进行读取和写入等操作。

(5)编译fortran代码,以intel fortran编译器为例,其他的编译器基本一致

ifort -c -I/usr/local/netcdf/include test.f90

ifort -o test test.o -L/usr/local/netcdf/lib -lnetcdf

(6)运行

./test

#include <iostream>

#include <netcdfcpp.h>

using namespace std

// We are reading 2D data, a 6 x 12 grid.

static const int NX = 6

static const int NY = 12

// Return this in event of a problem.

static const int NC_ERR = 2

int main(void)

{

// This is the array we will read.

int dataIn[NX][NY]

// Open the file. The ReadOnly parameter tells netCDF we want

// read-only access to the file.

NcFile dataFile("simple_xy.nc", NcFile::ReadOnly)

// You should always check whether a netCDF file open or creation

// constructor succeeded.

if (!dataFile.is_valid())

{

cout << "Couldn’t open file!\n"

return NC_ERR

}

// For other method calls, the default behavior of the C++ API is

// to exit with a message if there is an error. If that behavior

// is OK, there is no need to check return values in simple cases

// like the following.

// Retrieve the variable named "data"

Chapter 2: Example Programs 25

NcVar *data = dataFile.get_var("data")

// Read all the values from the "data" variable into memory.

data->get(&dataIn[0][0], NX, NY)

// Check the values.

for (int i = 0 i < NX i++)

for (int j = 0 j < NY j++)

if (dataIn[i][j] != i * NY + j)

return NC_ERR

// The netCDF file is automatically closed by the NcFile destructor

cout << "*** SUCCESS reading example file simple_xy.nc!" << endl

return 0

}