File: glue.cpp

package info (click to toggle)
r-cran-rpf 1.0.5%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 1,472 kB
  • sloc: cpp: 5,370; sh: 114; ansic: 41; makefile: 2
file content (366 lines) | stat: -rw-r--r-- 10,999 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
#include "rpf.h"

// [[Rcpp::export]]
int get_model_id(const StringVector &str)
{
	const char *target = str[0];
  for (int sx=0; sx < Glibrpf_numModels; sx++) {
    if (strcmp(Glibrpf_model[sx].name, target) == 0) {
			return sx;
    }
  }
  return NA_REAL;
}

static int getSpecID(const NumericVector &spec)
{
  if (spec.size() < RPF_ISpecCount)
    stop("Item spec must be of length %d, not %d",
				 RPF_ISpecCount, int(spec.size()));

  int id = spec[RPF_ISpecID];
  if (id < 0 || id >= Glibrpf_numModels)
    stop("Item model %d out of range", id);

	return id;
}

// [[Rcpp::export]]
int numSpec(const NumericVector &spec)
{
	int id = getSpecID(spec);
  int numSpec = (*Glibrpf_model[id].numSpec)(spec.begin());
	return numSpec;
}

// [[Rcpp::export]]
int numParam(const NumericVector &spec)
{
	int id = getSpecID(spec);
  int numParam = (*Glibrpf_model[id].numParam)(spec.begin());
	return numParam;
}

// [[Rcpp::export]]
SEXP paramInfo(const NumericVector &spec, int pnum)
{
	int id = getSpecID(spec);

  int numParam = (*Glibrpf_model[id].numParam)(spec.begin());
  if (pnum < 0 || pnum >= numParam) stop("Item model %d has %d parameters", id, numParam);

  const char *type;
  double upper, lower;
  (*Glibrpf_model[id].paramInfo)(spec.begin(), pnum, &type, &upper, &lower);

  int len = 3;
  SEXP names, ans;
  Rf_protect(names = Rf_allocVector(STRSXP, len));
  Rf_protect(ans = Rf_allocVector(VECSXP, len));
  int lx = 0;
  SET_STRING_ELT(names, lx, Rf_mkChar("type"));
  SET_VECTOR_ELT(ans,   lx, Rf_ScalarString(Rf_mkChar(type)));
  SET_STRING_ELT(names, ++lx, Rf_mkChar("upper"));
  SET_VECTOR_ELT(ans,   lx, Rf_ScalarReal(std::isfinite(upper)? upper : NA_REAL));
  SET_STRING_ELT(names, ++lx, Rf_mkChar("lower"));
  SET_VECTOR_ELT(ans,   lx, Rf_ScalarReal(std::isfinite(lower)? lower : NA_REAL));
  Rf_namesgets(ans, names);
  UNPROTECT(2);

  return ans;
}

int unpack_theta(int dims, double *param, int numAbilities, double *theta, double *out)
{
  if (numAbilities == dims) {
    for (int dx=0; dx < dims; ++dx) {
      double th = theta[dx];
      if (!std::isfinite(th)) return 0;
      out[dx] = th;
    }
  } else {
    int ax = 0;
    for (int dx=0; dx < dims; ++dx) {
      if (param[dx] == 0) continue;
      double th = theta[ax]; // could read uninitialized memory, but we detect below
      if (!std::isfinite(th)) return 0;
      out[dx] = th;
      ++ax;
    }
    if (ax != numAbilities) {
      stop("Item has %d nonzero dims but given %d abilities", ax, numAbilities);
    }
  }
  return 1;
}

// [[Rcpp::export]]
NumericMatrix prob(const NumericVector &spec, SEXP r_param, RObject r_theta)
{
	int id = getSpecID(spec);

  int numSpec = (*Glibrpf_model[id].numSpec)(spec.begin());
  if (spec.size() < numSpec)
    stop("Item spec must be of length %d, not %d", numSpec, spec.size());
    
  int numParam = (*Glibrpf_model[id].numParam)(spec.begin());
  if (Rf_length(r_param) < numParam)
    stop("Item has %d parameters, only %d given", numParam, Rf_length(r_param));

  const int numOutcomes = spec[RPF_ISpecOutcomes];
  const int dims = spec[RPF_ISpecDims];
  double *param = REAL(r_param);
  int numPeople = 1;
  int numAbilities = 1;
  double *theta = 0;
  if (dims == 0) {
	  if (r_theta != R_NilValue) {
			NumericVector tvec = as<NumericVector>(r_theta);
			numPeople = tvec.size();
		}
  } else if (dims == 1) {
		NumericVector tvec = as<NumericVector>(r_theta);
    numPeople = Rf_length(tvec);
		theta = tvec.begin();
  } else {
		NumericMatrix tmat = as<NumericMatrix>(r_theta);
		numAbilities = tmat.nrow();
		numPeople = tmat.ncol();
		theta = tmat.begin();
  }

	NumericMatrix out(numOutcomes, numPeople);
  Eigen::VectorXd thBuf(dims);
  for (int px=0; px < numPeople; px++) {
	  if (dims && !unpack_theta(dims, param, numAbilities, theta + px*numAbilities, thBuf.data())) {
		  for (int ox=0; ox < numOutcomes; ox++) {
			  out(ox, px) = NA_REAL;
		  }
		  continue;
	  }
	  (*Glibrpf_model[id].prob)(spec.begin(), param, thBuf.data(), out.begin()+px*numOutcomes);
    for (int ox=0; ox < numOutcomes; ox++) {
      double prob = out(ox, px);
      if (!std::isfinite(prob)) {
				out(ox, px) = NA_REAL;  // legitimate (e.g., grm thresholds misordered)
      }
    }
  }

  return out;
}

