wanlinksolve.cc 24.5 KB
Newer Older
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1
2
/*
 * EMULAB-COPYRIGHT
3
 * Copyright (c) 2000-2003 University of Utah and the Flux Group.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
4
5
6
 * All rights reserved.
 */

Chad Barb's avatar
 
Chad Barb committed
7
8
/**** 
 wanlinksolve - 
Chad Barb's avatar
Chad Barb committed
9
10
11
 Resilient Overlay Network 
 Reasonably Effective Algorithm for Genetically Assigning Nodes.

Chad Barb's avatar
 
Chad Barb committed
12
13
 Chad Barb, May 3, 2002

Chad Barb's avatar
Chad Barb committed
14
 Applies a standard genetic algorithm (with crossover and elitism)
Chad Barb's avatar
 
Chad Barb committed
15
16
17
18
 to solve the problem of mapping a smaller "virtual" graph
 into a larger "physical" graph, such that the actual 
 weights between acquired nodes are similar to desired weights.

Chad Barb's avatar
Chad Barb committed
19
 The penalty function is the sum of error square roots (for the first dimension).
Chad Barb's avatar
 
Chad Barb committed
20
21
22
23

 For the application this was designed for,
 "weights" are values of latency time in milliseconds.

Chad Barb's avatar
Chad Barb committed
24
 switches: 
Chad Barb's avatar
Chad Barb committed
25
26
   -v     Extra verbosity
   -v -v  Jumbo verbosity 
Chad Barb's avatar
Chad Barb committed
27

Chad Barb's avatar
Chad Barb committed
28
29
30
31
   -1 <weight>
       Multiply penalty for latency by <weight>.
       (optional, default weight is 1.0)

Chad Barb's avatar
Chad Barb committed
32
   -2 <weight>
Chad Barb's avatar
Chad Barb committed
33
       Solve for 2nd (bandwidth) dimension;
Chad Barb's avatar
Chad Barb committed
34
35
36
37
38
       Penalty for error is sum of differences of natural logs,
       multiplied by <weight>.
       A good weight seems to be around 7, but the appropriate
       value is pretty much application-dependent.

Chad Barb's avatar
Chad Barb committed
39
40
41
42
43
44
   -3 <weight>
       Solve for 3rd (loss) dimension
       Penalty for error is difference of %% (10 * percent) loss,
       multiplied by <weight>.
       -2 must be specified first.

Chad Barb's avatar
Chad Barb committed
45
46
47
   -m <plexpenalty>
       Handle multiple virtual->physical mapping.
       For each vnode beyond 1 assigned to a pnode, <plexpenalty> will be assessed.
Chad Barb's avatar
   
Chad Barb committed
48
49
50
       Asks for 'p' lines of input, with the maximum number of virtual
       nodes allowed on a given physical node, per line (See below)

Chad Barb's avatar
Chad Barb committed
51
52
53
   -s <seed>
       Use a specific random seed.

Chad Barb's avatar
Chad Barb committed
54
55
   -r <roundswobetter>
       Specify the number of rounds to continue going without a better solution.
Chad Barb's avatar
Chad Barb committed
56
57
58
59
60
       default: DEFAULT_ROUNDS

   -R <maxrounds>
       Specify the absolute maximum number of rounds.
       default: -1 (infinite)
Chad Barb's avatar
 
Chad Barb committed
61
62
63
64
65
66
67

 takes input from stdin, outputs to stdout.

 input format:

 * One line containing a single number 'p'-- the number of physical nodes.
 * 'p' lines containing the name of each physical node
Chad Barb's avatar
   
Chad Barb committed
68
69
 ? 'p' lines containing the maximum number of virtual nodes each 
       physical node can accommodate. ('-m' switch only)
Chad Barb's avatar
 
Chad Barb committed
70
71
72
 * 'p' lines each containing 'p' space-delimited numbers;
       this is a P x P matrix of the _actual_ weight from pnodes to 
       pnodes. For latencies, there are zeros along the diagonal.
Chad Barb's avatar
Chad Barb committed
73
 ? 'p' lines, a P x P matrix of actual bandwidth ('-2' switch only)
Chad Barb's avatar
Chad Barb committed
74
 ? 'p' lines, a P x P matrix of actual loss ('-3' switch only)
Chad Barb's avatar
Chad Barb committed
75

Chad Barb's avatar
 
Chad Barb committed
76
77

 * One line containing a single number 'v'-- the number of virtual nodes.
Chad Barb's avatar
   
Chad Barb committed
78
 * 'v' lines containing the name of each virtual node.
Chad Barb's avatar
Chad Barb committed
79
80
       appending a space then the name of a physical node will permanently
       "fix" the mapping of this vnode to the named pnode.
Chad Barb's avatar
 
Chad Barb committed
81
82
83
84
85
86
 * 'v' lines each containing 'v' space delimited numbers;
       this is a V x V matrix of the _desired_ weight between vnodes.
       '-1's indicate "don't care"s.. (e.g. for the weight between two
       not-connected vnodes.) 
       If link weights are symmetrical, this matrix will be its own
       transpose (symmetric over the diagonal.)
Chad Barb's avatar
Chad Barb committed
87
 ? 'v' lines, a V x V matrix of desired bandwidth ('-2' switch only)
Chad Barb's avatar
Chad Barb committed
88
 ? 'v' lines, a V x V matrix of desired loss ('-3' switch only)
Chad Barb's avatar
 
Chad Barb committed
89
90
91
92

 output format:
 
 Easily inferred. Note that the perl regexp:
Chad Barb's avatar
Chad Barb committed
93
 /(\S+)\smapsTo\s(\S+)/
Chad Barb's avatar
 
Chad Barb committed
94
 will grab vnode to pnode mappings (in $1 and $2, respectively.)
Chad Barb's avatar
Chad Barb committed
95
96
97
98
99
100
101
102
103
104


 Some references on GA's:

 Goldberg 89
    D. E. Goldberg. Genetic Algorithms in Search, Optimization, and Machine Learning. Addison-Wesley, Reading, MA, 1989.

 Holland 75
    J. Holland. Adaptation In Natural and Artificial Systems. The University of Michigan Press, Ann Arbour, 1975.

Chad Barb's avatar
 
Chad Barb committed
105
106
107
108
109
 
****/

