我试图使用NAG优化库来解决Fortran中的最大似然问题,但是我遇到了从外部子程序funct和hess访问主程序中的变量的问题(参见pseudo-代码如下)。将变量(例如b
)从主程序传递给这样的例程的最佳方法是什么,因为我不能直接将它们作为参数传递(NAG库的限制)。我试图实现COMMON块,但没有太大的成功。
MODULE user_parameters
! Define the user parameters
INTEGER, PARAMETER :: a = 100
... other parameters
END MODULE user_parameters
MODULE process_data
USE user_parameters
! Define some other variables
INTEGER :: b
... other variables
CONTAINS
SUBROUTINE read_data
... read the data (e.g. alter value of b)
END SUBROUTINE read_data
SUBROUTINE clean_data
... clean the data (e.g. alter value of b)
END SUBROUTINE clean_data
END MODULE process_data
MODULE maximum_likelihood
USE user_parameters
USE process_data
CONTAINS
SUBROUTINE funct
... returns the LL's function value and gradient
END SUBROUTINE funct
SUBROUTINE hess
... returns the LL's hessian
END SUBROUTINE hess
END MODULE maximum_likelihood
PROGRAM estimation
USE user_parameters
USE process_data
USE maximum_likelihood
EXTERNAL funct, hess
CALL read_data
CALL clean_data
! Call minimization routine
CALL E04LBF(funct, hess)
END PROGRAM estimation
答案 0 :(得分:1)
如何编写模块maximum_likelihood
如下?
MODULE maximum_likelihood
IMPLICIT NONE
PRIVATE
PUBLIC init, fin, funct, hess
INTEGER, SAVE :: aa, bb
REAL, DIMENSION(:), ALLOCATABLE, SAVE :: vv
CONTAINS
SUBROUTINE init(aa_arg, bb_arg, vv_arg)
! set values module variables
END SUBROUTINE init
SUBROUTINE fin()
deallocate(vv)
END SUBROUTINE fin
SUBROUTINE funct
... returns the LL's function value and gradient
! using the values of aa, bb, and/or vv
END SUBROUTINE funct
SUBROUTINE hess
... returns the LL's hessian
! using the values of aa, bb, and/or vv
END SUBROUTINE hess
END MODULE maximum_likelihood
然后,主程序看起来像
PROGRAM estimation
USE maximum_likelihood, ONLY: init, fin, funct, hess
! read values for the parameters aaa, bbb, vvv
! set these values in the module variables in maximum_likelihood
CALL init(aaa, bbb, vvv)
! Call minimization routine
CALL E04LBF(funct, hess)
! clean up the module variables in maximum_likelihood
CALL fin()
END PROGRAM estimation