// [[Rcpp::export]]
SEXP logprob(const NumericVector &spec, SEXP r_param, RObject r_theta)
{
	int id = getSpecID(spec);

  int numSpec = (*Glibrpf_model[id].numSpec)(spec.begin());
  if (spec.size() < numSpec)
    stop("Item spec must be of length %d, not %d", numSpec, spec.size());
    
  int numParam = (*Glibrpf_model[id].numParam)(spec.begin());
  if (Rf_length(r_param) < numParam)
    stop("Item has %d parameters, only %d given", numParam, Rf_length(r_param));

  const int numOutcomes = spec[RPF_ISpecOutcomes];
  const int dims = spec[RPF_ISpecDims];
  int numPeople = 1;
  double *param = REAL(r_param);
  int numAbilities = 1;
  double *theta = 0;
  if (dims == 0) {
	  if (r_theta != R_NilValue) {
			NumericVector tvec = as<NumericVector>(r_theta);
			numPeople = tvec.size();
		}
  } else if (dims == 1) {
		NumericVector tvec = as<NumericVector>(r_theta);
    numPeople = Rf_length(tvec);
		theta = tvec.begin();
  } else {
		NumericMatrix tmat = as<NumericMatrix>(r_theta);
		numAbilities = tmat.nrow();
		numPeople = tmat.ncol();
		theta = tmat.begin();
  }

	NumericMatrix out(numOutcomes, numPeople);
  Eigen::VectorXd thBuf(dims);
  for (int px=0; px < numPeople; px++) {
	  if (dims && !unpack_theta(dims, param, numAbilities, theta + px*numAbilities, thBuf.data())) {
		  for (int ox=0; ox < numOutcomes; ox++) {
			  out(ox, px) = NA_REAL;
		  }
		  continue;
	  }
	  (*Glibrpf_model[id].logprob)(spec.begin(), param, thBuf.data(), out.begin()+px*numOutcomes);
    for (int ox=0; ox < numOutcomes; ox++) {
      double prob = out(ox, px);
      if (!std::isfinite(prob)) {
				out(ox, px) = NA_REAL;  // legitimate (e.g., grm thresholds misordered)
      }
    }
  }
	return out;
}

// [[Rcpp::export]]
SEXP dLL(const NumericVector &spec, SEXP r_param, SEXP r_where, SEXP r_weight)
{
	int id = getSpecID(spec);
  int numSpec = (*Glibrpf_model[id].numSpec)(spec.begin());
  if (spec.size() < numSpec)
    stop("Item spec must be of length %d, not %d", numSpec, spec.size());
    
  int numParam = (*Glibrpf_model[id].numParam)(spec.begin());
  if (Rf_length(r_param) < numParam)
    stop("Item has %d parameters, only %d given", numParam, Rf_length(r_param));

  int dims = spec[RPF_ISpecDims];
  if (Rf_length(r_where) != dims)
    stop("Item has %d dimensions, but where is of length %d",
	  dims, Rf_length(r_where));

  int outcomes = spec[RPF_ISpecOutcomes];
  if (Rf_length(r_weight) != outcomes)
    stop("Item has %d outcomes, but weight is of length %d",
	  outcomes, Rf_length(r_weight));

  double *where = NULL;
  if (dims) where = REAL(r_where);

  const int numDeriv = numParam + numParam*(numParam+1)/2;
  SEXP ret;
  Rf_protect(ret = Rf_allocVector(REALSXP, numDeriv));
  memset(REAL(ret), 0, sizeof(double) * numDeriv);
  (*Glibrpf_model[id].dLL1)(spec.begin(), REAL(r_param),
			    where, REAL(r_weight), REAL(ret));
  for (int px=0; px < numDeriv; px++) {
    if (!std::isfinite(REAL(ret)[px])) stop("Deriv %d not finite at step 1", px);
  }
  (*Glibrpf_model[id].dLL2)(spec.begin(), REAL(r_param), REAL(ret));
  for (int px=0; px < numDeriv; px++) {
	  //if (!std::isfinite(REAL(ret)[px])) stop("Deriv %d not finite at step 2", px);
  }
  UNPROTECT(1);
  return ret;
}

