/
ratlab_internal.cpp
479 lines (457 loc) · 13.4 KB
/
ratlab_internal.cpp
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
#include <string>
using namespace std;
#include <string.h>
#include <math.h>
#include "mex.h"
#include <R.h>
#include <Rembedded.h>
#include <Rdefines.h>
#include <Rinternals.h>
#include <R_ext/Parse.h>
#include <stdio.h>
#include <stdlib.h>
// TODO: Currently, tight coupling is only going to be possible with
// Numeric types. Should we create an analogous factor?
#if defined(WIN32) || defined(WIN64)
static int R_running_as_main_program;
#else
extern int R_running_as_main_program;
#endif
static int R_is_running = 0;
extern "C"
{
SEXP RExecuteString (const char *s)
{
ParseStatus status;
SEXP cmdSexp, cmdExpr, ret;
PROTECT (cmdSexp = allocVector (STRSXP, 1));
SET_STRING_ELT (cmdSexp, 0, mkChar (s));
cmdExpr = PROTECT (R_ParseVector (cmdSexp, -1, &status, R_NilValue));
if (status != PARSE_OK)
{
ret = R_NilValue;
UNPROTECT (2);
}
else
{
ret = PROTECT (eval (VECTOR_ELT (cmdExpr, 0), R_GlobalEnv));
UNPROTECT (3);
}
return (ret);
}
// Does Matlab/Octave hold floats or integers?
// Yes, both. -bwl
SEXP MexDoubleMatrix2SexpVector (const mxArray * pMexMat)
{
if (!mxIsNumeric (pMexMat))
{
Rf_endEmbeddedR (0);
printf ("MexDoubleMatrix2SexpVector takes a matrix parameter.");
return (R_NilValue);
}
size_t N, M;
N = mxGetN (pMexMat);
M = mxGetM (pMexMat);
if (N > 1 && M > 1)
warning ("Both N and M are greater than 1.");
SEXP numericVals = PROTECT (NEW_NUMERIC (N * M));
memcpy (NUMERIC_DATA (numericVals), mxGetPr (pMexMat),
N * M * sizeof (double));
UNPROTECT (1);
return (numericVals);
}
SEXP MexDoubleCellArray2SexpVector (const mxArray * pMexMat)
{
if (!mxIsCell (pMexMat))
{
Rf_endEmbeddedR (0);
printf ("MexDoubleCellArray2SexpVector takes cell array parameter.");
return (R_NilValue);
}
int nVals = mxGetNumberOfElements (pMexMat);
SEXP numericVals = PROTECT (NEW_NUMERIC (nVals));
double *pVals = NUMERIC_DATA (numericVals);
int i;
const mxArray *pElem;
for (i = 0; i < nVals; ++i)
{
pElem = mxGetCell (pMexMat, i);
if (!mxIsNumeric (pElem))
{
Rf_endEmbeddedR (0);
printf ("Cell values must be numeric");
UNPROTECT (1);
return (R_NilValue);
}
if (mxGetNumberOfElements (pElem) != 1)
{
Rf_endEmbeddedR (0);
printf ("Only one value per cell is currently supported.\n");
UNPROTECT (1);
return (R_NilValue);
}
pVals[i] = *mxGetPr (pElem);
}
UNPROTECT (1);
return (numericVals);
}
SEXP MexStringCellArray2SexpVector (const mxArray * pMexMat)
{
if (!mxIsCell (pMexMat))
{
Rf_endEmbeddedR (0);
printf ("MexStringCellArray2SexpVector takes cell array parameter.\n");
return (R_NilValue);
}
int nStrings = mxGetNumberOfElements (pMexMat);
SEXP stringVals = PROTECT (allocVector (STRSXP, nStrings));
int i;
for (i = 0; i < nStrings; ++i)
{
mxArray *pElem = mxGetCell (pMexMat, i);
if (mxIsChar (pElem))
{
int nchar = mxGetNumberOfElements (pElem) + 1;
char *pNewString = (char *) malloc (nchar * sizeof (char));
mxGetString (pElem, pNewString, nchar);
SET_STRING_ELT (stringVals, i, mkChar (pNewString));
free (pNewString);
}
else
{
Rf_endEmbeddedR (0);
printf ("Element %d must be a string\n", i);
UNPROTECT (1);
return (R_NilValue);
}
}
UNPROTECT (1);
return (stringVals);
}
char **MexStringCellArray2StringVector (const mxArray * pMexMat)
{
if (!mxIsCell (pMexMat))
{
Rf_endEmbeddedR (0);
printf("MexStringCellArray2SexpVector takes cell array parameter.\n");
return (NULL);
}
int nStrings = mxGetNumberOfElements (pMexMat);
// See if any of the cell array elements are not strings.
int i;
for (i = 0; i < nStrings; ++i)
{
if (!mxIsChar (mxGetCell (pMexMat, i))) return NULL;
}
char **pStrings = (char **) malloc (sizeof (char *) * nStrings);
for (i = 0; i < nStrings; ++i)
{
mxArray *pElem = mxGetCell (pMexMat, i);
int nchar = mxGetNumberOfElements (pElem) + 1;
char *pNewString = (char *) malloc (nchar * sizeof (char));
mxGetString (pElem, pNewString, nchar);
pStrings[i] = pNewString;
}
return (pStrings);
}
// This function will take our matlab dataframe class and
// create a data frame.
SEXP CreateDataFrame (const mxArray * pColNames, const mxArray * pData)
{
// Let's make sure the lengths of each of the cell array elements
// is the same.
size_t i, firstLength, ncols;
ncols = mxGetNumberOfElements (pData);
firstLength =
ncols > 0 ? mxGetNumberOfElements (mxGetCell (pData, 0)) : 0;
for (i = 1; i < ncols; ++i)
{
if (mxGetNumberOfElements (mxGetCell (pData, i)) != firstLength)
{
Rf_endEmbeddedR (0);
printf ("Cell array elements are not of the same length.\n");
return (R_NilValue);
}
}
// There must be a column name for each column.
unsigned int ncolNames = mxGetNumberOfElements (pColNames);
if (!(ncolNames == ncols))
{
Rf_endEmbeddedR (0);
printf ("There must be one column name for each column.\n");
return (R_NilValue);
}
// Now, let's try to create the data frame
SEXP ret = PROTECT (NEW_LIST (ncols));
int protectCount = 1;
// Fill in the list with columns.
const mxArray *pElem;
for (i = 0; i < ncols; ++i)
{
pElem = mxGetCell (pData, i);
if (mxIsNumeric (pElem))
{
SET_VECTOR_ELT (ret, i, PROTECT (MexDoubleMatrix2SexpVector (pElem)));
++protectCount;
}
else if (mxIsCell (pElem))
{
if (mxGetNumberOfElements (pElem) == 0)
{
SET_VECTOR_ELT (ret, i, PROTECT (NEW_NUMERIC (0)));
}
else
{
const mxArray *first = mxGetCell (pElem, 0);
if (mxIsChar (first))
{
SET_VECTOR_ELT (ret, i, PROTECT (MexStringCellArray2SexpVector
(pElem)));
}
else
{
SET_VECTOR_ELT (ret, i, PROTECT (MexDoubleCellArray2SexpVector
(pElem)));
}
}
++protectCount;
}
}
SEXP colNames = PROTECT (MexStringCellArray2SexpVector (pColNames));
++protectCount;
SEXP dataFrameString = PROTECT (allocVector (STRSXP, 1));
SET_STRING_ELT (dataFrameString, 0, mkChar ("data.frame"));
++protectCount;
setAttrib (ret, R_NamesSymbol, colNames);
setAttrib (ret, R_ClassSymbol, dataFrameString);
UNPROTECT (protectCount);
return (ret);
}
SEXP *CreateSexps (const mxArray * pMexMat)
{
int nVectors = mxGetNumberOfElements (pMexMat);
if (nVectors == 0)
return NULL;
int i;
// TODO: Add code to see if we have something of the dataframe class!
// return the R object as a...
// Use 2 passes. One to figure out if the cell array elements are
// valid; one to create the SEXPs.
mxArray *pElem;
for (i = 0; i < nVectors; ++i)
{
pElem = mxGetCell (pMexMat, i);
if (mxIsCell (pElem))
{
if (mxGetNumberOfElements (pElem) > 0)
{
mxArray *first = mxGetCell (pElem, 0);
if (!mxIsChar (first) && !mxIsNumeric (first))
{
Rf_endEmbeddedR (0);
printf ("Cell %d contains an unsupported type: %s\n", i,
mxGetClassName (first));
return (NULL);
}
}
}
else if (mxIsClass (pElem, "struct"))
{
// Let's make sure it looks like a dataframe struct.
// Changed this from a field count to looking for a structure with a
// field named "colnames." XXX This should be further improved. -bwl
if (!mxGetField(pElem,0,"colnames"))
{
Rf_endEmbeddedR (0);
printf ("Bad struct passed to ratlab_internal\n");
return (NULL);
}
}
else if (!mxIsNumeric (pElem))
{
printf ("Cell %d contains an unsupported type: %s\n", i,
mxGetClassName (pElem));
return (NULL);
}
}
SEXP *pSexps = (SEXP *) malloc (sizeof (SEXP) * nVectors);
for (i = 0; i < nVectors; ++i)
{
pElem = mxGetCell (pMexMat, i);
if (mxIsNumeric (pElem))
{
pSexps[i] = MexDoubleMatrix2SexpVector (pElem);
}
else if (mxIsCell (pElem))
{
if (mxGetNumberOfElements (pElem) == 0)
{
pSexps[i] = NEW_NUMERIC (0);
}
else
{
const mxArray *first = mxGetCell (pElem, 0);
if (mxIsChar (first))
{
pSexps[i] = MexStringCellArray2SexpVector (pElem);
}
else
{
pSexps[i] = MexDoubleCellArray2SexpVector (pElem);
}
}
}
else if (mxIsClass (pElem, "struct"))
{
pSexps[i] = CreateDataFrame (mxGetField (pElem, 0, "colnames"),
mxGetField (pElem, 0, "data"));
}
else
return (NULL);
}
return (pSexps);
}
void FreeStrings (char **pStrings, const int numStrings)
{
int i;
for (i = 0; i < numStrings; ++i)
{
free (pStrings[i]);
}
free (pStrings);
}
// The R command to run.
// Three right-hand sides: {{symbol names}, {data}, "R statement"}
void mexFunction (int nlhs, mxArray * plhs[], int nrhs,
const mxArray * prhs[])
{
// Argument checking...
// Make sure we have the correct number of arguments.
if (nrhs != 3)
{
printf ("The ratlab function takes 3 arguements.\n");
return;
}
// Make sure we have a variable name for each data cell array element.
if (mxGetNumberOfElements (prhs[0]) != mxGetNumberOfElements (prhs[1]))
{
printf ("Error: there are %ld variable names but %ld data vectors!\n",
mxGetNumberOfElements (prhs[0]),
mxGetNumberOfElements (prhs[1]));
return;
}
// Make sure the third parameter is a string.
if (!mxIsChar (prhs[2]))
{
printf ("The third parameter must be an R statement.\n");
return;
}
// Create a new R instance if one has not been created...
if (!R_is_running)
{
R_running_as_main_program = 1;
char *argv[] = { (char *) "REmbedded", (char *) "--slave" };
Rf_initEmbeddedR (2, argv);
R_is_running = 1;
}
int protectCount=0;
// Get the R variable names.
char **pVariableNames = MexStringCellArray2StringVector (prhs[0]);
size_t nVariables = mxGetNumberOfElements (prhs[0]);
// Create the SEXPs. This is the only function that will change
// with the tight coupling.
SEXP *pSexps;
if ((pSexps = CreateSexps (prhs[1])) == NULL)
{
printf ("Problem in CreateSexps.\n");
return;
}
// Get the R command.
int commandLength = mxGetNumberOfElements (prhs[2]) + 1;
char *pCommand = (char *) malloc (commandLength * sizeof (char));
mxGetString (prhs[2], pCommand, commandLength);
// Create the variables in R.
size_t i = 0;
for (i = 0; i < nVariables; ++i)
{
defineVar (install (pVariableNames[i]), pSexps[i], R_GlobalEnv);
}
// Now, let's run the command in R.
RExecuteString ((string ("ratlabReturn=") + pCommand).c_str ());
// ratlabReturn holds the return of the command. Try to typecast it
// to a matrix.
// XXX XXX XXX Need more general R to Matlab conversion here.
// RExecuteString ("xxx=ls.str()");
// RExecuteString ("print(xxx,give.attr=TRUE)");
SEXP ratlabRet = findVar (install ("ratlabReturn"), R_GlobalEnv);
// If it doesn't have dimension attributes, make them.
SEXP rDim = getAttrib (ratlabRet, R_DimSymbol);
if (GET_LENGTH(rDim) == 0)
{
RExecuteString(
"ratlabReturn=matrix(as.double(ratlabReturn), nrow=length(ratlabReturn))");
}
else
{
RExecuteString(
"ratlabReturn=matrix(as.double(ratlabReturn), nrow=nrow(ratlabReturn), dimnames=dimnames(ratlabReturn))");
}
// Since we overwrote ratlabReturn we have to get it again from the
// R enviornment.
ratlabRet = findVar (install ("ratlabReturn"), R_GlobalEnv);
SEXP rDimNames = getAttrib (ratlabRet, R_DimNamesSymbol);
SEXP rRowNames = R_NilValue;
SEXP rColNames = R_NilValue;
if (GET_LENGTH(rDimNames) > 0)
{
rRowNames = VECTOR_ELT (rDimNames, 0);
rColNames = VECTOR_ELT (rDimNames, 1);
}
int pCaDims[3];
pCaDims[0] = GET_LENGTH (rRowNames);
pCaDims[1] = GET_LENGTH (rColNames);
pCaDims[2] = 1;
const char *fieldNames[] =
{ (char *) "colnames", (char *) "rownames", (char *) "data" };
// plhs[0] = mxCreateStructArray(3, pCaDims, 3, fieldNames);
plhs[0] = mxCreateStructMatrix (1, 1, 3, fieldNames);
mxArray *pColNameCells = mxCreateCellArray (1, &pCaDims[1]);
for (i = 0; i < (size_t) GET_LENGTH (rColNames); ++i)
{
mxSetCell (pColNameCells, i,
mxCreateString (CHAR (STRING_ELT (rColNames, i))));
// TODO: mxSetFieldByNumber will be more efficient.
// mxSetField(plhs[0], i, "colnames",
// mxCreateString(CHAR(STRING_ELT(rColNames, i))));
}
mxSetField (plhs[0], 0, "colnames", pColNameCells);
mxArray *pRowNameCells = mxCreateCellArray (1, &pCaDims[0]);
for (i = 0; i < (size_t) GET_LENGTH (rRowNames); ++i)
{
mxSetCell (pRowNameCells, i,
mxCreateString (CHAR (STRING_ELT (rRowNames, i))));
// TODO: mxSetFieldByNumber will be more efficient.
// mxSetField(plhs[0], i, "rownames",
// mxCreateString(CHAR(STRING_ELT(rRowNames, i))));
}
mxSetField (plhs[0], 0, "rownames", pRowNameCells);
int matrixDims[2];
matrixDims[0] = ncols (ratlabRet);
matrixDims[1] = nrows (ratlabRet);
mxArray *pRetMat =
mxCreateNumericArray (2, matrixDims, mxDOUBLE_CLASS, mxREAL);
double *pm = mxGetPr (pRetMat);
memcpy (pm, NUMERIC_DATA (ratlabRet),
sizeof (double) * matrixDims[0] * matrixDims[1]);
mxSetField (plhs[0], 0, "data", pRetMat);
// Clean up.
RExecuteString ("rm(ratabReturn)");
// TODO: If the next line is commented out, there may be a memory leak!
FreeStrings (pVariableNames, nVariables);
free (pSexps);
free (pCommand);
UNPROTECT(protectCount);
// Rf_endEmbeddedR(0);
return;
}
} // extern "C"