assign.cc 13.7 KB
Newer Older
Mac Newbold's avatar
Mac Newbold committed
1 2
#include <LEDA/graph_alg.h>
#include <LEDA/graphwin.h>
3
#include <LEDA/ugraph.h>
Mac Newbold's avatar
Mac Newbold committed
4 5 6 7
#include <LEDA/dictionary.h>
#include <LEDA/map.h>
#include <LEDA/graph_iterator.h>
#include <LEDA/node_pq.h>
8
#include <LEDA/sortseq.h>
Mac Newbold's avatar
Mac Newbold committed
9 10 11 12 13 14 15 16 17 18 19 20 21 22
#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/time.h>
#include <string.h>
#include <assert.h>

#include "common.h"
#include "physical.h"
#include "virtual.h"
#include "score.h"

23 24 25 26
void parse_options(char **argv, struct config_param options[], int nopt);
int config_parse(char **args, struct config_param cparams[], int nparams);
void dump_options(const char *str, struct config_param cparams[], int nparams);

Mac Newbold's avatar
Mac Newbold committed
27
// Purely heuristic
28

29
#ifdef USE_OPTIMAL
Mac Newbold's avatar
Mac Newbold committed
30
#define OPTIMAL_SCORE(edges,nodes) (nodes*SCORE_PNODE + \
31
                                    nodes/opt_nodes_per_sw*SCORE_SWITCH + \
32 33
                                    edges*((SCORE_INTRASWITCH_LINK+ \
                                    SCORE_DIRECT_LINK*2)*4+\
34
                                    SCORE_INTERSWITCH_LINK)/opt_nodes_per_sw)
35
#else
36
#define OPTIMAL_SCORE(edges,nodes) 0
37
#endif
Mac Newbold's avatar
Mac Newbold committed
38

39 40 41 42 43 44 45 46
tb_sgraph SG;
edge_array<int> edge_costs;
typedef node_array<int> switch_distance_array;
typedef node_array<edge> switch_pred_array;
node_array<switch_distance_array> switch_distances;
node_array<switch_pred_array> switch_preds;
tb_pgraph PG;
tb_vgraph G;
Mac Newbold's avatar
Mac Newbold committed
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

/* How can we chop things up? */
#define PARTITION_BY_ANNEALING 0

#define MAX_DELAYS 64

int nparts = 0;     /* DEFAULTS */
int accepts = 0;
int nnodes = 0;
int partition_mechanism;
int on_line = 0;
int cycles_to_best = 0;
int batch_mode = 0;

float sensitivity = .1;

int refreshed = 0;

node_array<int> bestnodes, absnodes;
float bestscore, absbest;

extern node pnodes[MAX_PNODES];
extern node_array<int> switch_index;
node_pq<int> unassigned_nodes(G);

int parse_top(tb_vgraph &G, istream& i);
73
int parse_ptop(tb_pgraph &PG, tb_sgraph &SG, istream& i);
Mac Newbold's avatar
Mac Newbold committed
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

/*
 * Basic simulated annealing parameters:
 *
 * Make changes proportional to T
 * Accept worse solution with p = e^(change/Temperature*sensitivity)
 *
 */

inline int accept(float change, float temperature)
{
  float p;
  int r;

  if (change == 0) {
    p = 1000 * temperature / temp_prob;
  } else {
    p = expf(change/(temperature*sensitivity)) * 1000;
  }
  r = random() % 1000;
  if (r < p) {
    accepts++;
    return 1;
  }
  return 0;
}

/*
 * The workhorse of our program.
 *
 * Assign performs an assignment of the virtual nodes (vnodes) to
 * nodes in the physical topology.
 *
 * The input virtual topology is the graph G (global)
 * the input physical topology is the topology topo (global).
 *
 * The simulated annealing logic is contained herein,
 * except for the "accept a bad change" computation,
 * which is performed in accept().
 */