// [[Rcpp::export]]
SEXP dTheta(const NumericVector &spec, SEXP r_param, SEXP r_where, SEXP r_dir)
{
	int id = getSpecID(spec);
  int numSpec = (*Glibrpf_model[id].numSpec)(spec.begin());
  if (spec.size() < numSpec)
    stop("Item spec must be of length %d, not %d", numSpec, spec.size());
    
  int numParam = (*Glibrpf_model[id].numParam)(spec.begin());
  if (Rf_length(r_param) < numParam)
    stop("Item has %d parameters, only %d given", numParam, Rf_length(r_param));

  int dims = spec[RPF_ISpecDims];
  if (dims == 0) stop("Item has no factors");
  if (Rf_length(r_dir) != dims)
    stop("Item has %d dimensions, but dir is of length %d",
	  dims, Rf_length(r_dir));
  if (Rf_length(r_where) != dims)
    stop("Item has %d dimensions, but where is of length %d",
	  dims, Rf_length(r_where));

  SEXP ret, names;
  Rf_protect(ret = Rf_allocVector(VECSXP, 2));
  Rf_protect(names = Rf_allocVector(STRSXP, 2));

  int outcomes = spec[RPF_ISpecOutcomes];
  SEXP grad, hess;
  Rf_protect(grad = Rf_allocVector(REALSXP, outcomes));
  Rf_protect(hess = Rf_allocVector(REALSXP, outcomes));
  memset(REAL(grad), 0, sizeof(double) * outcomes);
  memset(REAL(hess), 0, sizeof(double) * outcomes);
  (*Glibrpf_model[id].dTheta)(spec.begin(), REAL(r_param), REAL(r_where), REAL(r_dir),
			     REAL(grad), REAL(hess));
  SET_VECTOR_ELT(ret, 0, grad);
  SET_VECTOR_ELT(ret, 1, hess);
  SET_STRING_ELT(names, 0, Rf_mkChar("gradient"));
  SET_STRING_ELT(names, 1, Rf_mkChar("hessian"));
  Rf_namesgets(ret, names);
  UNPROTECT(4);
  return ret;
}

// [[Rcpp::export]]
NumericVector rescale(const NumericVector &spec, SEXP r_param, SEXP r_mean, const NumericMatrix &r_cov)
{
	int id = getSpecID(spec);
  int numSpec = (*Glibrpf_model[id].numSpec)(spec.begin());
  if (spec.size() < numSpec)
    stop("Item spec must be of length %d, not %d", numSpec, spec.size());
    
  int numParam = (*Glibrpf_model[id].numParam)(spec.begin());
  if (Rf_length(r_param) < numParam)
    stop("Item has %d parameters, only %d given", numParam, Rf_length(r_param));

  int dims = spec[RPF_ISpecDims];
  if (dims == 0) stop("Item has no factors");
  if (Rf_length(r_mean) != dims)
    stop("Item has %d dimensions, but mean is of length %d",
	  dims, Rf_length(r_mean));

  int cov_rows = r_cov.nrow();
	int cov_cols = r_cov.ncol();
  if (cov_rows != dims || cov_rows != dims)
    stop("Item has %d dimensions, but cov is %dx%d",
	  dims, cov_rows, cov_cols);

  Eigen::VectorXi mask(numParam);
  mask.setZero();

  NumericVector ret = clone(r_param);
  (*Glibrpf_model[id].rescale)(spec.begin(), ret.begin(), mask.data(),
															 REAL(r_mean), r_cov.begin());
  return ret;
}

// [[Rcpp::export]]
bool has_openmp()
{
#if defined(_OPENMP)
	return true;
#else
	return false;
#endif
}

int GlobalNumberOfCores = 1;

// [[Rcpp::export]]
int setNumberOfCores(int num)
{
#if defined(_OPENMP)
	GlobalNumberOfCores = num;
#endif
	return num;
}

extern const struct rpf librpf_model[];
extern const int librpf_numModels;

const struct rpf *Glibrpf_model;
int Glibrpf_numModels;

// Called by OpenMx
void get_librpf_models(int version, int *numModels, const struct rpf **model) // nocov start
{
  if (version != LIBIFA_RPF_API_VERSION) stop("LIBIFA_RPF binary API version mismatch");
  *numModels = librpf_numModels;
  *model = librpf_model;
} // nocov end

// [[Rcpp::export]]
void registerCCallable()
{
    Glibrpf_numModels = librpf_numModels;
    Glibrpf_model = librpf_model;
    R_RegisterCCallable("rpf", "get_librpf_model_GPL", (DL_FUNC) get_librpf_models);
}