#include <stdio.h>
#include <stdlib.h>
Chad Barb's avatar
Chad Barb committed
110
111
#include <stdarg.h>
#include <unistd.h>
Chad Barb's avatar
Chad Barb committed
112
#include <assert.h>
Chad Barb's avatar
 
Chad Barb committed
113
#include <math.h>
114
115
116
#include <sys/types.h>
#include <sys/time.h>
#include <sys/resource.h>
Chad Barb's avatar
 
Chad Barb committed
117
118
119
120
121

// To keep things lightweight, 
// structures are statically sized to
// accommodate up to MAX_NODES nodes.
// These could be changed to STL vectors in the future.
122
123
#define MAX_PNODES 256
#define MAX_VNODES 64
Chad Barb's avatar
Chad Barb committed
124
#define MAX_DIMENSIONS 3
Chad Barb's avatar
Chad Barb committed
125

126
127
// default rounds to keep going without finding a better solution.
#define DEFAULT_ROUNDS 512
Chad Barb's avatar
 
Chad Barb committed
128
129

// The size of our "population."
Chad Barb's avatar
Chad Barb committed
130
// (number of phenotypes)
131
#define SOLUTIONS 400
Chad Barb's avatar
 
Chad Barb committed
132

Chad Barb's avatar
Chad Barb committed
133
// The probability a given child will mutate (out of 1000)
134
135
//#define MUTATE_PROB 40
#define MUTATE_PROB 10
Chad Barb's avatar
 
Chad Barb committed
136

Chad Barb's avatar
Chad Barb committed
137
138
// probability crossover will happen (out of 1000)
#define CROSSOVER_PROB 700
Chad Barb's avatar
 
Chad Barb committed
139
140
141
142
143
144
145
146
147
148
149
150

// A score below Epsilon means we've found a perfect solution,
// so stop immediately.
#define EPSILON 0.0001f

// lets STL it up a notch.
#include <map>
#include <string>

// BAM!
using namespace std;

Chad Barb's avatar
Chad Barb committed
151
// some code to enable when the solver wedges and we don't know why.
Chad Barb's avatar
Chad Barb committed
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
#ifdef DEBUG
int wedgecount;
static inline void BEGIN_LOOP() { wedgecount = 0; } 
static inline void IN_LOOP_hlp( int line ) 
{ 
  ++wedgecount;
  if (wedgecount == 66666) { 
    printf( "possibly wedged in line %i.\n", line );
    assert(false);
  }
}
#define IN_LOOP() IN_LOOP_hlp(__LINE__)
#else

#define BEGIN_LOOP()
#define IN_LOOP()

#endif

Chad Barb's avatar
 
Chad Barb committed
171
172
// keep track of user names for nodes.
static map< int, string > pnodeNames;
Chad Barb's avatar
   
Chad Barb committed
173
static map< string, int > reversePNodeNames;
Chad Barb's avatar
 
Chad Barb committed
174
175
176
177
static map< int, string > vnodeNames;

static int pnodes, vnodes;

178
179
static int pLatency[MAX_DIMENSIONS][MAX_PNODES][MAX_PNODES];
static int vDesiredLatency[MAX_DIMENSIONS][MAX_VNODES][MAX_VNODES];
Chad Barb's avatar
Chad Barb committed
180

Chad Barb's avatar
Chad Barb committed
181
static float plexPenalty = 0.0f;
182
static int maxplex[MAX_PNODES];
Chad Barb's avatar
   
Chad Barb committed
183
184
static int userSpecifiedMultiplex = 0;

185
static int fixed[MAX_VNODES];
Chad Barb's avatar
   
Chad Barb committed
186

Chad Barb's avatar
Chad Barb committed
187
static int dimensions;
Chad Barb's avatar
Chad Barb committed
188
static float d1weight, d2weight, d3weight;
Chad Barb's avatar
Chad Barb committed
189
190
191
192

static int verbose = 0;

static int minrounds, maxrounds;
Chad Barb's avatar
 
Chad Barb committed
193

194
195
static bool himutate = false;

Chad Barb's avatar
 
Chad Barb committed
196
197
198
class Solution
{
public:
Chad Barb's avatar
Chad Barb committed
199
  // the beef, as it were.
200
  int vnode_mapping[MAX_VNODES];
Chad Barb's avatar
Chad Barb committed
201
202
203
204

  // Keep around a list of how many times each physical node is used
  // in this solution, rather than recomputing it each time it is needed
  // (which is often.)
205
  unsigned char pnode_uses[MAX_PNODES];
Chad Barb's avatar
Chad Barb committed
206

Chad Barb's avatar
Chad Barb committed
207
  // calculated penalty
Chad Barb's avatar
 
Chad Barb committed
208
  float error;
Chad Barb's avatar
Chad Barb committed
209
210
211

  // probability of selecting this particular one (or any before it)
  // out of MAXINT
212
  unsigned int prob;
Chad Barb's avatar
 
Chad Barb committed
213
214
};

Chad Barb's avatar
Chad Barb committed
215
216
217
// the population pool.
// at any one time, one of these is the "current" pool (where the parents come from)
// and one is the "next" pool (where the children go)
Chad Barb's avatar
 
Chad Barb committed
218
static Solution pool[SOLUTIONS];
219
static Solution pool2[SOLUTIONS];
Chad Barb's avatar
 
Chad Barb committed
220

Chad Barb's avatar
Chad Barb committed
221
222
const char dimName[3][12] = { "latency", "bandwidth", "loss" };

Chad Barb's avatar
Chad Barb committed
223
// determines probabilities of selecting each solution.
224
static inline void prepick( Solution * currentPool )
Chad Barb's avatar
 
Chad Barb committed
225
{
226
227
228
229
230
231
232
  float totalFitness = 0.0f;
  int i;

  for (i = 0; i < SOLUTIONS; i++) {
    totalFitness += 1.0f / currentPool[i].error;
  }

233
  unsigned int probsofar = 0;
234
  for (i = 0; i < SOLUTIONS; i++) {
235
236
    probsofar += (unsigned int)(((float)0xFFFFFFFF / currentPool[i].error) / totalFitness);
    currentPool[i].prob = probsofar;
237
  }
238
239

  currentPool[SOLUTIONS - 1].prob = 0xFFFFFFFF;
240
241
}

