简体   繁体   English

NetCDF4 Python尺寸重新排序

[英]NetCDF4 Python dimensions reordered

I am creating a NC file using netCDF4 in python. 我正在使用python中的netCDF4创建NC文件。 The file is quite simple and includes variables of 1 and 2 dimensions (1st dim=N, 2nd dim=M). 该文件非常简单,并包含1和2维的变量(1st dim = N,2nd dim = M)。 But the problem is that when I read out the file, the dimensions of the 2D variables are interchanged, ie instead of coming out as data of dimension (N, M), they come out as dimension (M, N), while all 1D data comes out as (N, ), as expected. 但是问题在于,当我读取文件时,二维变量的尺寸会互换,即不是以尺寸(N,M)的数据形式出现,而是以尺寸(M,N)的形式出现,而所有1D数据按预期以(N,)形式显示。

The code looks something like this 该代码看起来像这样

root = nc.Dataset(filename, 'w', format='NETCDF4')
dimensions = ('N', 'M')

root.createDimension(dimensions[0], None)
root.createDimension(dimensions[1], None)

for field in fields:
        field_def = ...<defintion of field, how many dimensions etc...>
        if field_def[0] == 1: # how many dimensions in this variable
            chunk_size = (200, )
        else:
            chunk_size = (200, 1)

        dim = tuple(dimensions[:field_def[0]])
        var = root.createVariable(field, field_def[3], dimensions=dim,
                                fill_value=0,   chunksizes=chunk_size)

But when I read the file the dimensions of the 2D variables are opposite, ie the chunk size is (1, chunk_size) and dimensions are (M, N) not (N, M). 但是,当我读取文件时,二维变量的尺寸相反,即块尺寸为(1,chunk_size),尺寸为(M,N)而不是(N,M)。

Anyone who as experienced something like this, or can see if I am doing something wrong? 任何人经历过这样的事情,或者可以看看我做错了什么吗? I have implemented the same in Matlab, but there it all comes out correctly. 我已经在Matlab中实现了相同的功能,但是一切都正确地实现了。

Thanks 谢谢

Seems that this is not a python netCDF issue but more a "feature" of MATLAB netCDF. 似乎这不是python netCDF的问题,而是MATLAB netCDF的“功能”。 From the netcdf.defVar MATLAB documentation 来自netcdf.defVar MATLAB文档

This function corresponds to the "nc_def_var" function in the netCDF library C API, but because MATLAB uses FORTRAN-style ordering, the the fastest-varying dimension comes first and the slowest comes last. 该函数与netCDF库C API中的“ nc_def_var”函数相对应,但是由于MATLAB使用FORTRAN样式的排序,所以变化最快的维数排在最前面,而变化最快的维数排在最后。 Any unlimited dimension is therefore last in the list of dimension IDs. 因此,任何不受限制的尺寸都在尺寸ID列表的最后。 This ordering is the reverse of that found in the C API. 此顺序与C API中的顺序相反。

Thus, files generated using MATLAB are not compatible with other languages, unless you have some idea about dimension ordering, and can reorder variables when reading writing. 因此,使用MATLAB生成的文件与其他语言不兼容,除非您对尺寸排序有一定了解,并且在阅读本文时可以对变量进行重新排序。 But you have to be aware of this if files are to be used in software using another library/dimension ordering. 但是,如果要在使用其他库/维度顺序的软件中使用文件,则必须意识到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM