首页 > 解决方案 > 由 R 调用时,Fortran 子例程不计算

问题描述

我有大量数据,在一个 3D 数组中,所以我试图通过使用 Fortran 例程来加速 R 中的计算。下面的子程序由两个命令完美编译:

    gfortran -c -ffree-form file_name.f
    R CMD SHLIB file_name.f

这是我的子程序:

    subroutine saturation_vapour_pressure_from_temperature(temp,m,n,o,saturation_vapour_pressure)
    implicit none
    integer :: m,n,o
    integer :: x,y,t
    real, intent(in) ::temp(m,n,o)
    real, intent(out) :: saturation_vapour_pressure(m,n,o)
    real :: lvRv,To,eo
    saturation_vapour_pressure(m,n,o) = temp(m,n,o)
    LvRv= 5234.0
    To= 273.15
    eo= 0.6113
    do 15, t=1,o
        do 10, y=1,n
          do 5, x=1,m
          saturation_vapour_pressure(x,y,t) = eo * exp(LvRv*1/To - LvRv*1/temp(x,y,t))
 5          end do 
10         end do 
15       end do
     end subroutine saturation_vapour_pressure_from_temperature

我为输入分配了与输出相同的值,然后通过循环执行计算。但是它不起作用,尽管我有其他具有相同原理的子例程并且它们正在工作!这是R中的调用。

 temperature<-array(runif(12,273.15,300),dim = c(2,3,2))
 DIMn<-dim(temperature)
 #DIMn is the dimension of array
 dyn.load("saturation_vapour_pressure_from_temperature.so")      
result<- array(.Fortran("saturation_vapour_pressure_from_temperature",temp=as.numeric(temperature),
                      m=as.integer(DIMn[1]),
                      n=as.integer(DIMn[2]),
                      o=as.numeric(DIMn[3]),saturation_vapour_pressure=as.numeric(temperature))$saturation_vapour_pressure,
             dim = DIMn)

当我检查值时

   $ all(temperature==result)
     [1] TRUE

标签: rfortrangfortransubroutine

解决方案


不幸的是,我并不精通 R,但我可以给你一些想法:

  1. 你在那里的代码不应该编译,因为你没有声明变量s。我怀疑第一个 do 循环应该使用t,而不是s作为迭代器,但你会更清楚这一点。是否有可能它无法编译并且您使用的是旧版本?

  2. 你不需要使用标签。只需键入

    do t = 1, o
        do y = 1, n
            do x = 1, m
                saturation_vapour_pressure(x,y,t) = eo * exp(LvRv*1/To - LvRv*1/temp(x,y,t))
            end do
        end do
    end do
    

推荐阅读