在TMB tutorial中,可以在.cpp文件中定义目标函数,以便在C++函数和R中调用的函数之间共享参数名称和模型数据结构的名称。例如,tutorial.cpp文件:
#include <TMB.hpp> // Links in the TMB libraries
template<class Type>
Type objective_function<Type>::operator() ()
{
DATA_VECTOR(x); // Data vector transmitted from R
PARAMETER(mu); // Parameter value transmitted from R
PARAMETER(sigma); //
Type f; // Declare the "objective function" (neg. log. likelihood)
f = -sum(dnorm(x,mu,sigma,true)); // Use R-style call to normal density
return f;
}在编译和dyn.load之后,可以从R调用这个函数,但是,您需要知道数据向量被命名为x,并且有两个参数值mu和sigma。是否可以从R中检索这些所需对象的名称?
发布于 2017-07-31 23:24:21
我不知道包中有什么函数可以做到这一点,但是下面的函数可能会帮到你;
TMBsearch = function(path,what='parameter',class=FALSE){
if(!missing(what) | length(what)>1) stop("What should be of length one")
if(!(what %in% c('parameter','data','report','sdreport'))) stop("What should be parameter, data, report or sdreport")
text = paste0(paste0(readLines(path), collapse = "\n"), "\n") # read the text from the cpp file
start = unlist(gregexpr(pattern =toupper(what),text)) # starting position
end.poss = unlist(gregexpr(pattern =')',text)) # possible end positions
end = rep(NA,length(start))
for(i in 1:length(start)){end[i] = end.poss[(end.poss-start[i]) > 0][1]} # actual end position
textsub = substring(text,first=start,last=end) # extract the full PARAMETER/DATA_x(...)
found = gsub("[\\(\\)]", "", regmatches(textsub, gregexpr("\\(.*?\\)", textsub))) # get rid of the brackets
if(class & what %in% c('parameter','data')){
dataclass=tolower(gsub("_", "",gsub(".*PARAMETER\\s*|\\(.*", "", textsub)))
dataclass[dataclass=='']="single value"
names(found)=datatype
}
return(found)
}
TMBsearch(path=paste0(filename,'.cpp'), what='parameter')"what“可以是”参数“、”数据“、”报告“或”sdreport“,但默认情况下我将其设为参数。
加法: if class==TRUE than for参数和数据类(矩阵、数组等)被指定为每个对象的名称。
发布于 2017-08-03 17:11:44
感谢你@Wave的有用功能。我只是稍微改进了一下,如果what有多个参数,就可以检索列表中的所有类型。我的名字中还有一些剩余的空格,所以我还添加了一个gsub。
TMBsearch <- function(path, what = c('parameter', 'data', 'report', 'sdreport')) {
res <- lapply(what, function(what) {
# what <- match.arg(what)
text <- paste0(paste0(readLines(path), collapse = "\n"), "\n") # read the text from the cpp file
start <- unlist(gregexpr(pattern = toupper(what), text)) # starting position
end.poss <- unlist(gregexpr(pattern = ')', text)) # possible end positions
end <- rep(NA,length(start))
for (i in 1:length(start)) {end[i] <- end.poss[(end.poss - start[i]) > 0][1]} # actual end position
textsub <- substring(text, first = start, last = end) # extract the full PARAMETER/DATA_x(...) -> might be handy to now whether array or vector or...
found <- gsub("[\\(\\)]", "", regmatches(textsub, gregexpr("\\(.*?\\)", textsub))) # get rid of the brackets
found_nospace <- gsub(" ", "", found) # get rid of the spaces if some left
return(found_nospace)
})
names(res) <- what
res
}https://stackoverflow.com/questions/42801008
复制相似问题