-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlogpost_c_i_c.cpp
282 lines (229 loc) · 9.68 KB
/
logpost_c_i_c.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
// compile with:
//
// mex logpost_c_i_c.cpp printmex.cpp -I/usr/local/boost-1.64.0/include/
// TODO dedupe with logprior_c and sample_c and loglik
//
// see https://stackoverflow.com/questions/16127060/what-is-the-default-location-for-boost-library-when-installed-using-macport-on-m
// and https://www.mathworks.com/matlabcentral/answers/7955-using-boost-libraries-with-mex-function-in-matlab
/* ========================================================================
* copy of
* phonebook.cpp
* example for illustrating how to manipulate structure.
*
* takes a (MxN) structure matrix which has first field as
* character array(name), and second field as scalar double (phone number).
* This function returns a new structure (1x1)containing following fields:
* for character array input, it will be (MxN) cell array;
* and for numeric double (noncomplex, scalar) input, it will be (MxN)
* cell array where each field is numeric array of type double.
*
* Build : from MATLAB
* >> mex phonebook.cpp
* Usage with example : from MATLAB
* >> friends(1).name = 'Jordan Robert';
* >> friends(1).phone = 3386;
* >> friends(2).name = 'Mary Smith';
* >> friends(2).phone = 3912;
* >> friends(3).name = 'Stacy Flora';
* >> friends(3).phone = 3238;
* >> friends(4).name = 'Harry Alpert';
* >> friends(4).phone = 3077;
* >> phonebook(friends)
*
* This is a MEX-file for MATLAB.
* Copyright 2017 The MathWorks, Inc.
*=======================================================================*/
#include "mex.hpp"
#include "mexAdapter.hpp"
#include "printmex.h"
#include "datastructs.h"
class MexFunction : public Function {
private:
std::shared_ptr<matlab::engine::MATLABEngine> matlabPtr;
// types -- see https://www.mathworks.com/help/matlab/apiref/matlab.data.arraytype.html
const std::vector<std::string> fieldNamesH = {"c", "p", "q", "tp", "hp", "theta", "mu"}; // H
const std::vector<ArrayType> fieldTypesH = {ArrayType::DOUBLE, ArrayType::DOUBLE, ArrayType::DOUBLE, ArrayType::DOUBLE, ArrayType::DOUBLE, ArrayType::DOUBLE, ArrayType::DOUBLE};
const std::vector<std::string> fieldNamesD = {"name", "G", "tasks", "r"}; // D
const std::vector<ArrayType> fieldTypesD = {ArrayType::CHAR, ArrayType::STRUCT, ArrayType::STRUCT, ArrayType::CELL};
const std::vector<std::string> fieldNamesG = {"N", "E", "edges"}; // D.G
const std::vector<ArrayType> fieldTypesG = {ArrayType::DOUBLE, ArrayType::DOUBLE, ArrayType::DOUBLE};
const std::vector<std::string> fieldNamesh = {"alpha", "std_theta", "theta_mean", "std_mu", "std_r"}; // h
const std::vector<ArrayType> fieldTypesh = {ArrayType::DOUBLE, ArrayType::DOUBLE, ArrayType::DOUBLE, ArrayType::DOUBLE, ArrayType::DOUBLE};
public:
/* Constructor for the class. */
MexFunction()
{
matlabPtr = getEngine();
}
void displayError(std::string errorMessage)
{
ArrayFactory factory;
matlabPtr->feval(matlab::engine::convertUTF8StringToUTF16String("error"),
0, std::vector<Array>({
factory.createScalar(errorMessage) }));
}
/* This is the gateway routine for the MEX-file. */
void
operator()(ArgumentList outputs, ArgumentList inputs) {
std::srand(0); // for reproducibility
checkArguments (outputs,inputs);
// check c_i_new
const TypedArray<double> _c_i_new = inputs[0];
int c_i_new = _c_i_new[0];
DEBUG_PRINT("c_i_new = %d\n", c_i_new);
// check i
const TypedArray<double> _i = inputs[1];
int i = _i[0];
DEBUG_PRINT("i = %d\n", i);
// check D TODO dedupe with sample_c.cpp
StructArray const matlabStructArrayD = inputs[3];
checkStructureElements(matlabStructArrayD, "D", fieldNamesD, fieldTypesD);
size_t total_num_of_elements = matlabStructArrayD.getNumberOfElements();
for (size_t i=0; i<total_num_of_elements; i++)
{
// check D.G
const StructArray structFieldG = matlabStructArrayD[i]["G"];
checkStructureElements(structFieldG, "D.G", fieldNamesG, fieldTypesG);
const TypedArray<double> _N = structFieldG[0]["N"];
const TypedArray<double> _E = structFieldG[0]["E"];
int N = (int)_N[0];
if (_E.getNumberOfElements() != N * N)
{
displayError("D.G.E must have D.G.N^2 elements.");
}
// check D.tasks
const StructArray matlabStructArrayTasks = matlabStructArrayD[i]["tasks"];
const TypedArray<double> _s = matlabStructArrayTasks[0]["s"];
const TypedArray<double> _g = matlabStructArrayTasks[0]["g"];
if (_s.getNumberOfElements() != _g.getNumberOfElements())
{
displayError("D.tasks.s and D.tasks.g must have the same number of elements.");
}
// check D.r
const CellArray matlabStructArrayRewards = matlabStructArrayD[i]["r"];
if (matlabStructArrayRewards.getNumberOfElements() != N)
{
displayError("D.r should have D.N elements");
}
}
// init D
Data D(matlabStructArrayD);
// check h
StructArray const matlabStructArrayHyperparams = inputs[4];
checkStructureElements(matlabStructArrayHyperparams, "h", fieldNamesh, fieldTypesh);
// init h
Hyperparams h(matlabStructArrayHyperparams);
// init & check H TODO dedupe with sample_c.cpp
Hierarchy H(D.G.N);
StructArray const matlabStructArrayH = inputs[2];
checkStructureElements(matlabStructArrayH, "H", fieldNamesH, fieldTypesH);
const TypedArray<double> _c = matlabStructArrayH[0]["c"];
if (_c.getNumberOfElements() != D.G.N)
{
displayError("H.c should have D.G.N elements");
}
const TypedArray<double> _theta = matlabStructArrayH[0]["theta"];
// TODO this is wrong; needs to be max(c)
// also, wtf try to pass Hout as input argument -> Busy
//if (_theta.getNumberOfElements() != D.G.N)
//{
// displayError("H.theta should have D.G.N elements");
//}
const TypedArray<double> _mu = matlabStructArrayH[0]["mu"];
if (_mu.getNumberOfElements() != D.G.N)
{
displayError("H.mu should have D.G.N elements");
}
H.InitFromMATLAB(matlabStructArrayH);
H.Print();
// compute Logpost
//
double logp = H.LogPost_c_i(c_i_new, i - 1, D, h); // OMG off by one on i, but not on c_i_new!
// read up on https://www.mathworks.com/help/matlab/apiref/matlab.data.arrayfactory.html?searchHighlight=createarray&s_tid=doc_srchtitle#bvn7dve-1
ArrayFactory factory;
Array result = factory.createScalar<double>(logp);
outputs[0] = result;
}
// check fields for any structure
//
void checkStructureElements(StructArray const & matlabStructArray, const std::string & name, const std::vector<std::string> & expectedFieldNames, const std::vector<ArrayType> & expectedFieldTypes)
{
std::ostringstream stream;
size_t nfields = matlabStructArray.getNumberOfFields();
auto fields = matlabStructArray.getFieldNames();
size_t total_num_of_elements = matlabStructArray.getNumberOfElements();
std::vector<std::string> fieldNames(fields.begin(), fields.end());
char err[100];
/* Produce error if structure has wrong number of fields. */
if(nfields != expectedFieldNames.size())
{
sprintf(err, "Struct %s must contain %lu fields.", name.c_str(), expectedFieldNames.size());
displayError(err);
}
for (size_t i = 0; i < expectedFieldNames.size(); i++)
{
auto it = find(fieldNames.begin(), fieldNames.end(), expectedFieldNames[i]);
/* Produce error if field is missing. */
if (it == fieldNames.end())
{
sprintf(err, "Struct %s must contain field '%s'.", name.c_str(), expectedFieldNames[i].c_str());
displayError(err);
}
else
{
for (size_t entryIndex=0; entryIndex<total_num_of_elements; entryIndex++)
{
const Array structField = matlabStructArray[entryIndex][expectedFieldNames[i]];
/* Produce error if name field in structure is empty. */
if (structField.isEmpty())
{
sprintf(err, "Struct %s has empty field %s on index %zu.", name.c_str(), expectedFieldNames[i].c_str(), entryIndex);
displayError(err);
}
/* Produce error if name is not a valid character array. */
if (structField.getType() != expectedFieldTypes[i])
{
sprintf(err, "Struct %s field %s on index %zu has invalid type", name.c_str(), expectedFieldNames[i].c_str(), entryIndex);
displayError(err);
}
}
}
}
}
// check function arguments
//
void checkArguments(ArgumentList outputs, ArgumentList inputs) {
if (inputs.size() < 5)
{
displayError("Specify H, D and h as input arguments.");
}
if (inputs.size() > 5)
{
displayError("Too many input arguments.");
}
if (outputs.size() > 1)
{
displayError("Too many outputs specified.");
}
if (inputs[0].getType() != ArrayType::DOUBLE)
{
displayError("c_i_new must be a number.");
}
if (inputs[1].getType() != ArrayType::DOUBLE)
{
displayError("i must be a number.");
}
if (inputs[2].getType() != ArrayType::STRUCT)
{
displayError("H must be a structure.");
}
if (inputs[3].getType() != ArrayType::STRUCT)
{
displayError("D must be a structure.");
}
if (inputs[4].getType() != ArrayType::STRUCT)
{
displayError("h must be a structure.");
}
}
};