Как узнать имена параметров и данных, требуемых целевой функцией, в файле TMB .cpp?

Из учебника TMB определяются целевые функции в .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?

2 ответа

Решение

Я не знаю о функции в пакете, которая делает это, но функция ниже может помочь вам;

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

"чем" может быть "параметр", "данные", "отчет" или "sdreport", но по умолчанию я сделал это параметром.

ДОПОЛНЕНИЕ: если class==TRUE, то для параметра и данных класс (матрица, массив и т. Д.) Задается в качестве имени каждого объекта.

Спасибо @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
}
Другие вопросы по тегам