Source

is-solver / siman_solve / siman_solve.c

Full commit
  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
/*
 * siman_solve.c
 *
 * Use simulated annealing to repeatedly invoke Stephen's solver.
 *
 * Usage:
 *
 *	siman_solve --rho=DDD --sigma_v=DDD --a=DDD --gamma=DDD --s=DDD \
 *        --lambda_1=DDD --lambda_2=DDD --delta=DDD --epsilon_P=DDD     \
 *	  --theta=DDD  [--prefix=PPPP]                                  \
 *
 *	--prefix is optional prefix for generated files.
 */

#include <math.h>
#include <tgmath.h>
#include <string.h>
#include <stdio.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_siman.h>

/* Command to run */
#define SOLVE_COMMAND		"solve_isC-icpc"

/* Solve parameters */
#define MODEL_VALUE_COUNT	8
#define	STEP_ALPHA		0.2

#define PARAM_rho  	0
#define PARAM_sigma_v   1
#define PARAM_a	        2
#define PARAM_gamma  	3
#define PARAM_s 	4	
#define PARAM_lambda_1 	5
#define PARAM_lambda_2 	6
#define PARAM_theta	7


/*
 * Model value ranges -
 *
 * 	These values are used to bound the stepping during the
 *	simulated annealuing processing. They are also used to
 *	validate the input parameters.
 */

/* STEPHEN - FILL IN */
double ModelValueMin[MODEL_VALUE_COUNT] =
{
    0.2,	/* rho  	*/
    -3.912023,	/* sigma_v  	*/
    0.01,	/* a	       	*/
    -10,	/* gamma (log gamma)  	*/
    0.0001,	/* s 		*/
    -9.21034,	/* lambda_1 	*/
    -9.21034,	/* lambda_2 	*/
  /* -10.0,	/\* delta 	*\/ */
  /* -10.0,	/\* epsilon_P	*\/ */
    -10.0		/* theta	*/
};

/* STEPHEN - FILL IN */
double ModelValueMax[MODEL_VALUE_COUNT] =
{
    0.95,		/* rho  	*/
    -0.01005034,		/* sigma_v 	*/
    1.0,		/* a 	 	*/
    -2.995732,		/* log gamma     	*/
    0.01,		/* s		*/
    -1.203973,		/* lambda_1 	*/
    -4.60517,		/* lambda_2	*/
    /* 10.0,		/\* delta 	*\/ */
    /* 10.0,		/\* epsilon_P	*\/ */
    0.84		/* theta	*/
};

char *ModelValueNames[MODEL_VALUE_COUNT] = 
{
  "rho",	
  "sigma_v",	
  "a",		
  "gamma",	
  "s",		
  "lambda_1",	
  "lambda_2",	
  /* "delta",	 */
  /* "epsilon_P", */
  "theta"
};

/* Global variables */
static int	 Iter   = 1;
static char	*Prefix = "Pref"
;static char     *Momentlist = "Momentlist";
static char     *Datamoments = "Datamoments";
static char     *Gmmweightmatrix = "Gmmweightmatrix";
static char     *DoSMM = "--do_smm_for_ddw --add_ddw='1' --delta='0.15' --epsilon_P='-4.0' --log_gamma --log_sigma_v ";
/*
 * Simulated annealing parameters:
 *
 *	These can be adjusted.
 *
 *	The STEP_SIZE parameter is simply passed from this code into gsl_siman_solve
 *	and from there to SolveStep, where it is ignored. 
 */

#define N_TRIES		200	/* How many points do we try before stepping 	*/
#define ITERS_FIXED_T	200	/* How many iterations for each T? 		*/
#define STEP_SIZE 	1.0     /* Max step size in random walk 		*/
#define K 		1.0	/* Boltzmann constant 				*/
#define T_INITIAL 	5000.0	/* Initial temperature 				*/
#define MU_T 		2.0   /* Damping factor for temperature 		*/
#define T_MIN 		5.0e-1	/* Minimum temperature 				*/

gsl_siman_params_t Params = {N_TRIES, ITERS_FIXED_T, STEP_SIZE, K, T_INITIAL, MU_T, T_MIN};

