在NetCDF中沿着无限维度写入标量变量

3
我正在尝试将一个水动力模型的时间变量写入到一个netcdf文件(无限维度变量)中。以下是一个Fortran90的简化代码示例,突显了我的问题。
在模拟期间,根据用户指定的输出间隔(此示例为10次),写入netcdf文件的子程序会被多次调用。我可以创建文件并在第一次调用子程序时添加属性。
但我无法正确地获取开始和计数变量,在子程序的后续调用中将时间变量写入文件中。在尝试编译代码时,写入模型时间变量时出现以下错误:错误:没有专门为通用函数“nf90_put_var”编写。
PROGRAM test_netcdf

  IMPLICIT NONE

  INTEGER :: N
  REAL :: time_step = 2.

  ! Call efdc_netcdf 10 times
  DO N=1,10

     CALL efdc_netcdf(N, time_step)

     time_step=time_step + 1.

  ENDDO

END PROGRAM test_netcdf

************************************
! Create NetCDF file and write variables
SUBROUTINE efdc_netcdf(N, time_step)

USE netcdf
IMPLICIT NONE

LOGICAL,SAVE::FIRST_NETCDF=.FALSE.
CHARACTER (len = *), PARAMETER :: FILE_NAME = "efdc_test.nc"
INTEGER :: ncid, status
INTEGER :: time_dimid
INTEGER :: ts_varid, time_varid

INTEGER :: start(1), count(1)
INTEGER :: deltat

INTEGER :: N
REAL :: time_step

start=(/N/)
count=(/1/)

! Create file and add attributes during first call of efdc_netcdf
IF(.NOT.FIRST_NETCDF)THEN

    status=nf90_create(FILE_NAME, NF90_CLOBBER, ncid)

    ! Define global attributes once
    status=nf90_put_att(ncid, NF90_GLOBAL, 'format', 'netCDF-3 64bit offset file')
    status=nf90_put_att(ncid, NF90_GLOBAL, 'os', 'Linux')
    status=nf90_put_att(ncid, NF90_GLOBAL, 'arch', 'x86_64')

    ! Define deltat variable
    status=nf90_def_var(ncid,'deltat',nf90_int,ts_varid)

    ! Define model time dimension
    status=nf90_def_dim(ncid,'efdc_time',nf90_unlimited,time_dimid)

    ! Define model time variable
    status=nf90_def_var(ncid,'efdc_time',nf90_real,time_dimid,time_varid)

    status=nf90_enddef(ncid)

    ! Put deltat during first call
    deltat=7
    status=nf90_put_var(ncid, ts_varid, deltat)

    FIRST_NETCDF=.TRUE.

ENDIF

! Put model time variable
status=nf90_put_var(ncid, time_varid, time_step, start=start, count=count)

! Close file at end of DO loop
IF(N.EQ.10) THEN
   status=nf90_close(ncid)
ENDIF

RETURN
END SUBROUTINE efdc_netcdf

刚才的评论撤销。nf90_put_var函数中的count参数在使用标量参数(如单个实数)时没有意义。除此之外,你的程序在这里的写法是正确的(gfortran、netcdf 4.1.3和4.2.1)。 - Jonathan Dursi
我将尝试省略计数,但当我将DIMENSION(1)添加到两个 REAL 变量声明中时,代码就可以运行了。 - Chris
1个回答

3
问题出现在编译器标注的这一行代码上:
status=nf90_put_var(ncid, time_varid, time_step, start=start, count=count)

你正在(正确地)尝试将标量变量time_step写入到定义在一维无限范围维度上的变量time_varid的特定索引start中。但是,在这种情况下,可选参数count没有意义;你正在写入标量,而count只能是1。因此,Fortran绑定的nf90_put_var()仅接受单个标量作为输入,并且没有为count定义可选参数,这就是为什么编译器会报“no specific function for the generic' nf90_put_var”错误的原因。这都是很合理的,但是错误信息和文档都没有很好地帮助解决问题。
你可以通过将time_step数据放入real,dimension(1)变量中,并将其放入其中来修复代码;但最简单的方法是摆脱不必要的count规定,因为在这里并不需要它。
status=nf90_put_var(ncid, time_varid, time_step, start=start)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接