int assign()
{
  float newscore, bestscore;
  node n;
  int iters = 0;

  float timestart = used_time();
  float timeend;
  float scorediff;

  nnodes = G.number_of_nodes();
 
127
  float cycles = CYCLES*(float)(nnodes + G.number_of_edges());
Mac Newbold's avatar
Mac Newbold committed
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142

  float optimal = OPTIMAL_SCORE(G.number_of_edges(),nnodes);
#ifdef STATS
  cout << "STATS_OPTIMAL = " << optimal << endl;
#endif
  
  int mintrans = (int)cycles;
  int trans;
  int naccepts = 40*nnodes;
  int accepts = 0;
  int oldpos;

  int bestviolated;
  int absbestv;
  
143
  float temp = init_temp;
144 145 146 147 148 149

#ifdef VERBOSE
  cout << "Initialized to cycles="<<cycles<<" optimal="<<optimal<<" mintrans="
       << mintrans<<" naccepts="<<naccepts<<" nnodes="<<nnodes<<"\n";
#endif
  
Mac Newbold's avatar
Mac Newbold committed
150 151 152 153 154 155
  
  /* Set up the initial counts */
  init_score();

  bestscore = get_score();
  bestviolated = violated;
156 157 158 159
#ifdef VERBOSE
  cout << "Problem started with score "<<bestscore<<" and "<< violated
       << " violations.\n";
#endif
Mac Newbold's avatar
Mac Newbold committed
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
  absbest = bestscore;
  absbestv = bestviolated;
  node n3;
  forall_nodes(n3, G) {
    absnodes[n3] = G[n3].posistion;
  }

  //  if (bestscore < 0.11f) {
  if (bestscore < optimal) {
#ifdef VERBOSE
    cout << "Problem started optimal\n";
#endif
    goto DONE;
  }
  
175
  while (temp >= temp_stop) {
Mac Newbold's avatar
Mac Newbold committed
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
#ifdef VERBOSE
    cout << "Temperature:  " << temp << endl;
#endif
    trans = 0;
    accepts = 0;

    bool unassigned = true;
    while (trans < mintrans && accepts < naccepts) {
#ifdef STATS
      cout << "STATS temp:" << temp << " score:" << get_score() <<
	" violated:" << violated << " trans:" << trans <<
	" accepts:" << accepts << endl;
#endif STATS
      int newpos;
      trans++;
      iters++;

      n = unassigned_nodes.find_min();
      if (n == nil)
	n = G.choose_node();

      // Note: we have a lot of +1's here because of the first
      // node loc in pnodes is 1 not 0.
      oldpos = G[n].posistion;
      newpos = ((oldpos+(random()%(nparts-1)+1))%nparts)+1;

      if (oldpos != 0) {
	remove_node(n);
	unassigned = false;
      }

      int first_newpos = newpos;
      while (add_node(n,newpos) == 1) {
	newpos = (newpos % nparts)+1;
	if (newpos == first_newpos) {
	  // no place to put a node.
	  // instead re randomly choose a node and remove it and
	  // then continue the 'continue'
	  // XXX - could improve this
	  node ntor = G.choose_node();
	  while (G[ntor].posistion == 0)
	    ntor = G.choose_node();
	  remove_node(ntor);
	  unassigned_nodes.insert(ntor,random());
	  continue;
	}
      }
      if (unassigned) unassigned_nodes.del(n);

      newscore = get_score();

      /* So it's negative if bad */
      scorediff = bestscore - newscore;

      // tinkering aournd witht his.
      if ((newscore < optimal) || (violated < bestviolated) ||
	  ((violated == bestviolated) && (newscore < bestscore)) ||
	  accept(scorediff*((bestviolated - violated)/2), temp)) {
	bestnodes[n] = G[n].posistion;
	bestscore = newscore;
	bestviolated = violated;
	accepts++;
238
	if ((violated < absbestv) ||
Mac Newbold's avatar
Mac Newbold committed
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
	    ((violated == absbestv) &&
	     (newscore < absbest))) {
	  node n2;
	  forall_nodes(n2, G) {
	    absnodes[n2] = G[n2].posistion;
	  }
	  absbest = newscore;
	  absbestv = violated;
	  cycles_to_best = iters;
	}
	//      if (newscore < 0.11f) {
	if (newscore < optimal) {
	  timeend = used_time(timestart);
	  cout << "OPTIMAL ( " << optimal << ") in "
	       << iters << " iters, "
	       << timeend << " seconds" << endl;
	  goto DONE;
	}
      } else { /* Reject this change */
	remove_node(n);
	if (oldpos != 0) {
	  int r = add_node(n,oldpos);
	  assert(r == 0);
	}
      }
    }
      
266
    temp *= temp_rate;
Mac Newbold's avatar
Mac Newbold committed
267
  }
268 269
  cout << "Done.\n";
  
Mac Newbold's avatar
Mac Newbold committed
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
 DONE:
  forall_nodes(n, G) {
    bestnodes[n] = absnodes[n];
  }
  bestscore = absbest;

  forall_nodes(n, G) {
    if (G[n].posistion != 0)
      remove_node(n);
  }
	
  forall_nodes(n, G) {
    if (absnodes[n] != 0) {
      if (add_node(n,absnodes[n]) != 0) {
	cerr << "Invalid assumption.  Tell calfeld that reseting to best configuration doesn't work" << endl;
      }
    } else {
      cout << "Unassigned node: " << G[n].name << endl;
    }
  }
  
  timeend = used_time(timestart);
292 293
  printf("   BEST SCORE:  %.2f",get_score());
  cout << " in " << iters << " iters and " << timeend << " seconds" << endl;
Mac Newbold's avatar
Mac Newbold committed
294 295 296 297 298 299 300 301 302
  cout << "With " << violated << " violations" << endl;
  cout << "With " << accepts << " accepts of increases\n";
  cout << "Iters to find best score:  " << cycles_to_best << endl;
  cout << "Violations: " << violated << endl;
  cout << "  unassigned: " << vinfo.unassigned << endl;
  cout << "  pnode_load: " << vinfo.pnode_load << endl;
  cout << "  no_connect: " << vinfo.no_connection << endl;
  cout << "  link_users: " << vinfo.link_users << endl;
  cout << "  bandwidth:  " << vinfo.bandwidth << endl;
303
  cout << "  desires:    " << vinfo.desires << endl;
Mac Newbold's avatar
Mac Newbold committed
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

  return 0;
}