/* Simulated annealing callback function declarations */
double	SolveEnergy(void *xp);
void	SolveStep(const gsl_rng *Rand, void *xp, double StepSize);
void	SolvePrint(void *xp);
double	SolveMetric(void *xp, void *yp);

/* Utility functions */
void PrintModel(char *, double[MODEL_VALUE_COUNT]);

/* Main program */
int main(int argc, char *argv[])
{
  int		i;
  int		j;
  double	Model[MODEL_VALUE_COUNT];

  /* Initialize model values */
  for (i = 0; i < MODEL_VALUE_COUNT; i++)
  {
    Model[i] = INFINITY;
  }

  /* Capture model values arguments */
  for (i = 1; i < argc; i++)
  {
    if (strncmp(argv[i], "--prefix=", 9) == 0)
    {
      Prefix = &argv[i][9];
      printf("Prefix set to %s\n", Prefix);
      continue;
    }


    if (strncmp(argv[i], "--momentlist=", 13) == 0) {
	Momentlist = &argv[i][13];
	printf("Momentlist set to %s\n", Momentlist);
	continue;
    }

    if (strncmp(argv[i], "--datamoments=", 14) == 0) {
	Datamoments = &argv[i][14];
	printf("Datamoments set to %s\n", Datamoments);
	continue;
    }

    if (strncmp(argv[i], "--gmm_weight_matrix=", 20) == 0) {
	Gmmweightmatrix = &argv[i][20];
	printf("Gmmweightmatrix set to %s\n", Gmmweightmatrix);
	continue;
    }


    j = ModelNameIndex(argv[i] + 2);
    
    if (j != -1)
    {
      Model[j] = atof(argv[i] + 3 + strlen(ModelValueNames[j]));
      continue;
    }

    printf("Usage: %s --rho=d.dd ... --epsilon_P=d.dd [--prefix=PPPP]\n", argv[0]);
    exit(1);
  }

  /* Validate model values */
  for (i = 0; i < MODEL_VALUE_COUNT; i++)
  {
    if (Model[i] == INFINITY)
    {
      printf("Error: No value supplied for parameter '%s'\n", ModelValueNames[i]);
      exit(2);
    }

    if (Model[i] < ModelValueMin[i])
    {
      printf("Error: Value supplied for parameter '%s' less than min.\n", ModelValueNames[i]);
      exit(2);
    }

    if (Model[i] > ModelValueMax[i])
    {
      printf("Error: Value supplied for parameter '%s' more than max.\n", ModelValueNames[i]);
      exit(3);
    }
  }
  
  PrintModel("After Parse and Validate", Model);

  /* Create and intialize random number generator */
  const gsl_rng *Rand = gsl_rng_alloc(gsl_rng_env_setup());

  /* Set IEEE floating point mode from environment */
  gsl_ieee_env_setup();

  /* Do the simulated annealing */
  gsl_siman_solve(Rand,			/* Random number generator	*/
		  Model,		/* Starting configuration	*/
		  SolveEnergy,		/* Energy function		*/
		  SolveStep,		/* Step function		*/
		  SolveMetric,		/* Distance function		*/
		  SolvePrint,		/* Print function		*/
		  NULL,			/* Copy function		*/
		  NULL,			/* Copy constructor function	*/
		  NULL,			/* Destructor function		*/
		  sizeof(Model),	/* Configuration size		*/
		  Params);		/* SA Parameters 		*/

  PrintModel("Solved", Model);
}

/*
 * PrintModel -
 *
 *	Display the model with the specified label. No return value.
 */

void PrintModel(char *Label, double Model[MODEL_VALUE_COUNT])
{
  int	i;

  printf("%s:\n", Label);
  printf("  ");

  for (i = 0; i < MODEL_VALUE_COUNT; i++)
  {
    printf("%s=%f", ModelValueNames[i], Model[i]);
    if (i != (MODEL_VALUE_COUNT - 1))
    {
      printf(", ");
    }
  }
  printf("\n");
}

/*
 * SolveEnergy -
 */