242
243
// optimized to 1. not use fp 2. use a binary search, rather than a linear one.
// win: according to gprof, was taking 75% of the total time, now takes 17%.
244
245
static inline int pickABest( Solution * currentPool )
{
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
  unsigned int x = rand();

  int lo = 0;
  int hi = SOLUTIONS;
  int mid;

  while (1) {
    mid = (hi + lo) / 2;
    if (x <= currentPool[mid].prob) { 
      if (mid == 0 || x > currentPool[mid - 1].prob) break; 
      hi = mid; 
    } else { 
      lo = mid; 
    }
  } 
261

262
263
  return mid;
  /*
264
265
  int i = 0;
  while (1) { 
266
    if (x < currentPool[i].prob) break;
267
    i++;
268
    if (i == SOLUTIONS) { printf("Ick.\n"); i = 0; break;}
269
270
  }
  return i - 1;
271
  */
272
273
}

274

Chad Barb's avatar
Chad Barb committed
275
// uses a template to avoid massive numbers
Chad Barb's avatar
 
Chad Barb committed
276
277
// of "if" choices.. compiler should generate two versions,
// one with dump and one without.
Chad Barb's avatar
   
Chad Barb committed
278
279
280
// returns 'true' if solution is free of invalidities 
// (e.g. no unusable links are used,)
// 'false' if invalid.
Chad Barb's avatar
 
Chad Barb committed
281
template <bool verbose>
Chad Barb's avatar
   
Chad Barb committed
282
static inline bool calcError( Solution * t )
Chad Barb's avatar
 
Chad Barb committed
283
{ 
Chad Barb's avatar
   
Chad Barb committed
284
  bool valid = true;
Chad Barb's avatar
 
Chad Barb committed
285
286
287
288
289
290
  float err = 0.0f;

  if (verbose) {
    printf("Error listing:\n");
  }

Chad Barb's avatar
Chad Barb committed
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
  if (userSpecifiedMultiplex) {
    for (int x = 0; x < pnodes; x++) {
      if (t->pnode_uses[x] > 1) { 
	float errDelta = (float)(t->pnode_uses[x] - 1) * plexPenalty;
	if (verbose) {
	  printf("%i nodes multiplexed on physical node %s, (err [(vnodes - 1) * plexPenalty] %4.3f)\n",
		 t->pnode_uses[x],
		 pnodeNames[x].c_str(),
		 errDelta );
	}
	err += errDelta;
      }
    }
  }

Chad Barb's avatar
 
Chad Barb committed
306
  {
Chad Barb's avatar
Chad Barb committed
307
308
309
310
311
    for (int z = 0; z < dimensions; z++) {
      for (int x = 0; x < vnodes; x++) {
	for (int y = 0; y < vnodes; y++) {
	  int should = vDesiredLatency[z][x][y];
	  if (should != -1) {
Chad Barb's avatar
   
Chad Barb committed
312
	    int is     = pLatency[z][ t->vnode_mapping[x] ][ t->vnode_mapping[y] ];
313
314
	    if (is == -1) {
	      if (verbose) {
Chad Barb's avatar
   
Chad Barb committed
315
		printf("%s -> %s link nonexistant! Super-icky penality of 100000 assessed.\n",
316
317
		       vnodeNames[x].c_str(), vnodeNames[y].c_str() ); 
	      }
Chad Barb's avatar
   
Chad Barb committed
318
319
	      err += 100000.0f;
	      valid = false;
320
	    } else if (should != is) { 
Chad Barb's avatar
Chad Barb committed
321
322
323
	      float errDelta;

	      if (z == 0) {
Chad Barb's avatar
Chad Barb committed
324
325
		errDelta = d1weight * sqrtf((float)(abs(should - is)));
	      } else if (z == 1) {
Chad Barb's avatar
Chad Barb committed
326
		errDelta = d2weight * (float)(abs(should - is));
Chad Barb's avatar
Chad Barb committed
327
		if (should < is) { errDelta *= 0.5f; }
Chad Barb's avatar
Chad Barb committed
328
329
	      } else {
		errDelta = d3weight * (float)(abs( should - is ));
Chad Barb's avatar
Chad Barb committed
330
331
332
333
	      }

	      if (verbose) {
		if (z == 0) {
Chad Barb's avatar
Chad Barb committed
334
		  printf("%s -> %s latency (ms) should be %i; is %i (err [wt * sqrt |a-b|] %4.3f)\n", 
Chad Barb's avatar
Chad Barb committed
335
336
			 vnodeNames[x].c_str(), vnodeNames[y].c_str(), 
			 should, is, errDelta );
Chad Barb's avatar
Chad Barb committed
337
		} else if (z == 1) {
Chad Barb's avatar
Chad Barb committed
338
		  printf("%s -> %s bandwidth (kB/s) should be ~%i; is ~%i (err [wt %s* ln (a/b)] %4.3f)\n", 
Chad Barb's avatar
Chad Barb committed
339
340
341
			 vnodeNames[x].c_str(), vnodeNames[y].c_str(), 
			 (int)expf((float)should / 1000.0f), 
			 (int)expf((float)is / 1000.0f),
Chad Barb's avatar
Chad Barb committed
342
			 (should < is) ? "* 0.5 " : "",
Chad Barb's avatar
Chad Barb committed
343
			 errDelta );
Chad Barb's avatar
Chad Barb committed
344
345
346
347
348
349
		} else {
		  printf("%s -> %s loss should be %1.4f; is %1.4f (err [wt * |a-b|] %4.3f)\n",
			 vnodeNames[x].c_str(), vnodeNames[y].c_str(), 			 
			 (float)should / 65536.0f,
			 (float)is / 65536.0f,
			 errDelta );
Chad Barb's avatar
Chad Barb committed
350
351
352
		}
	      }
	      err += errDelta;
Chad Barb's avatar
 
Chad Barb committed
353
354
355
356
357
358
359
	    }
	  }
	}
      }
    }
  }

Chad Barb's avatar
Chad Barb committed
360
  if (verbose) { printf("error of %4.3f\n", err ); }
Chad Barb's avatar
 
Chad Barb committed
361
  t->error = err;
Chad Barb's avatar
   
Chad Barb committed
362
363

  return valid;
Chad Barb's avatar
 
Chad Barb committed
364
365
366
367
368
369
370
371
372
373
374
375
} 