/*
 * A legacy function from a less general version of the program.
 *
 * Now simply resets the node assignment, performs a new assignment,
 * and prints out the results.
 *
 */
void loopassign()
{
  node_array<int> nodestorage;
  int optimal = 0;
  float timestart = used_time();
  float totaltime;

  nodestorage.init(G, 0);
  bestnodes.init(G, 0);
  absnodes.init(G, 0);
    
  nnodes = G.number_of_nodes();
  optimal = assign();
  totaltime = used_time(timestart);

  if (violated > 0) {
    cout << "violations: " << violated << endl;
  }
  cout << "Total time to find solution "
       << totaltime << " seconds" << endl;
}

/*
 * If we have more ways of partitioning the graph other than just
 * simulated annealing, throw them in here.
 */

void chopgraph() {
  switch(partition_mechanism) {
  case PARTITION_BY_ANNEALING:
    loopassign();
    break;
  default:
    cerr << "Unknown partition mechanism.  eeeek." << endl;
    exit(-1);
  }
}

void batch()
{
  bestnodes.init(G, 0);
  absnodes.init(G, 0);
  chopgraph();
}


void usage() {
  fprintf(stderr,
	  "usage:  assign [-h] [-bao] [-s <switches>] [-n nodes/switch] [-c cap] [file]\n"
	  "           -h ...... brief help listing\n"
	  //	  "           -s #  ... number of switches in cluster\n"
	  //	  "           -n #  ... number of nodes per switch\n"
	  "           -a ...... Use simulated annealing (default)\n"
	  "           -o ...... Update on-line (vs batch, default)\n"
	  "           -t <file> Input topology desc. from <file>\n"
	  "           -b ...... batch mode (no gui)\n"
	  );
}

