TMB Documentation  v1.9.11
getListElement.hpp
1 /* Helpers, to check that data and parameters are of the right types.
2  "RObjectTester" denotes the type of a pointer to a test function.
3  Examples of test functions are "isMatrix", "Rf_isArray", "isNumeric",
4  etc (see Rinternals.h).
5 */
6 typedef Rboolean (*RObjectTester)(SEXP);
7 #ifdef WITH_LIBTMB
8 void RObjectTestExpectedType(SEXP x, RObjectTester expectedtype, const char *nam);
9 Rboolean isValidSparseMatrix(SEXP x);
10 Rboolean isNumericScalar(SEXP x);
11 #else
12 void RObjectTestExpectedType(SEXP x, RObjectTester expectedtype, const char *nam){
13  if(expectedtype != NULL){
14  if(!expectedtype(x)){
15  if(Rf_isNull(x)){
16  Rf_warning("Expected object. Got NULL.");
17  }
18  if(Rf_isNumeric(x) && !Rf_isReal(x)) {
19  Rf_warning("NOTE: 'storage.mode(%s)' must be 'double' when attribute 'check.passed' is set for 'data'.",nam);
20  }
21  Rf_error("Error when reading the variable: '%s'. Please check data and parameters.",nam);
22  }
23  }
24 }
25 Rboolean isValidSparseMatrix(SEXP x){
26  if(!Rf_inherits(x,"dgTMatrix"))Rf_warning("Expected sparse matrix of class 'dgTMatrix'.");
27  return Rf_inherits(x,"dgTMatrix");
28 }
29 Rboolean isNumericScalar(SEXP x){
30  if(LENGTH(x)!=1){
31  Rf_warning("Expected scalar. Got length=%i",LENGTH(x));
32  return FALSE;
33  }
34  return Rf_isReal(x);
35 }
36 #endif
37 
39 #ifdef WITH_LIBTMB
40 SEXP getListElement(SEXP list, const char *str, RObjectTester expectedtype=NULL);
41 int getListInteger(SEXP list, const char *str, int default_value = 0);
42 #else
43 SEXP getListElement(SEXP list, const char *str, RObjectTester expectedtype=NULL)
44 {
45  if(config.debug.getListElement)std::cout << "getListElement: " << str << " ";
46  SEXP elmt = R_NilValue, names = Rf_getAttrib(list, R_NamesSymbol);
47  int i;
48  for (i = 0; i < Rf_length(list); i++)
49  if(strcmp(CHAR(STRING_ELT(names, i)), str) == 0)
50  {
51  elmt = VECTOR_ELT(list, i);
52  break;
53  }
54  if(config.debug.getListElement)std::cout << "Length: " << LENGTH(elmt) << " ";
55  if(config.debug.getListElement)std::cout << "\n";
56  RObjectTestExpectedType(elmt, expectedtype, str);
57  return elmt;
58 }
59 int getListInteger(SEXP list, const char *str, int default_value = 0) {
60  SEXP tmp = getListElement(list, str);
61  if ( tmp == R_NilValue ) {
62  Rf_warning("Missing integer variable '%s'. Using default: %d. (Perhaps you are using a model object created with an old TMB version?)", str, default_value);
63  return default_value;
64  }
65  return INTEGER(tmp)[0];
66 }
67 #endif
License: GPL v2