static int compar( const void * a , const void * b )
{
  Solution * sa = (Solution *)a;
  Solution * sb = (Solution *)b;

  if (sa->error > sb->error) { return  1; } else
  if (sa->error < sb->error) { return -1; } else
  { return 0; }
}

376
static inline void sortByError( Solution * t )
Chad Barb's avatar
 
Chad Barb committed
377
378
{
  // Ahh.. sweet, sweet qsort.
379
  qsort( t, SOLUTIONS, sizeof( Solution ), compar );
Chad Barb's avatar
 
Chad Barb committed
380
381
382
383
384
385
386
}

// "Mutating" is swapping what vnode a pnode maps to in
// the solution with what vnode a different pnode maps to.
// (if both are -1, e.g. not mapped to vnodes, nothing happens.)
static inline void mutate( Solution * t )
{
Chad Barb's avatar
Chad Barb committed
387
  BEGIN_LOOP();
Chad Barb's avatar
 
Chad Barb committed
388
  while(1) {
Chad Barb's avatar
Chad Barb committed
389
    IN_LOOP();
Chad Barb's avatar
 
Chad Barb committed
390
    // forecast calls for a 1% chance of mutation...
391
    if ((rand() % 1000) > (himutate ? 500 : MUTATE_PROB)) { break; }
Chad Barb's avatar
Chad Barb committed
392
393
394
395
    
    if ((rand() % 3)) {
      // swap mutation. 
      int a, b;
Chad Barb's avatar
Chad Barb committed
396
397

      BEGIN_LOOP();
Chad Barb's avatar
Chad Barb committed
398
      do {
Chad Barb's avatar
Chad Barb committed
399
	IN_LOOP();
Chad Barb's avatar
Chad Barb committed
400
	a = rand() % vnodes;
Chad Barb's avatar
Chad Barb committed
401
402
403
404
405
      } while (fixed[a] != -1);

      BEGIN_LOOP();
      do {
	IN_LOOP();
Chad Barb's avatar
Chad Barb committed
406
	b = rand() % vnodes;
Chad Barb's avatar
Chad Barb committed
407
408
409
410
411
412
413
      } while (fixed[b] != -1);

      if (a != b) {
	int temp = t->vnode_mapping[a];
	t->vnode_mapping[a] = t->vnode_mapping[b];
	t->vnode_mapping[b] = temp;
      }
Chad Barb's avatar
Chad Barb committed
414
415
416
417
418
    } else {
      // reassign mutation

      int a, b;
      // find which vnode to remap
Chad Barb's avatar
Chad Barb committed
419
      BEGIN_LOOP();
Chad Barb's avatar
Chad Barb committed
420
      do {
Chad Barb's avatar
Chad Barb committed
421
	IN_LOOP();
Chad Barb's avatar
Chad Barb committed
422
423
424
425
426
427
428
	a = rand() % vnodes;
      } while (fixed[a] != -1);

      // de-map it.
      --t->pnode_uses[ t->vnode_mapping[a] ];

      // now find a suitable physical node.
Chad Barb's avatar
Chad Barb committed
429
      BEGIN_LOOP();
Chad Barb's avatar
Chad Barb committed
430
      do {
Chad Barb's avatar
Chad Barb committed
431
	IN_LOOP();
Chad Barb's avatar
Chad Barb committed
432
433
434
435
436
437
438
	b = rand() % pnodes;
      } while (t->pnode_uses[b] >= maxplex[b]);

      // now map it.
      t->vnode_mapping[a] = b;
      ++t->pnode_uses[b];
    }
Chad Barb's avatar
 
Chad Barb committed
439
440
441
442
443
444
445
446
  }
}