374 375 376 377 378 379 380 381 382 383 384
int mst_comp(const edge &A,const edge &B)
{
  edge pA,pB;
  pA = SG[A].mate;
  pB = SG[B].mate;
  // Highbandwidth = low score
  if (PG[pA].bandwidth > PG[pB].bandwidth) return -1;
  if (PG[pA].bandwidth < PG[pB].bandwidth) return 1;
  return 0;
}

Mac Newbold's avatar
Mac Newbold committed
385 386 387 388 389 390 391 392 393 394 395
void print_solution()
{
  node n;
  cout << "Best solution: " << absbest << endl;
  cout << "Nodes:" << endl;
  forall_nodes(n,G) {
    if (!G[n].posistion) {
      cout << "unassigned: " << G[n].name << endl;
    } else {
      node pnode = pnodes[G[n].posistion];
      tb_pnode &pnoder = PG[pnode];
396 397 398 399 400 401 402
      cout << G[n].name << " ";
      if (pnoder.the_switch) {
	cout << PG[pnoder.the_switch].name;
      } else {
	cout << "NO_SWITCH";
      }
      cout << " " << pnoder.name << endl;
Mac Newbold's avatar
Mac Newbold committed
403 404 405 406 407 408 409 410 411
    }
  }
  cout << "End Nodes" << endl;
  cout << "Edges:" << endl;
  edge e;
  forall_edges(e,G) {
    tb_vlink &v = G[e];
    cout << G[e].name;
    if (v.type == tb_vlink::LINK_DIRECT) {
412 413 414
      tb_plink &p = PG[v.plink];
      cout << " direct " << p.name << " (" <<
	p.srcmac << "," << p.dstmac << ")" << endl;
Mac Newbold's avatar
Mac Newbold committed
415
    } else if (v.type == tb_vlink::LINK_INTRASWITCH) {
416 417 418 419 420
      tb_plink &p = PG[v.plink];
      tb_plink &p2 = PG[v.plink_two];
      cout << " intraswitch " << p.name << " (" <<
	p.srcmac << "," << p.dstmac << ") " <<
	p2.name << " (" << p2.srcmac << "," << p2.dstmac <<
Mac Newbold's avatar
Mac Newbold committed
421 422
	")" << endl;
    } else if (v.type == tb_vlink::LINK_INTERSWITCH) {
423 424 425 426 427 428 429 430
      cout << " interswitch ";
      edge e;
      tb_plink &lp = PG[v.plink_local_one];
      tb_plink &lp2 = PG[v.plink_local_two];
      cout << lp.name << " (" << lp.srcmac << "," << lp.dstmac << ")";
      forall(e,v.path) {
	tb_plink &p = PG[e];
	cout << " " << p.name << " (" << p.srcmac << "," << p.dstmac << ")";
Mac Newbold's avatar
Mac Newbold committed
431
      }
432 433
      cout << " " << lp2.name << " (" << lp2.srcmac << "," <<
	lp2.dstmac << ")" << endl;
Mac Newbold's avatar
Mac Newbold committed
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
    } else {
      cout << "Unknown link type" << endl;
    }
  }
  cout << "End Edges" << endl;
  cout << "End solution" << endl;
}

