简体   繁体   中英

NetCDF4 Python dimensions reordered

I am creating a NC file using netCDF4 in python. The file is quite simple and includes variables of 1 and 2 dimensions (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.

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).

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.

Thanks

Seems that this is not a python netCDF issue but more a "feature" of MATLAB netCDF. From the netcdf.defVar MATLAB documentation

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. Any unlimited dimension is therefore last in the list of dimension IDs. This ordering is the reverse of that found in the 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. But you have to be aware of this if files are to be used in software using another library/dimension ordering.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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