// TODO: make sure that failed matings don't happen too
// often for difficult graphs.
// (perhaps have a limited retry)
static inline void splice( Solution * t, Solution * a, Solution * b)
{
Chad Barb's avatar
Chad Barb committed
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
  if ((rand() % 1000) > CROSSOVER_PROB) {
    if (rand() % 2) {
      for (int x = 0; x < vnodes; x++) {
	t->vnode_mapping[x] = a->vnode_mapping[x];
      }
      for (int y = 0; y < vnodes; y++) {
	t->pnode_uses[y] = a->pnode_uses[y];
      }
    } else {
      for (int x = 0; x < vnodes; x++) {
	t->vnode_mapping[x] = b->vnode_mapping[x];
      }
      for (int y = 0; y < vnodes; y++) {
	t->pnode_uses[y] = b->pnode_uses[y];
      }
Chad Barb's avatar
 
Chad Barb committed
462
    }
Chad Barb's avatar
Chad Barb committed
463
  } else {
Chad Barb's avatar
 
Chad Barb committed
464

Chad Barb's avatar
Chad Barb committed
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
    bzero( t->pnode_uses, sizeof( t->pnode_uses ) );
    
    for (int i = 0; i < vnodes; i++) {
      if (fixed[i] != -1) {
	t->vnode_mapping[i] = fixed[i];
	++t->pnode_uses[ fixed[i] ];
      }
    }
    
    // go through each mapping, and pick randomly
    // which one of the two parents' mappings the child
    // will inherit.
    // Inherit the one that makes sense if the other would
    // conflict with a previously chosen mapping.
    // If both would conflict with a previously chosen mapping.
    // its a failed mating, and we return.
    
    int pos = rand() % vnodes;
    for (int i = 0; i < vnodes; i++) {
      pos = (pos + 1) % vnodes;
      if (fixed[pos] != -1) continue;
      if (rand() % 2) {
	if (t->pnode_uses[ a->vnode_mapping[pos] ] < maxplex[ a->vnode_mapping[pos] ]) {
	  t->vnode_mapping[pos] = a->vnode_mapping[pos];
	  ++t->pnode_uses[ a->vnode_mapping[pos] ];
Chad Barb's avatar
 
Chad Barb committed
490
	} else {
Chad Barb's avatar
Chad Barb committed
491
492
493
494
495
496
497
498
499
500
501
502
	  if (t->pnode_uses[ b->vnode_mapping[pos] ] < maxplex[ b->vnode_mapping[pos] ]) {
	    t->vnode_mapping[pos] = b->vnode_mapping[pos];
	    ++t->pnode_uses[ b->vnode_mapping[pos] ];
	  } else {
	    // failed mating (asexually clone a parent)
	    for (int x = 0; x < vnodes; x++) {
	      t->vnode_mapping[x] = a->vnode_mapping[x];
	    }
	    for (int y = 0; y < vnodes; y++) {
	      t->pnode_uses[y] = a->pnode_uses[y];
	    }
	    break;
503
	  }
Chad Barb's avatar
 
Chad Barb committed
504
505
	}
      } else {
Chad Barb's avatar
Chad Barb committed
506
507
508
	if (t->pnode_uses[ b->vnode_mapping[pos] ] < maxplex[ b->vnode_mapping[pos] ]) {
	  t->vnode_mapping[pos] = b->vnode_mapping[pos];
	  ++t->pnode_uses[ b->vnode_mapping[pos] ];
Chad Barb's avatar
 
Chad Barb committed
509
	} else {
Chad Barb's avatar
Chad Barb committed
510
511
512
513
514
515
516
517
518
519
520
521
	  if (t->pnode_uses[ a->vnode_mapping[pos] ] < maxplex[ a->vnode_mapping[pos] ]) {
	    t->vnode_mapping[pos] = a->vnode_mapping[pos];
	    ++t->pnode_uses[ a->vnode_mapping[pos] ];
	  } else {
	    // failed mating (asexually clone a parent)
	    for (int x = 0; x < vnodes; x++) {
	      t->vnode_mapping[x] = b->vnode_mapping[x];
	    }
	    for (int y = 0; y < vnodes; y++) {
	      t->pnode_uses[y] = b->pnode_uses[y];
	    }
	    break;
522
	  }
Chad Barb's avatar
 
Chad Barb committed
523
524
525
526
527
528
529
530
531
532
533
534
535
	}
      }
    }
  }

  mutate( t );
  calcError<false>( t );  
} 

// Generate a random solution 
// for the initial population.
static inline void generateRandomSolution( Solution * t )
{
Chad Barb's avatar
Chad Barb committed
536
  bzero( t->pnode_uses, sizeof( t->pnode_uses ) );
Chad Barb's avatar
   
Chad Barb committed
537
538
539
540

  for (int i = 0; i < vnodes; i++) {
    if (fixed[i] != -1) {
      t->vnode_mapping[i] = fixed[i];
Chad Barb's avatar
Chad Barb committed
541
      ++t->pnode_uses[ fixed[i] ];
Chad Barb's avatar
 
Chad Barb committed
542
543
    }
  }
Chad Barb's avatar
   
Chad Barb committed
544
545
546
547

  for (int i = 0; i < vnodes; i++) {
    if (fixed[i] == -1) {
      int x;
Chad Barb's avatar
Chad Barb committed
548
      BEGIN_LOOP();
Chad Barb's avatar
   
Chad Barb committed
549
      do {
Chad Barb's avatar
Chad Barb committed
550
	IN_LOOP();
Chad Barb's avatar
   
Chad Barb committed
551
	x = rand() % pnodes;
Chad Barb's avatar
Chad Barb committed
552
553
      } while( t->pnode_uses[x] >= maxplex[x] );
      ++t->pnode_uses[x];
Chad Barb's avatar
   
Chad Barb committed
554
555
556
557
      t->vnode_mapping[i] = x;
    }
  }

Chad Barb's avatar
 
Chad Barb committed
558
559
560
  calcError<false>( t );
}

Chad Barb's avatar
Chad Barb committed
561
void usage( char * appname )
Chad Barb's avatar
 
Chad Barb committed
562
{
Chad Barb's avatar
Chad Barb committed
563
564
  fprintf(stderr,
	  "Usage:\n"
Chad Barb's avatar
Chad Barb committed
565
566
	  "%s [-v [-v]] [-m <penalty>] [-s <seed>] [-1 <weight>]\n"
	  "\t[-2 <weight> [-3 <weight>]] [-r <minrounds>] [-R <maxrounds>]\n\n"
Chad Barb's avatar
Chad Barb committed
567
	  "  -v              extra verbosity\n"
Chad Barb's avatar
Chad Barb committed
568
	  "  -v -v           jumbo verbosity\n"
Chad Barb's avatar
Chad Barb committed
569
570
	  "  -m <penalty>    enable many-to-one virtual to physical mappings\n"
	  "  -s <seed>       seed the random number generator with a specific value\n"
Chad Barb's avatar
Chad Barb committed
571
	  "  -1 <weight>     assign weight to latency penalty (optional; default 1.0)\n"
Chad Barb's avatar
Chad Barb committed
572
573
	  "  -2 <weight>     enable solving for bandwidth;\n"
	  "                  multiply bandwidth penalties by <weight>.\n"
Chad Barb's avatar
Chad Barb committed
574
575
	  "  -3 <weight>     enable solving for loss.\n"
	  "                  (must specify -2 first)\n"
Chad Barb's avatar
Chad Barb committed
576
	  "  -r <minrounds>  number of rounds to go without a solution before stopping\n"
Chad Barb's avatar
Chad Barb committed
577
578
579
	  "                  default: %i\n"
	  "  -R <maxrounds>  set maximum rounds\n"
	  "                  default: infinite (-1)\n\n", appname, DEFAULT_ROUNDS );
Chad Barb's avatar
Chad Barb committed
580
  exit(1);
Chad Barb's avatar
Chad Barb committed
581
582
}

583
584
585
586
587
588
589
590
591
592
unsigned int msecscpu()
{
  struct rusage r;

  getrusage( 0, &r );

  return r.ru_utime.tv_sec * 1000 + 
         r.ru_utime.tv_usec / 1000;
}