int main(int argc, char **argv)
{
  extern char *optarg;
  extern int optind;
  char *topofile = NULL;
    
  int ch;

  partition_mechanism = PARTITION_BY_ANNEALING;
Christopher Alfeld's avatar
Christopher Alfeld committed
451

Mac Newbold's avatar
Mac Newbold committed
452 453 454 455 456 457 458 459 460 461 462 463 464 465
  while ((ch = getopt(argc, argv, "boas:n:t:h")) != -1)
    switch(ch) {
    case 'h': usage(); exit(0);
      //		case 's': nparts = atoi(optarg); break;
    case 'a': partition_mechanism = PARTITION_BY_ANNEALING; break;
    case 'o': on_line = 1; break;
    case 't': topofile = optarg; break;
    case 'b': batch_mode = 1; break;
    default: usage(); exit(-1);
    }

  argc -= optind;
  argv += optind;

466 467 468 469 470 471 472
  /* newbold@cs
     These relate to the globals defined in common.h
     It reads in all the parameters for the program that were formerly
     all hardcoded constants.
  */
  parse_options(argv, options, noptions);
#ifdef SCORE_DEBUG
473
  dump_options("Configuration options:", options, noptions);
474 475
#endif

Mac Newbold's avatar
Mac Newbold committed
476 477 478 479 480 481 482 483 484 485 486
  int seed = time(NULL)+getpid();
  if (getenv("ASSIGN_SEED") != NULL) {
    sscanf(getenv("ASSIGN_SEED"),"%d",&seed);
  }
  printf("seed = %d\n",seed);
  srandom(seed);

  /*
   * Allow the user to specify a topology in ".top" format.
   */

487
  if (argc >= 1) {
Mac Newbold's avatar
Mac Newbold committed
488 489 490 491 492 493
    ifstream infile;
    infile.open(argv[0]);
    if (!infile || !infile.good()) {
      cerr << "Error opening file: " << argv[0] << endl;
      exit(-11);
    }
494
    cout << "Parsing top\n";
Mac Newbold's avatar
Mac Newbold committed
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
    parse_top(G, infile);
  }

  /*
   * Allow the user to specify a physical topology
   * in .phys format.  Fills in the "topo" global variable.
   * Make no mistake:  This is actually mandatory now.
   */
  if (topofile != NULL) {
    cout << "Parsing ptop\n";
    ifstream ptopfile;
    ptopfile.open(topofile);
    if (!ptopfile || !ptopfile.good()) {
      cerr << "Error opening file: " << topofile << endl;
      exit(-1);
    }
511
    nparts = parse_ptop(PG,SG,ptopfile);
Mac Newbold's avatar
Mac Newbold committed
512
    cout << "Nparts: " << nparts << endl;
513 514 515 516 517 518 519 520 521 522 523
    cout << "Initializing data structures." << endl;
    edge_costs.init(SG);
    switch_distances.init(SG);
    switch_preds.init(SG);
    cout << "Calculating shortest paths on switch fabric." << endl;
    edge ed;
    forall_edges(ed,SG) {
      edge_costs[ed] = 10000-PG[SG[ed].mate].bandwidth;
#ifdef SCORE_DEBUG
      cerr << "  " << PG[SG[ed].mate].name << " " << edge_costs[ed] << endl;
#endif
Mac Newbold's avatar
Mac Newbold committed
524

525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
    }
    node sw;
    forall_nodes(sw,SG) {
      switch_distances[sw].init(SG);
      switch_preds[sw].init(SG);
      DIJKSTRA_T(SG,sw,edge_costs,
		 switch_distances[sw],switch_preds[sw]);
#ifdef SCORE_DEBUG
      cerr << "Source " << PG[SG[sw].mate].name << endl;
      node dsw;
      forall_nodes(dsw,SG) {
	cerr << "  " << PG[SG[dsw].mate].name;
	int dist = switch_distances[sw][dsw];
	cerr << "  dist " << dist;
	edge de = switch_preds[sw][dsw];
	if (de == nil) {
	  cerr << "  pred nil" << endl;
	} else {
	  cerr << "  pred " << PG[SG[de].mate].name << endl;
	}
      }
#endif
    }
  }
  
  cout << "Annealing!" << endl;
Christopher Alfeld's avatar
Christopher Alfeld committed
551
  batch();
Mac Newbold's avatar
Mac Newbold committed
552 553 554 555 556

  print_solution();
    
  return 0;
}