double SolveEnergy(void *xp)
{
  double 	*Model = (double *) xp;
  int		 i;
  char		 Command[2048];
  char		 CommandArg[1024];
  char		 CommandOut[2048];
  char           MlCommand[1024];
  char           DMCommand[1024];
  char           GMWCommand[1024];
  char		*EnPtr;
  FILE		*FP;
  double 	 Energy;

  /* Create basic command line */
  strcpy(Command, "");
  strcat(Command, SOLVE_COMMAND);
  strcat(Command, " ");

  /* Add iteration */
  sprintf(CommandArg, "--uuid_i=%s%d", Prefix, Iter);
  strcat(Command, CommandArg);
  strcat(Command, " ");

  /* Add model values */
  for (i = 0; i < MODEL_VALUE_COUNT; i++)
  {
    sprintf(CommandArg, "--%s='%f'", ModelValueNames[i], Model[i]);
    strcat(Command, CommandArg);
    strcat(Command, " ");
  }

  /* Add smm flag */
  strcat(Command, DoSMM);
  strcat(Command, " ");

  /* Add momentlist */
  sprintf(MlCommand, "--momentlist='%s'", Momentlist);
  strcat(Command, MlCommand);
  strcat(Command, " ");

  /* Add datamoments */
  sprintf(DMCommand, "--datamoments='%s'", Datamoments);
  strcat(Command, DMCommand);
  strcat(Command, " ");

  /* Add gmm_weight_matrix */
  sprintf(GMWCommand, "--gmm_weight_matrix='%s'", Gmmweightmatrix);
  strcat(Command, GMWCommand);
  strcat(Command, " ");


  printf("Running command: %s\n", Command);
  
  Energy = INFINITY;
  FP = popen(Command, "r");
  while (fgets(CommandOut, sizeof CommandOut, FP))
  {
    if (strstr(CommandOut, "Hey Dad") != NULL)
    {
      EnPtr = strstr(CommandOut, "Energy=");
      if (EnPtr != NULL)
      {
	if (sscanf(EnPtr + 7, "%lf", &Energy) == 1)
	{
	  printf("Found energy: %f\n", Energy);
	  pclose(FP);
	  break;
	}
      }
    }
  }
  return Energy;
}

/*
 * SolveStep -
 *	
 *	Modify a random part of the model in a random way,
 *	bounded (for efficiency) by the Min and Max values
 *	for each value in the model.
 *
 *	StepSize is passed through from the Params supplied
 *	to the call to gsl_siman_solve, and is not currently
 *	used.
 */

void SolveStep(const gsl_rng *Rand, void *xp, double StepSize)
{
  double *Model = (double *) xp;

  int 	 i;
  double LowBound;
  double HighBound;
  double OldValue;
  double NewValue;

  /* Choose a part of the model */
  i = gsl_rng_get(Rand) % MODEL_VALUE_COUNT;
  
  /* Get current value */
  OldValue = Model[i];

  /* Compute upper and lower bounds on new value */
  LowBound  = fmax(OldValue * (1.0 - STEP_ALPHA), ModelValueMin[i]);
  HighBound = fmin(OldValue * (1.0 + STEP_ALPHA), ModelValueMax[i]);

  /* Compute new random value between LowBound and HighBound */
  NewValue = LowBound + (gsl_rng_uniform(Rand) * (HighBound - LowBound));

  /* Update the model */
  Model[i] = NewValue;
  
  /* Trace steps for debugging */
  printf("SolveStep: Updated [%d] from %f to %f, range=%f-%f, min/max=%f/%f\n",
	 i, OldValue, NewValue, LowBound, HighBound, ModelValueMin[i], ModelValueMax[i]);
}

/*
 * SolvePrint -
 */

void SolvePrint(void *xp)
{
  double *Model = (double *) xp;
  PrintModel("SolvePrint", Model);
}

/*
 * SolveMetric -
 *
 *	GSL 1.15 doesn't call this function.
 */

double	SolveMetric(void *xp, void *yp)
{ 
 printf("SolveMetric: How did you get here?\n");
  return 0.0;
}

int ModelNameIndex(char *ModelValueName)
{
  int i;
  for (i = 0; i < MODEL_VALUE_COUNT; i++)
  {
    if (strncmp(ModelValueName, ModelValueNames[i], strlen(ModelValueNames[i])) == 0)
    {
      return i;
    }
  }
  return -1;
}