Chad Barb's avatar
Chad Barb committed
593
594
int main( int argc, char ** argv )
{
Chad Barb's avatar
   
Chad Barb committed
595
  unsigned int seed = 1;
Chad Barb's avatar
Chad Barb committed
596
597
  int available = 0;
  int fixedNodeCount = 0;
598
  unsigned int bestSpeed = 0;
Chad Barb's avatar
Chad Barb committed
599

Chad Barb's avatar
Chad Barb committed
600
601
  verbose = 0;
  dimensions = 1;
Chad Barb's avatar
Chad Barb committed
602
  d1weight = 1.0f;
Chad Barb's avatar
Chad Barb committed
603
  d2weight = 1.0f / 1000.0f;
Chad Barb's avatar
Chad Barb committed
604
  d3weight = 1.0f / 65536.0f;
Chad Barb's avatar
Chad Barb committed
605
606
607
608
609
610

  minrounds = DEFAULT_ROUNDS;
  maxrounds = -1;

  int ch;

Chad Barb's avatar
   
Chad Barb committed
611
612
613
614
615
616
617
  { 
    struct timeval tp;
    if ( 0 == gettimeofday( &tp, NULL )) {
      seed = ((unsigned int)tp.tv_sec << 6) + (unsigned int)tp.tv_usec;
    }
  }

Chad Barb's avatar
Chad Barb committed
618
  while ((ch = getopt(argc, argv, "v1:2:3:r:R:s:m:")) != -1) {
Chad Barb's avatar
Chad Barb committed
619
    switch (ch) {
Chad Barb's avatar
Chad Barb committed
620
    case 's':
Chad Barb's avatar
   
Chad Barb committed
621
      seed = atoi( optarg );
Chad Barb's avatar
Chad Barb committed
622
      break;
Chad Barb's avatar
Chad Barb committed
623
624
625
    case 'v': 
      verbose++; 
      break;
Chad Barb's avatar
   
Chad Barb committed
626
    case 'm':
Chad Barb's avatar
Chad Barb committed
627
      plexPenalty = atof( optarg );
Chad Barb's avatar
   
Chad Barb committed
628
629
      userSpecifiedMultiplex++;
      break;
Chad Barb's avatar
Chad Barb committed
630
631
632
    case '1':
      d1weight = atof( optarg );
      break;
Chad Barb's avatar
Chad Barb committed
633
634
635
636
    case '2': 
      dimensions = 2;
      d2weight = atof( optarg ) / 1000.0f; 
      break;
Chad Barb's avatar
Chad Barb committed
637
638
639
640
641
642
643
644
645
    case '3':
      if (dimensions != 2) {
	fprintf(stderr, "Must specify -2 option first when using -3.\n");
	exit(1);
      } else {
	dimensions = 3;
	d3weight = atof( optarg ) / 65536.0f;
      }
      break;
Chad Barb's avatar
Chad Barb committed
646
647
648
649
650
651
652
653
    case 'r':
      minrounds = atoi( optarg );
      break;
    case 'R':
      maxrounds = atoi( optarg );
      break;
    default: 
      usage( argv[0] );
Chad Barb's avatar
Chad Barb committed
654
      break;
Chad Barb's avatar
Chad Barb committed
655
656
657
    }
  }

Chad Barb's avatar
   
Chad Barb committed
658
659
660
661
662
663
664
665
666
667
  if (minrounds < 0 ) { minrounds = 0; }
  if (maxrounds < 0 ) { maxrounds = -1; }

  if (d1weight < 0.0f || d2weight < 0.0f || d3weight < 0.0f /* || plexPenalty < 0.0f */) {
    fprintf(stderr, 
	    "The '-1','-2' and '-3' switches each require\n"
	    "a positive argument, or zero.\n"
	    "Negative weights are silly.\n" );
    exit(1);
  }
Chad Barb's avatar
Chad Barb committed
668

Chad Barb's avatar
   
Chad Barb committed
669
670
671
  srand( seed );
  if (verbose) { printf("Using random seed %u\n", seed ); }

672
  char line[4096];
Chad Barb's avatar
 
Chad Barb committed
673
674

  {
Chad Barb's avatar
Chad Barb committed
675
    if (verbose > 1) { printf("How many physical nodes?\n"); }
Chad Barb's avatar
Chad Barb committed
676
    fgets( line, sizeof( line ), stdin );
Chad Barb's avatar
 
Chad Barb committed
677
678
    sscanf( line, "%i", &pnodes );

679
680
681
682
683
    if (pnodes > MAX_PNODES) {
      fprintf(stderr, "Too many nodes. Increase MAX_PNODES!\n");
      exit(1);
    }

Chad Barb's avatar
Chad Barb committed
684
    if (verbose > 1) { printf("Okay, enter %i names for the physical nodes, one per line.\n", pnodes ); }
Chad Barb's avatar
 
Chad Barb committed
685
686
    for (int i = 0; i < pnodes; i++) {
      char name[1024];
Chad Barb's avatar
Chad Barb committed
687
      fgets( line, sizeof( line ), stdin );
Chad Barb's avatar
 
Chad Barb committed
688
689
      sscanf( line, "%s", name );
      pnodeNames[i] = string( name );
Chad Barb's avatar
   
Chad Barb committed
690
691
692
693
      reversePNodeNames[string(name)] = i;
    }

    if (userSpecifiedMultiplex) {
Chad Barb's avatar
Chad Barb committed
694
      if (verbose > 1) { printf("Enter %i numbers, one per line, indicating the"
Chad Barb's avatar
   
Chad Barb committed
695
696
697
			    " maximum number of virtual nodes allowed on each"
			    " physical node.\n", pnodes ); }
      for (int i = 0; i < pnodes; i++) {
Chad Barb's avatar
Chad Barb committed
698
	fgets( line, sizeof( line ), stdin );
Chad Barb's avatar
   
Chad Barb committed
699
	sscanf( line, "%i", &(maxplex[i]));
Chad Barb's avatar
Chad Barb committed
700
	available += maxplex[i];
Chad Barb's avatar
   
Chad Barb committed
701
702
703
704
      }
    } else {
      for (int i = 0; i < pnodes; i++) {
	maxplex[i] = 1;
Chad Barb's avatar
Chad Barb committed
705
	++available;
Chad Barb's avatar
   
Chad Barb committed
706
      }
Chad Barb's avatar
 
Chad Barb committed
707
708
    }

Chad Barb's avatar
Chad Barb committed
709
    for (int z = 0; z < dimensions; z++) {
Chad Barb's avatar
Chad Barb committed
710
      if (verbose > 1) {
Chad Barb's avatar
Chad Barb committed
711
	printf("Enter %ix%i grid o' actual %s.\n", pnodes, pnodes, dimName[z]);
Chad Barb's avatar
Chad Barb committed
712
713
714
      }
      for (int y = 0; y < pnodes; y++) {
	char * linePos = line;
Chad Barb's avatar
Chad Barb committed
715
	fgets( line, sizeof( line ), stdin );
Chad Barb's avatar
Chad Barb committed
716
717
	while (*linePos == ' ') { linePos++; } // skip leading whitespace
	for (int x = 0; x < pnodes; x++) {
Chad Barb's avatar
Chad Barb committed
718
	  float temp;
Chad Barb's avatar
Chad Barb committed
719
	  sscanf( linePos, "%i", &pLatency[z][x][y] );
Chad Barb's avatar
Chad Barb committed
720
	  sscanf( linePos, "%f", &temp );
721
	    if (pLatency[z][x][y] != -1) {
Chad Barb's avatar
Chad Barb committed
722
723
724
725
726
	      if (z == 1) { 
		pLatency[z][x][y] = (int)( logf(pLatency[z][x][y]) * 1000.0f ); 
	      } else if (z == 2) {
		pLatency[z][x][y] = (int)(temp * 65536.0f);
	      }
727
	  }
Chad Barb's avatar
Chad Barb committed
728
729
730
	  while (*linePos != ' ' && *linePos != '\n') { linePos++; }
	  while (*linePos == ' ') { linePos++; }
	}
Chad Barb's avatar
 
Chad Barb committed
731
732
733
734
735
      }
    }
  } 

  {
Chad Barb's avatar
Chad Barb committed
736
    if (verbose > 1) { printf("How many virtual nodes?\n"); }
Chad Barb's avatar
Chad Barb committed
737
    fgets( line, sizeof( line ), stdin );
Chad Barb's avatar
 
Chad Barb committed
738
739
    sscanf( line, "%i", &vnodes );

740
741
742
743
744
    if (vnodes > MAX_VNODES) {
      fprintf(stderr, "Too many vnodes. Increase MAX_VNODES!\n");
      exit(1);
    }

Chad Barb's avatar
Chad Barb committed
745
746
747
748
749
750
751
752
753
754
755
    if (vnodes > available) {
      fprintf(stderr, 
	      "More nodes required (%i) than can be mapped (%i).\n", 
	      vnodes, available );
      exit(2);
    }

    if (verbose > 1) { printf("Okay, enter %i names for the virtual nodes, one per line.\n"
			      "to fix a node, suffix a space then the name of the physical node.\n", 
			      vnodes ); }

Chad Barb's avatar
 
Chad Barb committed
756
757
    for (int i = 0; i < vnodes; i++) {
      char name[1024];
Chad Barb's avatar
Chad Barb committed
758
      char pname[1024];
Chad Barb's avatar
Chad Barb committed
759
      fgets( line, sizeof( line ), stdin );
Chad Barb's avatar
Chad Barb committed
760
761
      if (sscanf( line, "%s %s", name, pname ) == 2) {
	map< string, int >::iterator it = reversePNodeNames.find( string( pname ) );
Chad Barb's avatar
   
Chad Barb committed
762
	if (it == reversePNodeNames.end()) {
Chad Barb's avatar
Chad Barb committed
763
764
	  fprintf(stderr,"pnode '%s' does not exist; can't fix.\n", pname );
	  exit(3);
Chad Barb's avatar
   
Chad Barb committed
765
	}
Chad Barb's avatar
Chad Barb committed
766
767
	if (verbose > 1) { 
	  printf("Fixing assignment from vnode %s to pnode %s.\n", name, pname );
Chad Barb's avatar
   
Chad Barb committed
768
	}
Chad Barb's avatar
Chad Barb committed
769
770
	fixed[i] = reversePNodeNames[ string( pname ) ];
	fixedNodeCount++;
Chad Barb's avatar
   
Chad Barb committed
771
772
773
      } else {
	fixed[i] = -1;
      }
Chad Barb's avatar
Chad Barb committed
774
      vnodeNames[i] = string( name );
Chad Barb's avatar
 
Chad Barb committed
775
776
    }

Chad Barb's avatar
Chad Barb committed
777
    for (int z = 0; z < dimensions; z++) {
Chad Barb's avatar
Chad Barb committed
778
      if (verbose > 1) {
Chad Barb's avatar
Chad Barb committed
779
	printf("Enter %ix%i grid o' desired %s (-1 is don't care.)\n", vnodes, vnodes, 
Chad Barb's avatar
Chad Barb committed
780
	       dimName[z]);
Chad Barb's avatar
 
Chad Barb committed
781
      }
Chad Barb's avatar
Chad Barb committed
782
783
      for (int y = 0; y < vnodes; y++) {
	char * linePos = line;
Chad Barb's avatar
Chad Barb committed
784
	fgets( line, sizeof( line ), stdin );
Chad Barb's avatar
Chad Barb committed
785
786
	while (*linePos == ' ') { linePos++; } // skip leading whitespace
	for (int x = 0; x < vnodes; x++) {
Chad Barb's avatar
Chad Barb committed
787
	  float temp;
Chad Barb's avatar
Chad Barb committed
788
	  sscanf( linePos, "%i", &vDesiredLatency[z][x][y] );
Chad Barb's avatar
Chad Barb committed
789
790
791
	  sscanf( linePos, "%f", &temp );
	  if (vDesiredLatency[z][x][y] != -1) {
	    if (z == 1) { 
Chad Barb's avatar
Chad Barb committed
792
	      vDesiredLatency[z][x][y] = (int)(logf(vDesiredLatency[z][x][y]) * 1000.0f); 
Chad Barb's avatar
Chad Barb committed
793
794
	    } else if (z == 2) {
	      vDesiredLatency[z][x][y] = (int)(temp * 65536.0f);
Chad Barb's avatar
Chad Barb committed
795
796
797
798
799
800
801
802
	    }
	  }
	  while (*linePos != ' ' && *linePos != '\n') { linePos++; }
	  while (*linePos == ' ') { linePos++; }
	}
      }
    } 
  }
Chad Barb's avatar
 
Chad Barb committed
803

804
805
806
  Solution * currentPool = pool;
  Solution * nextPool = pool2;

Chad Barb's avatar
Chad Barb committed
807
808
  if (fixedNodeCount < vnodes) {
    if (verbose) { printf("Now running...\n"); }
Chad Barb's avatar
 
Chad Barb committed
809

Chad Barb's avatar
Chad Barb committed
810
811
    {
      for (int i = 0; i < SOLUTIONS; i++) {
812
	generateRandomSolution( &(currentPool[i]) );
Chad Barb's avatar
Chad Barb committed
813
      }
814
      sortByError( currentPool );
Chad Barb's avatar
 
Chad Barb committed
815
816
817
    }

    int highestFoundRound = 0;
818
819
    float last = currentPool[0].error;

820
    himutate = false;
Chad Barb's avatar
Chad Barb committed
821
    for (int i = 0; i != maxrounds && i < (highestFoundRound + minrounds); i++) {
822
823
824
825
826
827
828
829
830
831
832
833
     
      float avg = 0.0f;
      int xy;
      for (xy = 0; xy < SOLUTIONS; xy++) { avg += currentPool[xy].error; }
      avg /= (float)SOLUTIONS;
      
      float stddev = 0.0f;
      for (xy = 0; xy < SOLUTIONS; xy++) { 
	float diff = currentPool[xy].error - avg;
	stddev += diff * diff;
      }
      stddev = sqrtf(stddev / (float)(SOLUTIONS - 1));
834
      
835
      if (verbose && !(i % 100)) {
836
	printf("Round %i. (best %4.3f; avg %4.3f; sdev %4.3f)\n", i, currentPool[0].error, avg, stddev);
Chad Barb's avatar
 
Chad Barb committed
837
      }
Chad Barb's avatar
Chad Barb committed
838
      
839
      if (currentPool[0].error < last) {
Chad Barb's avatar
Chad Barb committed
840
841
	if (verbose) {
	  printf("Better solution found in round %i (error %4.3f)\n", 
842
		 i, currentPool[0].error);
Chad Barb's avatar
Chad Barb committed
843
	}
844
	bestSpeed = msecscpu();
845
	last = currentPool[0].error;
Chad Barb's avatar
 
Chad Barb committed
846
847
	highestFoundRound = i;
      }
848

Chad Barb's avatar
Chad Barb committed
849
850
      // this is "elitism" -- the best solution is guaranteed to survive.
      // (otherwise, a good solution may be found, but may be lost by the next generation.)
851
852
853
854
855
      memcpy( &(nextPool[0]), &(currentPool[0]), sizeof( Solution ) );
      prepick( currentPool );

      int j;

856
857
858
859
860
861
      // if there is not enough variety, more mutation!
      if (stddev < (avg / 10.0f)) { 
	himutate = true;
      }

      for (j = 1; j < SOLUTIONS; j++) {
862
863
864
865
866
	splice( &(nextPool[j]),
		&(currentPool[pickABest( currentPool )]),
		&(currentPool[pickABest( currentPool )]) );
      }

Chad Barb's avatar
Chad Barb committed
867
868
869
      //if (stddev < (avg / 10.0f))) {
      himutate = false;
      //}
Chad Barb's avatar
Chad Barb committed
870

871
872
873
874
875
876
877
      sortByError( nextPool );

      Solution * temp = currentPool;
      currentPool = nextPool;
      nextPool = temp;

      if (currentPool[0].error < EPSILON) { 
Chad Barb's avatar
Chad Barb committed
878
	if (verbose > 1) { printf("Found perfect solution.\n"); }
Chad Barb's avatar
 
Chad Barb committed
879
880
881
	break;
      }
    }
Chad Barb's avatar
Chad Barb committed
882
883
  } else {
    if (verbose) { printf("No non-fixed vnodes (or no vnodes at all,) so nothing to be done!\n"); }
Chad Barb's avatar
 
Chad Barb committed
884
885
886
  }

  {
Chad Barb's avatar
Chad Barb committed
887
    if (verbose) { printf("\nYour solution is as follows:\n"); }
Chad Barb's avatar
   
Chad Barb committed
888
    for (int x = 0; x < vnodes; x++) {
889
890
      if (pnodeNames.find( currentPool[0].vnode_mapping[x] ) == pnodeNames.end()) {
	pnodeNames[ currentPool[0].vnode_mapping[x] ] = "CRAP";
Chad Barb's avatar
Chad Barb committed
891
892
893
      }
      printf("%s mapsTo %s\n", 
	     vnodeNames[x].c_str(),
894
	     pnodeNames[currentPool[0].vnode_mapping[x]].c_str() );
Chad Barb's avatar
 
Chad Barb committed
895
    }
Chad Barb's avatar
   
Chad Barb committed
896

Chad Barb's avatar
 
Chad Barb committed
897
898
899
    printf("\n");

    // dump a detailed report of the returned solution's errors.
900
    if (verbose > 1) { 
Chad Barb's avatar
   
Chad Barb committed
901
902
903
904
905
906
      if (calcError<true>( &(currentPool[0]) )) {
	printf("Found in %i msecs (cpu time)\n", bestSpeed );
      } else {
	fprintf( stderr, "Solution is invalid, since it uses unavailable links.");
	exit(6);
      }
907
    }
Chad Barb's avatar
 
Chad Barb committed
908
909
  }

Chad Barb's avatar
Chad Barb committed
910
  if (verbose > 1) { printf("Bye now.\n"); }
Chad Barb's avatar
 
Chad Barb committed
911
912
  return 0;
}