-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathspin_glass.cpp
388 lines (341 loc) · 12.9 KB
/
spin_glass.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
/* To compile this file, put it in the examples folder in your libdai installation location and
* run the following command from the libdai root directory:
*
* Ubuntu:
* g++ -Iinclude -Wno-deprecated -Wall -W -Wextra -fpic -O3 -g -DDAI_DEBUG -Llib -oexamples/spin_glass examples/spin_glass.cpp -ldai -lgmpxx -lgmp
*
* Mac:
* g++ -Iinclude -I/opt/local/include -Wno-deprecated -Wall -W -Wextra -fPIC -DMACOSX -arch x86_64 -O3 -g -DDAI_DEBUG -Llib -L/opt/local/lib -o examples/spin_glass examples/spin_glass.cpp -ldai -lgmpxx -lgmp -arch x86_64
*/
#include <dai/factorgraph.h>
#include <cmath>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <fstream>
#include <string>
#include <dai/alldai.h> // Include main libDAI header file
#include <dai/jtree.h>
using namespace std;
using namespace dai;
const double EULER = 0.5772156649;
// Random seed
int seed;
// Parameters (global variables set by main method)
string topology; // one of {chain, cycle, grid}
int n; // standard notation for number of variables
int A, B; // for grid: n=AxB variables V = [0, 1, ..., A-1] x [0, 1, ...,B-1]
int R; // variables take values in [0, 1, ..., R-1]
float f; // unary potentials drawn randomly from [-f, +f]
float c; // edge potentials drawn randomly from [0, c] or [-c, +c]
string potentials_type; // one of {fixed, attractive_random, mixed}
// Global variables
double logZ_exact; // exact value
// Variables and Factors
vector<Var> VAR;
vector<Factor> F;
/*
* Utility functions
*/
// Random number uniformly distributed in the interval [a, b]
double randu(double a, double b) {
if (a == b)
return a;
else
return a + static_cast <double> (rand()) /( static_cast <double> (RAND_MAX/(b-a)));
}
// Random number with Gumbel distribution of mean 0
double rand_gumbel() {
return -std::log((double)-std::log((double)randu(0.0, 1.0))) - EULER;
}
// Sets sampling bounds [theta_e_min, theta_e_max] for edge potentials based on model type
void set_bounds(string potentials_type, double& theta_e_min, double& theta_e_max) {
if (potentials_type == "fixed") {
theta_e_min = c;
theta_e_max = c;
}
else if (potentials_type == "attractive") {
theta_e_min = 0.0;
theta_e_max = c;
}
else if (potentials_type == "mixed") {
theta_e_min = -c;
theta_e_max = +c;
}
else throw invalid_argument("Invalid argument potentials_type");
}
// Creates an edge between variables n1 and n2 of potential J
Factor create_factor_Ising( const Var &n1, const Var &n2, Real J ) {
DAI_ASSERT( n1 != n2 );
Real buf[R*R];
int i = 0;
for (int i2 = 0; i2 < R; ++i2)
for (int i1 = 0; i1 < R; ++i1)
buf[i++] = (i1 == i2) ? std::exp(J) : std::exp(-J);
return Factor( VarSet(n1, n2), &buf[0] );
}
/*
* Model generation
* These functions set the global variables VAR (model variables) and F (model factors).
*/
void generate_model_chain(bool verbose = false) {
if (verbose) cout << "Generating Chain model variables and factors..." << endl;
// Variables
VAR.clear();
for (int i = 0; i < n; ++i)
VAR.push_back( Var(i, R) );
// Range of values for edge potentials
double theta_e_min = 0.0, theta_e_max = 0.0;
set_bounds(potentials_type, theta_e_min, theta_e_max);
// Factors with potentials
F.clear();
for (int i = 0; i < n; ++i) {
// unary potential
Real buf[R];
for (int r = 0; r < R; ++r)
buf[r] = std::exp(randu(-f, +f));
F.push_back( Factor(VAR[i], &buf[0]) );
// edge potential
if(i >= 1) F.push_back( create_factor_Ising(VAR[i], VAR[i-1], randu(theta_e_min, theta_e_max)) );
}
}
void generate_model_cycle(bool verbose = false) {
if (verbose) cout << "Generating Cycle model variables and factors..." << endl;
// Cycle is just a Chain with one more Factor
generate_model_chain();
if (n == 1) return;
// Range of values for edge potentials
double theta_e_min = 0.0, theta_e_max = 0.0;
set_bounds(potentials_type, theta_e_min, theta_e_max);
F.push_back( create_factor_Ising(VAR[0], VAR[n-1], randu(theta_e_min, theta_e_max)) );
}
void generate_model_grid(bool verbose = false) {
if (verbose) cout << "Generating Spin Glass model..." << endl;
//DAI_ASSERT( R == 2);
DAI_ASSERT(n = A * B);
// Variables
VAR.clear();
for (int a = 0; a < A; ++a)
for (int b = 0; b < B; ++b)
VAR.push_back( Var(a*B+b, R) );
// Range of values for edge potentials
double theta_e_min = 0.0, theta_e_max = 0.0;
set_bounds(potentials_type, theta_e_min, theta_e_max);
// Factors with potentials
F.clear();
for (int a = 0; a < A; ++a)
for (int b = 0; b < B; ++b) {
// unary potential
if (R == 2)
F.push_back( createFactorIsing(VAR[a*B+b], randu(-f, +f)) );
else {
Real buf[R];
for (int r = 0; r < R; ++r)
buf[r] = std::exp(randu(-f, +f));
F.push_back( Factor(VAR[a*B+b], &buf[0]) );
}
// edge potential
if(a >= 1) F.push_back( create_factor_Ising(VAR[a*B+b], VAR[(a-1)*B+b], randu(theta_e_min, theta_e_max)) );
if(b >= 1) F.push_back( create_factor_Ising(VAR[a*B+b], VAR[a*B+(b-1)], randu(theta_e_min, theta_e_max)) );
}
}
/*
* Perturbations
* These functions *copy* the global variable F (model factors), so VAR and F are not modified.
*/
FactorGraph perturb_none(bool verbose = false) {
if (verbose) cout << "Constructing FactorGraph with no perturbations..." << endl;
// Factor graph
FactorGraph SpinGlassModel(F);
return SpinGlassModel;
}
FactorGraph perturb_unary(bool verbose = false) {
if (verbose) cout << "Constructing FactorGraph with unary perturbations..." << endl;
// Perturbation factors
vector<Factor> factors(F);
for(int i = 0; i < n; ++i) {
Factor local( (VarSet(VAR[i])) );
for (int r = 0; r < R; ++r)
local.set(r, std::exp(rand_gumbel()));
factors.push_back(local);
}
// Factor graph
FactorGraph SpinGlassModel(factors);
return SpinGlassModel;
}
/*
* libDAI calls
*/
double logZ(FactorGraph fg, bool verbose = false) {
if (verbose) cout << "Computing logZ on FactorGraph..." << endl;
// Set some constants
size_t maxiter = 10000;
Real tol = 1e-9;
size_t verb = 0;
// Store the constants in a PropertySet object
PropertySet opts;
opts.set("maxiter",maxiter); // Maximum number of iterations
opts.set("tol",tol); // Tolerance for convergence
opts.set("verbose",verb); // Verbosity (amount of output generated)
JTree jt;
vector<size_t> jtmapstate;
// Construct a JTree (junction tree) object from the FactorGraph fg
// using the parameters specified by opts and an additional property
// that specifies the type of updates the JTree algorithm should perform
jt = JTree( fg, opts("updates",string("HUGIN")) );
// Initialize junction tree algorithm
jt.init();
// Run junction tree algorithm
jt.run();
// Report log partition sum (normalizing constant) of fg, calculated by the junction tree algorithm
return jt.logZ();
}
double MAP_JT(FactorGraph fg, bool verbose = false) {
if (verbose) cout << "Computing MAP on FactorGraph..." << endl;
// Set some constants
size_t maxiter = 100000;
Real tol = 1e-10;
size_t verb = 0;
// Store the constants in a PropertySet object
PropertySet opts;
opts.set("maxiter",maxiter); // Maximum number of iterations
opts.set("tol",tol); // Tolerance for convergence
opts.set("verbose",verb); // Verbosity (amount of output generated)
JTree jtmap;
vector<size_t> jtmapstate;
// Construct another JTree (junction tree) object that is used to calculate
// the joint configuration of variables that has maximum probability (MAP state)
//jtmap = JTree( fg, opts("updates",string("HUGIN"))("inference",string("MAXPROD")) );
jtmap = JTree( fg, opts("updates",string("SHSH"))("logdomain",false)("heuristic",string("MINWEIGHT"))("inference",string("MAXPROD")) );
// Initialize junction tree algorithm
jtmap.init();
// Run junction tree algorithm
jtmap.run();
// Calculate joint state of all variables that has maximum probability
jtmapstate = jtmap.findMaximum();
return fg.logScore( jtmapstate );
}
double MAP_BP(FactorGraph fg, bool verbose = false) {
if (verbose) cout << "Computing MAP on FactorGraph using max-product BP..." << endl;
// Set some constants
size_t maxiter = 10000;
Real tol = 1e-9;
size_t verb = 0;
// Store the constants in a PropertySet object
PropertySet opts;
opts.set("maxiter",maxiter); // Maximum number of iterations
opts.set("tol",tol); // Tolerance for convergence
opts.set("verbose",verb); // Verbosity (amount of output generated)
// Construct a BP (belief propagation) object from the FactorGraph fg
// using the parameters specified by opts and two additional properties,
// specifying the type of updates the BP algorithm should perform and
// whether they should be done in the real or in the logdomain
BP mp(fg, opts("updates",string("SEQRND"))("logdomain",false)("inference",string("MAXPROD"))("damping",string("0.5")));
// Initialize max-product algorithm
mp.init();
// Run max-product algorithm
mp.run();
// Calculate joint state of all variables that has maximum probability
// based on the max-product result
vector<size_t> mpstate = mp.findMaximum();
return fg.logScore( mpstate );
}
void json_header() {
cout << "{" << endl;
cout << " \"topology\" : \"" << topology << "\"," << endl;
cout << " \"n\" : " << n << "," << endl;
if (topology == "grid") {
cout << " \"A\" : " << A << "," << endl;
cout << " \"B\" : " << B << "," << endl;
}
cout << " \"K\" : " << R << "," << endl;
cout << " \"f\" : " << f << "," << endl;
cout << " \"c\" : " << c << "," << endl;
cout << " \"potentials_type\" : \"" << potentials_type << "\"," << endl;
cout << " \"lnZ\" : " << logZ_exact << "," << endl;
cout << " \"seed\" : " << seed << "," << endl;
}
void json_MAPs_unary_JT(int M) {
cout << " \"MAPs_unary_JT\" : [";
for (int m = 0; m < M - 1; ++m)
cout << MAP_JT(perturb_unary()) << ", ";
cout << MAP_JT(perturb_unary()) << "]" << endl;
cout << "}" << endl;
}
void json_MAPs_unary_BP(int M) {
cout << " \"MAPs_unary_BP\" : [";
for (int m = 0; m < M - 1; ++m)
cout << MAP_BP(perturb_unary()) << ", ";
cout << MAP_BP(perturb_unary()) << "]" << endl;
cout << "}" << endl;
}
void json_MAPs_unary_JT_BP(int M) {
// Compute MAP values
vector<double> MAPs_JT;
vector<double> MAPs_BP;
for (int m = 0; m < M; ++m) {
FactorGraph fg = perturb_unary();
MAPs_JT.push_back(MAP_JT(fg));
MAPs_BP.push_back(MAP_BP(fg));
}
// Print JT
cout << " \"MAPs_unary_JT\" : [";
for (int m = 0; m < M - 1; ++m)
cout << MAPs_JT[m] << ", ";
cout << MAPs_JT[M - 1] << "]," << endl;
// Print BP
cout << " \"MAPs_unary_BP\" : [";
for (int m = 0; m < M - 1; ++m)
cout << MAPs_BP[m] << ", ";
cout << MAPs_BP[M - 1] << "]" << endl;
// Print footer
cout << "}" << endl;
}
/*
Command line arguments:
- topology: {chain, cycle, grid}
- n: int >= 1
- A: grid height, only relevant for grid
- K: int >= 2
- f: float
- c: float
- potentials_type: string
- M: int
- MAP_solver: string
- seed: int
*/
int main(int argc, char* argv[]) {
// parse arguments
if (argc < 11)
cerr << "Not enough arguments provided" << endl;
topology = argv[1];
// set global variables
n = atoi(argv[2]);
A = atoi(argv[3]);
B = n / A;
if ((topology == "grid") && (A*B != n))
throw invalid_argument("Grid width A does not divide n");
R = atoi(argv[4]);
f = atof(argv[5]);
c = atof(argv[6]);
potentials_type = argv[7];
// set computation parameters
int M = atoi(argv[8]);
string MAP_solver = argv[9];
// seed randomness
seed = atoi(argv[10]);
srand (static_cast <unsigned> (seed));
// construct appropriate model
if (topology == "chain") generate_model_chain();
else if (topology == "cycle") generate_model_cycle();
else if (topology == "grid") generate_model_grid();
else throw invalid_argument("Invalid model topology provided");
// compute logZ and requested number M perturb-and-MAP samples
logZ_exact = logZ(perturb_none());
json_header();
if (MAP_solver == "JT") json_MAPs_unary_JT(M);
else if (MAP_solver == "BP") json_MAPs_unary_BP(M);
else if (MAP_solver == "JT_BP") json_MAPs_unary_JT_BP(M);
else throw invalid_argument("Invalid MAP solver argument provided");
return 0;
}