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

7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#include "port.h"

#include <hash_map>
#include <rope>
#include <queue>

#include <boost/config.hpp>
#include <boost/utility.hpp>
#include <boost/property_map.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
#include <boost/graph/graphviz.hpp>

#include <fstream.h>
Mac Newbold's avatar
Mac Newbold committed
22
#include <iostream.h>
23
#include <time.h>
Mac Newbold's avatar
Mac Newbold committed
24
#include <stdlib.h>
25
#include <math.h>
Mac Newbold's avatar
Mac Newbold committed
26 27
#include <sys/types.h>
#include <sys/time.h>
28 29 30
#include <sys/resource.h>

using namespace boost;
Mac Newbold's avatar
Mac Newbold committed
31 32

#include "common.h"
33
#include "delay.h"
Mac Newbold's avatar
Mac Newbold committed
34
#include "physical.h"
35
#include "virtual.h"
36
#include "vclass.h"
37
#include "pclass.h"
38
#include "score.h"
39

40 41 42 43 44
/*
 * 'optimal' score - computes a lower bound on the optimal score for this
 * mapping, so that if we find this score, we know we're done and can exit
 * early.
 */
45
#ifdef USE_OPTIMAL
Mac Newbold's avatar
Mac Newbold committed
46
#define OPTIMAL_SCORE(edges,nodes) (nodes*SCORE_PNODE + \
47
                                    nodes/opt_nodes_per_sw*SCORE_SWITCH + \
48 49
                                    edges*((SCORE_INTRASWITCH_LINK+ \
                                    SCORE_DIRECT_LINK*2)*4+\
50
                                    SCORE_INTERSWITCH_LINK)/opt_nodes_per_sw)
51
#else
52
#define OPTIMAL_SCORE(edges,nodes) 0
53
#endif
Mac Newbold's avatar
Mac Newbold committed
54

55 56 57 58 59 60 61 62 63 64 65 66 67 68
#ifdef ROB_DEBUG
#define RDEBUG(a) a
#else
#define RDEBUG(a)
#endif

// Some defaults for #defines
#ifndef NO_REVERT
#define NO_REVERT 0
#endif

#ifndef REVERT_VIOLATIONS
#define REVERT_VIOLATIONS 1
#endif
Mac Newbold's avatar
Mac Newbold committed
69

70 71 72 73 74 75 76 77 78 79 80 81
#ifndef REVERT_LAST
#define REVERT_LAST 0
#endif

#ifdef PHYS_CHAIN_LEN
#define PHYSICAL(x) x
#else
#define PHYSICAL(x) 0
#endif

// Here we set up all our graphs.  Need to create the graphs
// themselves and then setup the property maps.
82
tb_pgraph PG;
83 84 85 86 87 88 89 90 91 92 93 94 95
tb_pgraph_vertex_pmap pvertex_pmap = get(vertex_data, PG);
tb_pgraph_edge_pmap pedge_pmap = get(edge_data, PG);
tb_sgraph SG;
tb_sgraph_vertex_pmap svertex_pmap = get(vertex_data, SG);
tb_sgraph_edge_pmap sedge_pmap = get(edge_data, SG);
tb_vgraph VG;
tb_vgraph_vertex_pmap vvertex_pmap = get(vertex_data, VG);
tb_vgraph_edge_pmap vedge_pmap = get(edge_data, VG);

// Map of physical node name to its vertex descriptor.
name_pvertex_map pname2vertex;

// A simple list of physical types.
96
name_count_map ptypes;
97 98 99 100 101 102 103 104 105 106 107 108 109 110

// Map of virtual node name to its vertex descriptor.
name_vvertex_map vname2vertex;

// This is a vector of all the nodes in the top file.  It's used
// to randomly choose nodes.
vvertex_vector virtual_nodes;

// Map of virtual node name to the physical node name it's fixed too.
// The domain is the set of all fixed virtual nodes and the range is
// the set of all fixed physical nodes.
name_name_map fixed_nodes;

// List of virtual types by name.
111
name_count_map vtypes;
112 113 114 115 116 117 118 119 120 121

// Priority queue of unassigned virtual nodes.  Basically a fancy way
// of randomly choosing a unassigned virtual node.  When nodes become
// unassigned they are placed in the queue with a random priority.
vvertex_int_priority_queue unassigned_nodes;

// Map from a pnode* to the the corresponding pvertex.
pnode_pvertex_map pnode2vertex;

// A list of all pclasses.
122
pclass_list pclasses;
123 124 125

// Map of a type to a tt_entry, a vector of pclasses and the size of
// the vector.
126
pclass_types type_table;
127 128 129
#ifdef PER_VNODE_TT
pclass_types vnode_type_table;
#endif
130

131 132 133 134 135
// This datastructure contains all the information needed to calculate
// the shortest path between any two switches.  Indexed by svertex,
// the value will be a predicate map (indexed by svertex as well) of
// the shortest paths for the given vertex.
switch_pred_map_map switch_preds;
136

137 138
// Same, but for distances 
switch_dist_map_map switch_dist;
139

140 141
// Time started, finished, and the time limit
double timestart, timeend, timelimit, timetarget;
142

143 144 145
#ifdef GNUPLOT_OUTPUT
FILE *scoresout, *tempout, *deltaout;
#endif
146

147 148 149 150 151 152 153
// A hash function for graph edges.
struct hashedge {
  size_t operator()(vedge const &A) const {
    hashptr<void *> ptrhash;
    return ptrhash(target(A,VG))/2+ptrhash(source(A,VG))/2;
  }
};
154

155 156 157 158
typedef hash_map<vvertex,pvertex,hashptr<void *> > node_map;
typedef hash_map<vvertex,bool,hashptr<void *> > assigned_map;
typedef hash_map<pvertex,crope,hashptr<void *> > type_map;
typedef hash_map<vedge,tb_link_info,hashedge> link_map;
159

160 161 162 163
// A scaling constant for the temperature in determining whether to
// accept a change.
//static double sensitivity = 0.1;
static double sensitivity = 1;
164

165 166
// The number of accepts of increase that took place during the annealing.
int accepts;
167

168 169
// The number of iterations that took place.
int iters;
Mac Newbold's avatar
Mac Newbold committed
170

171 172 173 174 175 176 177
// These variables store the best solution.
node_map absassignment;		// assignment field of vnode
assigned_map absassigned;	// assigned field of vnode
type_map abstypes;		// type field of vnode
double absbest;			// score
int absbestviolated;		// violated
int iters_to_best = 0;		// iters
178

179
int npnodes;
180

181 182
// Whether or not assign is allowed to generate trivial links
bool allow_trivial_links = true;
183

184 185
// Whether or not assign should use pclasses
bool use_pclasses = true;
186

187 188 189
// Determines whether to accept a change of score difference 'change' at
// temperature 'temperature'.
inline int accept(double change, double temperature)
Mac Newbold's avatar
Mac Newbold committed
190
{
191
  double p;
Mac Newbold's avatar
Mac Newbold committed
192 193 194 195 196 197 198
  int r;

  if (change == 0) {
    p = 1000 * temperature / temp_prob;
  } else {
    p = expf(change/(temperature*sensitivity)) * 1000;
  }
199
  r = std::random() % 1000;
Mac Newbold's avatar
Mac Newbold committed
200
  if (r < p) {
201
    //accepts++;
Mac Newbold's avatar
Mac Newbold committed
202 203 204 205 206
    return 1;
  }
  return 0;
}

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
float used_time()
{
  struct rusage ru;
  getrusage(RUSAGE_SELF,&ru);
  return ru.ru_utime.tv_sec+ru.ru_utime.tv_usec/1000000.0+
    ru.ru_stime.tv_sec+ru.ru_stime.tv_usec/1000000.0;
}

void read_physical_topology(char *filename)
{
  ifstream ptopfile;
  ptopfile.open(filename);
  cout << "Physical Graph: " << parse_ptop(PG,SG,ptopfile) << endl;

#ifdef DUMP_GRAPH
  {
    cout << "Physical Graph:" << endl;
    
    pvertex_iterator vit,vendit;
    tie(vit,vendit) = vertices(PG);
    
    for (;vit != vendit;vit++) {
      tb_pnode *p = get(pvertex_pmap,*vit);
      cout << *vit << "\t" << *p;
    }
    
    pedge_iterator eit,eendit;
    tie(eit,eendit) = edges(PG);

    for (;eit != eendit;eit++) {
      tb_plink *p = get(pedge_pmap,*eit);
      cout << *eit << " (" << source(*eit,PG) << " <-> " <<
	target(*eit,PG) << ")\t" << *p;
    }
  }
#endif

#ifdef GRAPH_DEBUG
  {
    cout << "Switch Graph:" << endl;
    

    svertex_iterator vit,vendit;
    tie(vit,vendit) = vertices(SG);
    
    for (;vit != vendit;vit++) {
      tb_switch *p = get(svertex_pmap,*vit);
      cout << *vit << "\t" << *p;
    }
    
    sedge_iterator eit,eendit;
    tie(eit,eendit) = edges(SG);

    for (;eit != eendit;eit++) {
      tb_slink *p = get(sedge_pmap,*eit);
      cout << *eit << " (" << source(*eit,SG) << " <-> " <<
	target(*eit,SG) << ")\t" << *p;
    }
  }
#endif

  // Set up pnode2vertex
  pvertex_iterator pvit,pvendit;
  tie(pvit,pvendit) = vertices(PG);
  for (;pvit != pvendit;pvit++) {
    pnode2vertex[get(pvertex_pmap,*pvit)]=*pvit;
  }

}

void calculate_switch_MST()
278
{
279 280 281 282 283 284 285 286 287 288 289 290
  // Calculute MST
  cout << "Calculating shortest paths on switch fabric." << endl;
  tb_sgraph_weight_pmap sweight_pmap = get(edge_weight, SG);
  sedge_iterator seit,seendit;
  tie(seit,seendit) = edges(SG);
  for (;seit != seendit;seit++) {
    tb_slink *slink = get(sedge_pmap,*seit);
    // XXX should we make this more complicated depending on
    // latency/loss as well?
    put(sweight_pmap,*seit,
	100000000-get(pedge_pmap,slink->mate)->delay_info.bandwidth);
  }
291

292 293 294 295 296 297 298 299 300
  // ricci - add distance map
  svertex_iterator svit,svendit;
  tie(svit,svendit) = vertices(SG);
  for (;svit != svendit;svit++) {
    switch_preds[*svit] = new switch_pred_map(num_vertices(SG));
    switch_dist[*svit] = new switch_dist_map(num_vertices(SG));
    dijkstra_shortest_paths(SG,*svit,
    			    predecessor_map(&((*switch_preds[*svit])[0])).
			    distance_map(&((*switch_dist[*svit])[0])));
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
#ifdef GRAPH_DEBUG
  cout << "Shortest paths" << endl;
  tie(svit,svendit) = vertices(SG);
  for (;svit != svendit;svit++) {
    cout << *svit << ":" << endl;
    for (unsigned int i = 0;i<num_vertices(SG);++i) {
      cout << i << " " << (*switch_dist[*svit])[i] << endl;
    }
  }
#endif
}

void read_virtual_topology(char *filename)
{
  ifstream topfile;
  topfile.open(filename);
  cout << "Virtual Graph: " << parse_top(VG,topfile) << endl;

#ifdef DUMP_GRAPH
  {
    cout << "Virtual Graph:" << endl;
    

    vvertex_iterator vit,vendit;
    tie(vit,vendit) = vertices(VG);
    
    for (;vit != vendit;vit++) {
      tb_vnode *p = get(vvertex_pmap,*vit);
      cout << *vit << "\t" << *p;
    }
    
    vedge_iterator eit,eendit;
    tie(eit,eendit) = edges(VG);

    for (;eit != eendit;eit++) {
      tb_vlink *p = get(vedge_pmap,*eit);
      cout << *eit << " (" << source(*eit,VG) << " <-> " <<
	target(*eit,VG) << ")\t" << *p;
    }
  }  
#endif
}
345

346 347 348 349 350 351 352 353 354
tb_pnode *find_pnode(tb_vnode *vn)
{
#ifdef PER_VNODE_TT
  tt_entry tt = vnode_type_table[vn->name];
#else
  tt_entry tt = type_table[vn->type];
#endif
  int num_types = tt.first;
  pclass_vector *acceptable_types = tt.second;
355
  
356
  tb_pnode *newpnode;
357
  
358 359 360 361 362 363 364 365 366 367 368
  int i = std::random()%num_types;
  int first = i;
  for (;;) {
    i = (i+1)%num_types;
#ifdef PCLASS_SIZE_BALANCE
    int acceptchance = 1000 * (*acceptable_types)[i]->size * 1.0 /
	npnodes;
    //cout << "Chance was " << acceptchance << endl;
    if ((std::rand() % 1000) < acceptchance) {
	continue;
    }
369
#endif
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 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
#ifdef LOAD_BALANCE
REDO_SEARCH:
    tb_pnode* firstmatch = NULL;
#endif
#ifdef FIND_PNODE_SEARCH
    list<tb_pnode*>::iterator it = (*acceptable_types)[i]->members[vn->type]->L.begin();
#ifdef LOAD_BALANCE
    int skip = std::rand() % (*acceptable_types)[i]->members[vn->type]->L.size();
    // Skip the begging of the list
    for (int j = 0; j < skip; j++) {
	it++;
    }
#endif
    while (it != (*acceptable_types)[i]->members[vn->type]->L.end()) {
#ifdef LOAD_BALANCE
	if ((*it)->typed) {
	    if ((*it)->current_type.compare(vn->type)) {
		it++;
	    } else {
		if (firstmatch == NULL) {
		    firstmatch = *it;
		}
		double acceptchance = 1 - (*it)->current_load * 1.0
		    / (*it)->max_load;
		//double acceptchance = 1.0 / (*acceptable_types)[i]->members[vn->type]->L.size();

	        int p = 1000 * acceptchance;
		if ((std::random() % 1000) < (1000 * acceptchance)) {
		    break;
		} else {
		    it++;
		}
	    }
	} else {
	    break;
	}
#else
	if ((*it)->typed && ((*it)->current_type.compare(vn->type) ||
			     ((*it)->current_load >= (*it)->max_load))) {
	    it++;
	} else {
	    break;
	}
#endif
    }
    if (it == (*acceptable_types)[i]->members[vn->type]->L.end()) {
#ifdef LOAD_BALANCE
	if (firstmatch) {
	    //newpnode = firstmatch;
	    goto REDO_SEARCH;
	} else {
	    newpnode = NULL;
	}
#else
	newpnode = NULL;
#endif
    } else {
	newpnode = *it;
    }
#else
    newpnode = (*acceptable_types)[i]->members[vn->type]->front();
#endif
#ifdef PCLASS_DEBUG
    cerr << "Found pclass: " <<
      (*acceptable_types)[i]->name << " and node " <<
      (newpnode == NULL ? "NULL" : newpnode->name) << "\n";
#endif
    if (newpnode != NULL) {
      RDEBUG(cout << " to " << newpnode->name << endl;)
      return newpnode;
    }
    
#ifndef PCLASS_SIZE_BALANCE
    if (i == first) {
	// couldn't find one
	return NULL;
    }
#endif
  }
449
}
Mac Newbold's avatar
Mac Newbold committed
450

451 452 453 454
/* When this is finished the state will reflect the best solution found. */
void anneal()
{
  cout << "Annealing." << endl;
Mac Newbold's avatar
Mac Newbold committed
455

456 457 458 459 460 461 462 463
  double newscore = 0;
  double bestscore = 0;
  
  iters = 0;
  iters_to_best =0;
  accepts = 0;
  
  double scorediff;
464

465 466 467 468 469 470 471
  int nnodes = num_vertices(VG);
  npnodes = num_vertices(PG);
  int npclasses = pclasses.size();
  
  float cycles = CYCLES*(float)(nnodes + num_edges(VG) + PHYSICAL(npnodes));
  float optimal = OPTIMAL_SCORE(num_edges(VG),nnodes);
    
Mac Newbold's avatar
Mac Newbold committed
472 473 474
#ifdef STATS
  cout << "STATS_OPTIMAL = " << optimal << endl;
#endif
475

Mac Newbold's avatar
Mac Newbold committed
476 477
  int mintrans = (int)cycles;
  int trans;
478 479 480
  int naccepts = 20*(nnodes + PHYSICAL(npnodes));
  pvertex oldpos;
  bool oldassigned;
Mac Newbold's avatar
Mac Newbold committed
481
  int bestviolated;
482
  int num_fixed=0;
483 484 485
  double meltedtemp;
  double temp = init_temp;
  double deltatemp, deltaavg;
486 487 488

#ifdef VERBOSE
  cout << "Initialized to cycles="<<cycles<<" optimal="<<optimal<<" mintrans="
489
       << mintrans<<" naccepts="<<naccepts<< endl;
490
#endif
491

Mac Newbold's avatar
Mac Newbold committed
492 493 494
  /* Set up the initial counts */
  init_score();

495
  /* Set up fixed nodes */
496 497 498 499 500
  for (name_name_map::iterator fixed_it=fixed_nodes.begin();
       fixed_it!=fixed_nodes.end();++fixed_it) {
    if (vname2vertex.find((*fixed_it).first) == vname2vertex.end()) {
      cerr << "Fixed node: " << (*fixed_it).first <<
	"does not exist." << endl;
501 502
      exit(1);
    }
503 504 505 506
    vvertex vv = vname2vertex[(*fixed_it).first];
    if (pname2vertex.find((*fixed_it).second) == pname2vertex.end()) {
      cerr << "Fixed node: " << (*fixed_it).second <<
	" not available." << endl;
507 508
      exit(1);
    }
509 510 511 512 513
    pvertex pv = pname2vertex[(*fixed_it).second];
    tb_vnode *vn = get(vvertex_pmap,vv);
    tb_pnode *pn = get(pvertex_pmap,pv);
    if (vn->vclass != NULL) {
      cerr << "Can not have fixed nodes be in a vclass!.\n";
514 515
      exit(1);
    }
516 517 518
    if (add_node(vv,pv,false) == 1) {
      cerr << "Fixed node: Could not map " << vn->name <<
	" to " << pn->name << endl;
519 520
      exit(1);
    }
521
    vn->fixed = true;
522
    num_fixed++;
523
  }
524

Mac Newbold's avatar
Mac Newbold committed
525 526
  bestscore = get_score();
  bestviolated = violated;
527

528 529
#ifdef VERBOSE
  cout << "Problem started with score "<<bestscore<<" and "<< violated
530
       << " violations." << endl;
531
#endif
532

Mac Newbold's avatar
Mac Newbold committed
533
  absbest = bestscore;
534 535 536 537 538 539 540 541 542 543 544 545 546 547
  absbestviolated = bestviolated;

  vvertex_iterator vit,veit;
  tie(vit,veit) = vertices(VG);
  for (;vit!=veit;++vit) {
    tb_vnode *vn = get(vvertex_pmap,*vit);
    absassigned[*vit] = vn->assigned;
    if (vn->assigned) {
      assert(vn->fixed);
      absassignment[*vit] = vn->assignment;
      abstypes[*vit] = vn->type;
    } else {
      unassigned_nodes.push(vvertex_int_pair(*vit,std::random()));
    }
548 549
  }

550 551 552 553 554 555 556 557
  int neighborsize;
  neighborsize = nnodes * npclasses;
  if (neighborsize < min_neighborhood_size) {
    neighborsize = min_neighborhood_size;
  }
#ifdef CHILL
  double scores[neighborsize];
#endif
558 559 560 561

  if (num_fixed == nnodes) {
    cout << "All nodes are fixed.  No annealing." << endl;
    goto DONE;
Mac Newbold's avatar
Mac Newbold committed
562
  }
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
  
  // Annealing loop!
  vvertex vv;
  tb_vnode *vn;

  // Crap added by ricci
  bool melting;
  int nincreases, ndecreases;
  double avgincrease;
  double avgscore;
//  float avgscoresquared;
  double initialavg;
  double stddev;
  bool finished;
  bool forcerevert;
  finished = forcerevert = false;
  int tsteps;
  int mintsteps;
  double meltstart;

#define MAX_AVG_HIST 16
  double avghist[MAX_AVG_HIST];
  int hstart, nhist;
  hstart = nhist = 0;
  double lasttemp;
  double smoothedavg, lastsmoothed;
  lastsmoothed = 500000.0f;
  lasttemp = 5000.0f;
  int melttrials;
  melttrials = 0;

  bool finishedonce;
  finishedonce = false;

  tsteps = 0;
  mintsteps = MAX_AVG_HIST;
  tsteps = 0;
  mintsteps = MAX_AVG_HIST;
  tsteps = 0;
  mintsteps = MAX_AVG_HIST;

  // Make sure the last two don't prevent us from running!
  avgscore = initialavg = 1.0;

  stddev = 0;

#ifdef MELT
  melting = true;
#ifdef TIME_TARGET
  meltstart = used_time();
#endif
#else
  melting = false;
#endif
Mac Newbold's avatar
Mac Newbold committed
617

618 619 620 621 622
  melt_trans = neighborsize;
#ifdef EPSILON_TERMINATE
//  while ((initialavg) && ((temp * avgscore / initialavg) >= epsilon)) {
  while(1) {
#else
623
  while (temp >= temp_stop) {
624
#endif
Mac Newbold's avatar
Mac Newbold committed
625
#ifdef VERBOSE
626 627
    cout << "Temperature:  " << temp << " AbsBest: " << absbest <<
      " (" << absbestviolated << ")" << endl;
Mac Newbold's avatar
Mac Newbold committed
628 629 630
#endif
    trans = 0;
    accepts = 0;
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
    nincreases = ndecreases = 0;
    avgincrease = 0.0;
    avgscore = bestscore;
#ifdef CHILL
    scores[0] = bestscore;
#endif

    if (melting) {
      cout << "Doing melting run" << endl;
    }

    while ((melting && (trans < melt_trans))
#ifdef NEIGHBOR_LENGTH
	    || (trans < neighborsize)) {
#else
	    || (!melting && (trans < mintrans && accepts < naccepts))) {
#endif
Mac Newbold's avatar
Mac Newbold committed
648 649 650 651

#ifdef STATS
      cout << "STATS temp:" << temp << " score:" << get_score() <<
	" violated:" << violated << " trans:" << trans <<
652 653 654 655
	" accepts:" << accepts << " current_time:" <<
	used_time() << endl;
#endif 
      pvertex newpos;
Mac Newbold's avatar
Mac Newbold committed
656 657 658
      trans++;
      iters++;

659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
      bool freednode = false;
      if (! unassigned_nodes.empty()) {
	vv = unassigned_nodes.top().first;
	assert(!get(vvertex_pmap,vv)->assigned);
	unassigned_nodes.pop();
      } else {
	int start = std::random()%nnodes;
	int choice = start;
#if defined(FIX_LAN_NODES) || defined(AUTO_MIGRATE)
	while (get(vvertex_pmap,virtual_nodes[choice])->fixed ||
		!get(vvertex_pmap,virtual_nodes[choice])->type.compare("lan")) {
#else
	while (get(vvertex_pmap,virtual_nodes[choice])->fixed) {
#endif
	  choice = (choice +1) % nnodes;
	  if (choice == start) {
	      choice = -1;
	      break;
	  }
	}
	if (choice >= 0) {
	    vv = virtual_nodes[choice];
	} else {
	    cout << "All nodes are fixed or LANs.  No annealing." << endl;
	    goto DONE;
	}
685
      }
686 687 688 689 690 691 692 693 694 695
      
      vn = get(vvertex_pmap,vv);
      RDEBUG(cout << "Reassigning " << vn->name << endl;)
      oldassigned = vn->assigned;
      oldpos = vn->assignment;
      
#ifdef FREE_IMMEDIATELY
      if (oldassigned) {
	remove_node(vv);
	RDEBUG(cout << "Freeing up " << vn->name << endl;)
696
      }
697 698 699 700
#endif
      
      if (vn->vclass != NULL) {
	vn->type = vn->vclass->choose_type();
701
#ifdef SCORE_DEBUG
702 703
	cerr << "vclass " << vn->vclass->name  << ": choose type = "
	     << vn->type << " dominant = " << vn->vclass->dominant << endl;
704
#endif
705
      }
706 707 708 709 710 711 712
      if (vn->type.compare("lan") == 0) {
	// LAN node
	pvertex lanv = make_lan_node(vv);
#ifndef FREE_IMMEDIATELY
	if (oldassigned) {
	  RDEBUG(cout << "removing: lan,oldassigned" << endl;)
	  remove_node(vv);
Mac Newbold's avatar
Mac Newbold committed
713
	}
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
#endif
	if (add_node(vv,lanv,false) != 0) {
	  delete_lan_node(lanv);
	  unassigned_nodes.push(vvertex_int_pair(vv,std::random()));
	  continue;
	}
      } else {
	tb_pnode *newpnode = find_pnode(vn);
#ifndef FREE_IMMEDIATELY
	if (oldassigned) {
	  RDEBUG(cout << "removing: !lan, oldassigned" << endl;)
	  remove_node(vv);
	  //unassigned_nodes.push(vvertex_int_pair(vv,std::random()));
	}
#endif
	if (newpnode == NULL) {
	  // We're not going to be re-assigning this one
#ifndef SMART_UNMAP
	  unassigned_nodes.push(vvertex_int_pair(vv,std::random()));
#endif
	  // need to free up nodes
#ifdef SMART_UNMAP
     	  // XXX: Should probably randomize this
	  // XXX: Add support for not using PER_VNODE_TT
	  // XXX: Not very robust

	  freednode = true;

	  //cout << "Finding a replacement node for " << vn->name << endl;

	  //cerr << "Starting" << endl;
	  tt_entry tt = vnode_type_table[vn->name];
	  //cerr << "Got TT" << endl;
	  int size = tt.first;
	  pclass_vector *acceptable_types = tt.second;
	  //cerr << "Got AT" << endl;
	  // Find a node to kick out
	  bool foundnode = false;
	  int offi = std::rand();
	  int index;
	  //cerr << "Starting " << size << endl;
	  for (int i = 0; i < size; i++) {
	      index = (i + offi) % size;
	      //cout << "On " << index << endl;
	      if ((*acceptable_types)[index]->used_members.find(vn->type) ==
		      (*acceptable_types)[index]->used_members.end()) {
		  //cout << "Can't find type" << endl;
		  continue;
	      }
	      if ((*acceptable_types)[index]->used_members[vn->type]->size() == 0) {
		  //cout << "used_members empty" << endl;
		  continue;
	      }
	      //cerr << "Works!" << endl;
	      foundnode = true;
	      break;
	  }

	  //cerr << "Got i " << i << endl;
	  if (foundnode) {
	      assert((*acceptable_types)[index]->used_members[vn->type]->size());
	      tb_pclass::tb_pnodeset::iterator it = (*acceptable_types)[index]->used_members[vn->type]->begin();
	      int j = std::rand() % (*acceptable_types)[index]->used_members[vn->type]->size();
	      //cerr << "Used members: " << (*acceptable_types)[i]->used_members[vn->type]->size() << endl;
	      while (j > 0) {
		  it++;
		  j--;
		  //cerr << "Skipping" << endl;
	      }
	      //cerr << "Got it" << endl;
	      tb_vnode_set::iterator it2 = (*it)->assigned_nodes.begin();
	      int k = std::rand() % (*it)->assigned_nodes.size();
	      while (k > 0) {
		  it2++;
		  k--;
		  //cerr << "Skipping" << endl;
	      }
	      //cerr << "Got it2" << endl;
	      tb_vnode *kickout = *it2;
	      //cerr << "Kicking out " << kickout->name << " on " << (*it)->name <<  endl;
	      assert(kickout->assigned);
	      vvertex toremove = vname2vertex[kickout->name];
	      newpnode = *it;
	      //cerr << "Got vvertex" << endl;
	      remove_node(toremove);
	      unassigned_nodes.push(vvertex_int_pair(toremove,
			  std::random()));
	  } else {
	      cerr << "Failed to find a replacement!" << endl;
	  }

	  //cerr << "Done" << endl;
#else
	  int start = std::random()%nnodes;
	  int toremove = start;
#if defined(FIX_LAN_NODES) || defined(AUTO_MIGRATE)
	  while (get(vvertex_pmap,virtual_nodes[toremove])->fixed ||
		 (!get(vvertex_pmap,virtual_nodes[toremove])->assigned) ||
		 (get(vvertex_pmap,virtual_nodes[toremove])->type.compare("lan"))) {
#else
#ifdef SMART_UNMAP

#ifdef PER_VNODE_TT
          tt_entry tt = vnode_type_table[vn->name];
#else
	  tt_entry tt = type_table[vn->type];
#endif
	  pclass_vector *acceptable_types = tt.second;

	  while (1) {
	      bool keepgoing = false;
	      if (get(vvertex_pmap,virtual_nodes[toremove])->fixed) {
		  keepgoing = true;
		  //cout << "keepgoing: fixed" << endl;
	      } else if (! get(vvertex_pmap,virtual_nodes[toremove])->assigned) {
		  keepgoing = true;
		  //cout << "keepgoing: !assigned" << endl;
	      } else {
		  pvertex pv = get(vvertex_pmap,virtual_nodes[toremove])->assignment;
		  tb_pnode *pn = get(pvertex_pmap,pv);
		  int j;
		  for (j = 0; j < acceptable_types->size(); j++) {
		      if ((*acceptable_types)[j] == pn->my_class) {
			  break;
		      }
		  }
		  if (j == acceptable_types->size()) {
		      keepgoing = true;
		      //cout << "keepgoing: wrongtype" << endl;
		  }
	      }

	      if (!keepgoing) {
		  break;
	      }
		  
#else
	  while (get(vvertex_pmap,virtual_nodes[toremove])->fixed ||
		 (! get(vvertex_pmap,virtual_nodes[toremove])->assigned)) {
#endif
#endif
	      toremove = (toremove +1) % nnodes;
	      if (toremove == start) {
		  toremove = -1;
		  break;
	      }
	  }
	  if (toremove >= 0) {
	      RDEBUG(cout << "removing: freeing up nodes" << endl;)
	      remove_node(virtual_nodes[toremove]);
	      unassigned_nodes.push(vvertex_int_pair(virtual_nodes[toremove],
						     std::random()));
	  }
	  continue;
#endif /* SMART_UNMAP */
#ifndef SMART_UNMAP
	} else {
	  //printf("Found an old node!\n");
#else
	}
#endif
	  if (newpnode != NULL) {
	      newpos = pnode2vertex[newpnode];
	      if (add_node(vv,newpos,false) != 0) {
		  unassigned_nodes.push(vvertex_int_pair(vv,std::random()));
		  continue;
	      }
	  } else {
#ifdef SMART_UNMAP
		  unassigned_nodes.push(vvertex_int_pair(vv,std::random()));
#endif
	      if (freednode) {
		  continue;
	      }
888
	  }
889
#ifndef SMART_UNMAP
890
	}
891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
#endif
      }

	/*
#ifdef FREE_IMMEDIATELY
      if (oldassigned) {
	remove_node(vv);
      }
#endif
*/

#ifdef FIX_LAN_NODES
      // OK, we're going to do something silly here: Migrate LAN nodes!
      //cout << "Migrating: " << unassigned_nodes.size() << " nodes free" << endl;
      vvertex_iterator lanvertex_it,end_lanvertex_it;
      vvertex_list migrate_lan_nodes;
      tie(lanvertex_it,end_lanvertex_it) = vertices(VG);
      for (;lanvertex_it!=end_lanvertex_it;++lanvertex_it) {
	  tb_vnode *vnode = get(vvertex_pmap,*lanvertex_it);
	  if (vnode->assigned) {
	      if (vnode->type.compare("lan") == 0) {
		  migrate_lan_nodes.push_front(*lanvertex_it);
	      }
	  }
      }
      while (migrate_lan_nodes.size() > 0) {
	  vvertex lanv = migrate_lan_nodes.front();
	  migrate_lan_nodes.pop_front();
	  RDEBUG(cout << "removing: migration" << endl;)
	  remove_node(lanv);
	  pvertex lanpv = make_lan_node(lanv);
	  add_node(lanv,lanpv,true);
      }
Mac Newbold's avatar
Mac Newbold committed
924

925
#endif
Mac Newbold's avatar
Mac Newbold committed
926

927
      newscore = get_score();
928 929 930 931 932 933 934 935 936 937 938 939 940 941
      /*
      if (melting) {
        printf("Melting: Adding %f to avgscore\n",newscore);
	melttrials++;
	avgscore += newscore;
      }
      */
      assert(newscore >= 0);

//      avgscore = avgscore * (trans -1) / trans + newscore / trans;
//      avgscoresquared = avgscoresquared * (trans -1) / trans
//	+ (newscore * newscore) / trans;
      //avgscore = avgscore + newscore / neighborsize;
//      avgscoresquared = avgscoresquared + (newscore * newscore) / neighborsize;
942 943
      
      // Negative means bad
Mac Newbold's avatar
Mac Newbold committed
944
      scorediff = bestscore - newscore;
945 946 947 948 949 950 951 952 953
      // This looks funny, because < 0 means worse, which means an increase in
      // score
      if (scorediff < 0) {
	nincreases++;
	avgincrease = avgincrease * (nincreases -1) / nincreases +
	  (-scorediff)  / nincreases;
      } else {
	ndecreases++;
      }
954
      
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
      bool accepttrans = false;
      if (newscore < optimal) {
	  accepttrans = true;
	  RDEBUG(cout << "accept: optimal (" << newscore << "," << optimal
		  << ")" << endl;)
      } else if (melting) {
	  accepttrans = true;
	  RDEBUG(cout << "accept: melting" << endl;)
      } else
#ifdef NO_VIOLATIONS
	  if (newscore < bestscore) {
	      accepttrans = true;
	      RDEBUG(cout << "accept: better (" << newscore << "," << bestscore
		      << ")" << endl;)
	  } else if (accept(scorediff,temp)) {
	      accepttrans = true;
	      RDEBUG(cout << "accept: metropolis (" << newscore << ","
		      << bestscore << "," << expf(scorediff/(temp*sensitivity))
		      << ")" << endl;)
	  }
#else
          if ((violated == bestviolated) && (newscore < bestscore)) {
	      accepttrans = true;
	      RDEBUG(cout << "accept: better (" << newscore << "," << bestscore
		      << ")" << endl;)
	  } else if (violated < bestviolated) {
	      accepttrans = true;
	      RDEBUG(cout << "accept: better (violations) (" << newscore << ","
		      << bestscore << "," << violated << "," << bestviolated
		      << ")" << endl;
	          cout << "Violations: (new) " << 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;
		  cout << "  desires:    " << vinfo.desires << endl;
		  cout << "  vclass:     " << vinfo.vclass << endl;
		  cout << "  delay:      " << vinfo.delay << endl;)
	  } else if (accept(scorediff,temp)) {
	      accepttrans = true;
	      RDEBUG(cout << "accept: metropolis (" << newscore << ","
		      << bestscore << "," << expf(scorediff/(temp*sensitivity))
		      << ")" << endl;)
	  }
#endif

      if (accepttrans) {
Mac Newbold's avatar
Mac Newbold committed
1003 1004
	bestscore = newscore;
	bestviolated = violated;
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
#ifdef GNUPLOT_OUTPUT
	fprintf(tempout,"%f\n",temp);
	fprintf(scoresout,"%f\n",newscore);
	fprintf(deltaout,"%f\n",-scorediff);
#endif
	//if (!melting) {
	    //printf("Adding %f to avgscore\n",newscore);
	avgscore += newscore;
	//}

Mac Newbold's avatar
Mac Newbold committed
1015
	accepts++;
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027

#ifdef CHILL
	 if (!melting) {
	     scores[accepts] = newscore;
	 }
#endif

#ifdef NO_VIOLATIONS
	if (newscore < absbest) {
#else
	if ((violated < absbestviolated) ||
	    ((violated == absbestviolated) &&
Mac Newbold's avatar
Mac Newbold committed
1028
	     (newscore < absbest))) {
1029 1030 1031 1032 1033 1034 1035 1036 1037
#endif
#ifdef SCORE_DEBUG
	  cerr << "New best solution." << endl;
#endif
	  tie(vit,veit) = vertices(VG);
	  for (;vit!=veit;++vit) {
	    absassignment[*vit] = get(vvertex_pmap,*vit)->assignment;
	    absassigned[*vit] = get(vvertex_pmap,*vit)->assigned;
	    abstypes[*vit] = get(vvertex_pmap,*vit)->type;
Mac Newbold's avatar
Mac Newbold committed
1038 1039
	  }
	  absbest = newscore;
1040 1041 1042 1043 1044
	  absbestviolated = violated;
	  iters_to_best = iters;
#ifdef SCORE_DEBUG
	  cerr << "New best recorded" << endl;
#endif
Mac Newbold's avatar
Mac Newbold committed
1045 1046
	}
	if (newscore < optimal) {
1047
	  cout << "OPTIMAL ( " << optimal << ")" << endl;
Mac Newbold's avatar
Mac Newbold committed
1048 1049
	  goto DONE;
	}
1050 1051 1052
	// Accept change
      } else {
	// Reject change
1053 1054 1055 1056 1057 1058 1059
	RDEBUG(cout << "removing: rejected change" << endl;)
	remove_node(vv);
	if (oldassigned) {
	  if (vn->type.compare("lan") == 0) {
	    oldpos = make_lan_node(vv);
	  }
	  add_node(vv,oldpos,false);
Mac Newbold's avatar
Mac Newbold committed
1060 1061
	}
      }
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081

      if (melting) {
	//cout << "Melt: avgi " << avgincrease << " nin " << nincreases << " ndec "
	// << ndecreases << " X0 " << X0 << endl;
	temp = avgincrease /
	  log(nincreases/ (nincreases * X0 - ndecreases * (1 - X0)));
	if (!(temp > 0.0)) {
	    temp = 0.0;
	}
	//cout << "New melting temp is " << temp << endl;
      }
#ifdef TIME_TERMINATE
      if (timelimit && ((used_time() - timestart) > timelimit)) {
	printf("Reached end of run time, finishing\n");
	forcerevert = true;
	finished = true;
	goto NOTQUITEDONE;
      }
#endif

Mac Newbold's avatar
Mac Newbold committed
1082 1083
    }

1084 1085 1086
#ifdef RANDOM_ASSIGNMENT
      if (violated == 0) {
	  finished = true;
1087
      }
1088 1089 1090 1091 1092
#endif

#ifdef REALLY_RANDOM_ASSIGNMENT
      if (unassigned_nodes.size() == 0) {
	  finished = true;
1093
      }
1094 1095 1096 1097 1098 1099
#endif

NOTQUITEDONE:
   /* if (melting) {
	printf("Melting: avgscore: %f = %f / %i\n",avgscore / melttrials,avgscore,melttrials);
      avgscore = avgscore / melttrials;
1100
    } else {
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
    */
      RDEBUG(printf("avgscore: %f = %f / %i\n",avgscore / (accepts +1),avgscore,accepts+1);)
      avgscore = avgscore / (accepts +1);
      /*
    }
    */

    if (melting) {
      melting = false;
      initialavg = avgscore;
      meltedtemp = temp;
      RDEBUG(cout << "Melting finished with a temperature of " << temp
	<< " avg score was " << initialavg << endl;)
      if (!(meltedtemp > 0.0)) { // This backwards expression to catch NaNs
	cout << "Finished annealing while melting!" << endl;
	finished = true;
	forcerevert = true;
      }
#ifdef TIME_TARGET
      if (timetarget) {
	double melttime = used_time() - meltstart;
	double timeleft = timetarget - melttime;
	double stepsleft = timeleft / melttime;
	cout << "Melting took " << melttime << " seconds, will try for "
	  << stepsleft << " temperature steps" << endl;
	temp_rate = pow(temp_stop/temp,1/stepsleft);
	cout << "Timelimit: " << timelimit << " Timeleft: " << timeleft
	  << " temp_rate: " << temp_rate << endl;
      }
#endif
    } else {
#ifdef CHILL
      if (!melting) {
	  stddev = 0;
	  for (int i = 0; i <= accepts; i++) {
	    stddev += pow(scores[i] - avgscore,2);
	  }
	  stddev /= (accepts +1);
	  stddev = sqrt(stddev);
	  temp = temp / (1 + (temp * log(1 + delta))/(3  * stddev));
      }
#else
      temp *= temp_rate;
#endif
Mac Newbold's avatar
Mac Newbold committed
1145 1146 1147
    }


1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
#ifdef DEBUG_TSTEP
#ifdef EPSILON_TERMINATE
#ifdef CHILL
    RDEBUG(printf("temp_end: %f %f %f\n",temp,temp * avgscore / initialavg,stddev);)
#else
    RDEBUG(printf("temp_end: %f %f\n",temp,temp * avgscore / initialavg);)
#endif
#else
    printf("temp_end: %f ",temp);
    if (trans >= mintrans) {
	if (accepts >= naccepts) {
	    printf("both");
	} else {
	    printf("trans %f",accepts*1.0/naccepts);
	}
    } else {
	printf("accepts %f",trans*1.0/mintrans);
    }
    printf("\n");
#endif
#endif
Mac Newbold's avatar
Mac Newbold committed
1169
    
1170 1171 1172 1173
    // Revert to best found so far - do link/lan migration as well
#ifdef SCORE_DEBUG
    cerr << "Reverting to best known solution." << endl;
#endif
Mac Newbold's avatar
Mac Newbold committed
1174 1175


1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
    // Add this to the history, and computed a smoothed average
    smoothedavg = avgscore / (nhist + 1);
    for (int j = 0; j < nhist; j++) {
      smoothedavg += avghist[(hstart + j) % MAX_AVG_HIST] / (nhist + 1);
    }
    /*
    printf("smooth: avgscore %f, smoothedavg %f, hstart %i, nhist %i\n",avgscore,
	smoothedavg,hstart,nhist);
    */

    avghist[(hstart + nhist) % MAX_AVG_HIST] = avgscore;
    if (nhist < MAX_AVG_HIST) {
      nhist++;
    } else {
      hstart = (hstart +1) % MAX_AVG_HIST;
    }
Mac Newbold's avatar
Mac Newbold committed
1192

1193 1194 1195 1196 1197 1198 1199
#ifdef LOCAL_DERIVATIVE
    deltaavg = lastsmoothed - smoothedavg;
    deltatemp = lasttemp - temp;
#else
    deltaavg = initialavg - smoothedavg;
    deltatemp = meltedtemp - temp;
#endif
1200

1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
    lastsmoothed = smoothedavg;
    lasttemp = temp;

#ifdef EPSILON_TERMINATE
    RDEBUG(
       printf("avgs: real: %f, smoothed %f, initial: %f\n",avgscore,smoothedavg,initialavg);
       printf("epsilon: (%f) %f / %f * %f / %f < %f (%f)\n", fabs(deltaavg), temp, initialavg,
	   deltaavg, deltatemp, epsilon,(temp / initialavg) * (deltaavg/ deltatemp));
    )
    if ((tsteps >= mintsteps) && // (temp <= min_temp_end) &&
#ifdef ALLOW_NEGATIVE_DELTA
	((fabs(deltaavg) < 0.0000001)
	 || (fabs((temp / initialavg) * (deltaavg/ deltatemp)) < epsilon))) {
#else
	(deltaavg > 0) && ((temp / initialavg) * (deltaavg/ deltatemp) < epsilon)) {
#endif
#ifdef FINISH_HILLCLIMB
        if (!finishedonce && ((absbestviolated <= violated) && (absbest < bestscore))) {
	    // We don't actually stop, we just go do a hill-climb (basically) at the best
	    // one we previously found
	    finishedonce = true;
	    printf("Epsilon Terminated, but going back to a better solution\n");
	} else {
	    finished = true;
	}
#else
	finished = true;
#endif
	forcerevert = true;
    }
#endif
1232

1233 1234 1235 1236 1237
    bool revert = false;
    if (forcerevert) {
	cout << "Reverting: forced" << endl;
	revert = true;
    }
1238

1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
#ifndef NO_REVERT
    if (REVERT_VIOLATIONS && (absbestviolated < violated)) {
	cout << "Reverting: REVERT_VIOLATIONS" << endl;
	revert = true;
    }
    if (absbest < bestscore) {
	cout << "Reverting: best score" << endl;
	revert = true;
    }
#endif
1249

1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
    if (REVERT_LAST && (temp < temp_stop)) {
	cout << "Reverting: REVERT_LAST" << endl;
	revert = true;
    }

    // Only revert if the best configuration has better violations
    /*
    if ((NO_REVERT || (REVERT_LAST && (temp >= temp_stop)) ||
	(REVERT_VIOLATIONS && (absbestviolated > violated))) && !forcerevert) {
	*/
    vvertex_list lan_nodes;
    vvertex_iterator vvertex_it,end_vvertex_it;
    if (!revert) {
      // Just find LAN nodes, for migration
      tie(vvertex_it,end_vvertex_it) = vertices(VG);
      for (;vvertex_it!=end_vvertex_it;++vvertex_it) {
	tb_vnode *vnode = get(vvertex_pmap,*vvertex_it);
	if (vnode->assigned) {
	  if (vnode->type.compare("lan") == 0) {
	    lan_nodes.push_front(*vvertex_it);
	  }
	}
      } 
    } else {
      cout << "Reverting to best solution\n";
      // Do a full revert
      tie(vvertex_it,end_vvertex_it) = vertices(VG);
      for (;vvertex_it!=end_vvertex_it;++vvertex_it) {
	tb_vnode *vnode = get(vvertex_pmap,*vvertex_it);
	if (vnode->fixed) continue;
	if (vnode->assigned) {
	  RDEBUG(cout << "removing: revert " << vnode->name << endl;)
	  remove_node(*vvertex_it);
	} else {
	  RDEBUG(cout << "not removing: revert " << vnode->name << endl;)
	}
      }
      tie(vvertex_it,end_vvertex_it) = vertices(VG);
      for (;vvertex_it!=end_vvertex_it;++vvertex_it) {
	tb_vnode *vnode = get(vvertex_pmap,*vvertex_it);
	if (vnode->fixed) continue;
	if (absassigned[*vvertex_it]) {
	  if (vnode->type.compare("lan") == 0) {
	    lan_nodes.push_front(*vvertex_it);
	  } else {
	    if (vnode->vclass != NULL) {
	      vnode->type = abstypes[*vvertex_it];
	    }
	    assert(!add_node(*vvertex_it,absassignment[*vvertex_it],true));
	  }
	}
      }
    }

    // Do LAN migration
    RDEBUG(cout << "Doing LAN migration" << endl;)
    while (lan_nodes.size() > 0) {
      vvertex lanv = lan_nodes.front();
      lan_nodes.pop_front();
      if (!revert) { // If reverting, we've already done this
	  RDEBUG(cout << "removing: migration" << endl;)
	  remove_node(lanv);
      }
      pvertex lanpv = make_lan_node(lanv);
      add_node(lanv,lanpv,true);
    }

    tsteps++;

    if (finished) {
      goto DONE;
    }
  }
 DONE:
  cout << "Done" << endl;
1325 1326
}

Mac Newbold's avatar
Mac Newbold committed
1327 1328
void print_solution()
{
1329 1330 1331
  vvertex_iterator vit,veit;
  tb_vnode *vn;
  
Mac Newbold's avatar
Mac Newbold committed
1332
  cout << "Nodes:" << endl;
1333 1334 1335 1336 1337
  tie(vit,veit) = vertices(VG);
  for (;vit != veit;++vit) {
    vn = get(vvertex_pmap,*vit);
    if (! vn->assigned) {
      cout << "unassigned: " << vn->name << endl;
Mac Newbold's avatar
Mac Newbold committed
1338
    } else {
1339 1340
      cout << vn->name << " "
	   << get(pvertex_pmap,vn->assignment)->name << endl;
Mac Newbold's avatar
Mac Newbold committed
1341 1342 1343 1344
    }
  }
  cout << "End Nodes" << endl;
  cout << "Edges:" << endl;
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
  vedge_iterator eit,eendit;
  tie(eit,eendit) = edges(VG);
  for (;eit!=eendit;++eit) {
    tb_vlink *vlink = get(vedge_pmap,*eit);
    cout << vlink->name;
    if (vlink->link_info.type == tb_link_info::LINK_DIRECT) {
      tb_plink *p = get(pedge_pmap,vlink->link_info.plinks.front());
      cout << " direct " << p->name << " (" <<
	p->srcmac << "," << p->dstmac << ")" << endl;
    } else if (vlink->link_info.type == tb_link_info::LINK_INTRASWITCH) {
      tb_plink *p = get(pedge_pmap,vlink->link_info.plinks.front());
      tb_plink *p2 = get(pedge_pmap,vlink->link_info.plinks.back());
      cout << " intraswitch " << p->name << " (" <<
	p->srcmac << "," << p->dstmac << ") " <<
	p2->name << " (" << p2->srcmac << "," << p2->dstmac <<
Mac Newbold's avatar
Mac Newbold committed
1360
	")" << endl;
1361
    } else if (vlink->link_info.type == tb_link_info::LINK_INTERSWITCH) {
1362
      cout << " interswitch ";
1363 1364 1365 1366 1367
      for (pedge_path::iterator it=vlink->link_info.plinks.begin();
	   it != vlink->link_info.plinks.end();++it) {
	tb_plink *p = get(pedge_pmap,*it);
	cout << " " << p->name << " (" << p->srcmac << "," <<
	  p->dstmac << ")";
Mac Newbold's avatar
Mac Newbold committed
1368
      }
1369 1370
      cout << endl;
    } else if (vlink->link_info.type == tb_link_info::LINK_TRIVIAL) {
1371
      cout << " trivial" << endl;
Mac Newbold's avatar
Mac Newbold committed
1372
    } else {
1373
      cout << " Mapping Failed" << endl;
Mac Newbold's avatar
Mac Newbold committed
1374 1375 1376 1377 1378 1379
    }
  }
  cout << "End Edges" << endl;
  cout << "End solution" << endl;
}

1380 1381 1382 1383 1384 1385 1386 1387 1388
struct pvertex_writer {
  void operator()(ostream &out,const pvertex &p) const {
    tb_pnode *pnode = get(pvertex_pmap,p);
    out << "[label=\"" << pnode->name << "\"";
    crope style;
    if (pnode->types.find("switch") != pnode->types.end()) {
      out << " style=dashed";
    } else if (pnode->types.find("lan") != pnode->types.end()) {
      out << " style=invis";
Mac Newbold's avatar
Mac Newbold committed
1389
    }
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
    out << "]";
  }
};

struct vvertex_writer {
  void operator()(ostream &out,const vvertex &v) const {
    tb_vnode *vnode = get(vvertex_pmap,v);
    out << "[label=\"" << vnode->name << " ";
    if (vnode->vclass == NULL) {
      out << vnode->type;
    } else {
      out << vnode->vclass->name;
    }
    out << "\"";
    if (vnode->fixed) {
      out << " style=dashed";
    }
    out << "]";
  }
};

struct pedge_writer {
  void operator()(ostream &out,const pedge &p) const {
    out << "[";
    tb_plink *plink = get(pedge_pmap,p);
#ifdef VIZ_LINK_LABELS
    out << "label=\"" << plink->name << " ";
    out << plink->delay_info.bandwidth << "/" <<
      plink->delay_info.delay << "/" << plink->delay_info.loss << "\"";
#endif
    if (plink->type == tb_plink::PLINK_INTERSWITCH) {
      out << " style=dashed";
    }
    tb_pnode *src = get(pvertex_pmap,source(p,PG));
    tb_pnode *dst = get(pvertex_pmap,target(p,PG));
    if ((src->types.find("lan") != src->types.end()) ||
	(dst->types.find("lan") != dst->types.end())) {
      out << " style=invis";
    }
    out << "]";
  }
};
1432

1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455
struct sedge_writer {
  void operator()(ostream &out,const sedge &s) const {
    tb_slink *slink = get(sedge_pmap,s);
    pedge_writer pwriter;
    pwriter(out,slink->mate);
  }
};
struct svertex_writer {
  void operator()(ostream &out,const svertex &s) const {
    tb_switch *snode = get(svertex_pmap,s);
    pvertex_writer pwriter;
    pwriter(out,snode->mate);
  }
};

struct vedge_writer {
  void operator()(ostream &out,const vedge &v) const {
    tb_vlink *vlink = get(vedge_pmap,v);
    out << "[";
#ifdef VIZ_LINK_LABELS
    out << "label=\"" << vlink->name << " ";
    out << vlink->delay_info.bandwidth << "/" <<
      vlink->delay_info.delay << "/" << vlink->delay_info.loss << "\"";
1456
#endif
1457 1458 1459 1460 1461 1462
    if (vlink->emulated) {
      out << "style=dashed";
    }
    out <<"]";
  }
};
1463

1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
struct graph_writer {
  void operator()(ostream &out) const {
    out << "graph [size=\"1000,1000\" overlap=\"false\" sep=0.1]" << endl;
  }
};

struct solution_edge_writer {
  void operator()(ostream &out,const vedge &v) const {
    tb_link_info &linfo = get(vedge_pmap,v)->link_info;
    out << "[";
    crope style;
    crope color;
    crope label;
    switch (linfo.type) {
    case tb_link_info::LINK_UNKNOWN: style="dotted";color="red"; break;
    case tb_link_info::LINK_DIRECT: style="dashed";color="black"; break;
    case tb_link_info::LINK_INTRASWITCH:
      style="solid";color="black";
      label=get(pvertex_pmap,linfo.switches.front())->name;
      break;
    case tb_link_info::LINK_INTERSWITCH:
      style="solid";color="blue";
      label="";
      for (pvertex_list::const_iterator it=linfo.switches.begin();
	   it!=linfo.switches.end();++it) {
	label += get(pvertex_pmap,*it)->name;
	label += " ";
1491
      }
1492 1493
      break;
    case tb_link_info::LINK_TRIVIAL: style="dashed";color="blue"; break;
1494
    }
1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531
    out << "style=" << style << " color=" << color;
    if (label.size() != 0) {
      out << " label=\"" << label << "\"";
    }
    out << "]";
  }
};

struct solution_vertex_writer {
  void operator()(ostream &out,const vvertex &v) const {
    tb_vnode *vnode = get(vvertex_pmap,v);
    crope label=vnode->name;
    crope color;
    if (absassigned[v]) {
      label += " ";
      label += get(pvertex_pmap,absassignment[v])->name;
      color = "black";
    } else {
      color = "red";
    }
    crope style;
    if (vnode->fixed) {
      style="dashed";
    } else {
      style="solid";
    }
    out << "[label=\"" << label << "\" color=" << color <<
      " style=" << style << "]";
  }
};

void print_help()
{
  cerr << "assign [options] ptopfile topfile [config params]" << endl;
  cerr << "Options: " << endl;
#ifdef TIME_TERMINATE
  cerr << "  -l <time>   - Limit runtime." << endl;
1532
#endif
1533 1534 1535 1536 1537 1538 1539
  cerr << "  -s <seed>   - Set the seed." << endl;
  cerr << "  -v <viz>    - Produce graphviz files with given prefix." <<
    endl;
  cerr << "  -r          - Don't allow trivial links." << endl;
  cerr << "  -p          - Disable pclasses." << endl;
  exit(0);
}
1540

1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554
int main(int argc,char **argv)
{
  int seed = 0;
  crope viz_prefix;
  
  // Handle command line
  char ch;
  timelimit = 0.0;
  timetarget = 0.0;
  while ((ch = getopt(argc,argv,"s:v:l:t:rp")) != -1) {
    switch (ch) {
    case 's':
      if (sscanf(optarg,"%d",&seed) != 1) {
	print_help();
1555
      }
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
      break;
    case 'v':
      viz_prefix = optarg;
      break;
#ifdef TIME_TERMINATE
    case 'l':
      if (sscanf(optarg,"%lf",&timelimit) != 1) {
	print_help();
      }
      break;
#endif
#ifdef TIME_TARGET
    case 't':
      if (sscanf(optarg,"%lf",&timetarget) != 1) {
	print_help();
      }
      break;
1573
#endif
1574 1575 1576 1577 1578 1579
    case 'r':
      allow_trivial_links = false; break;
    case 'p':
      use_pclasses = false; break;
    default:
      print_help();
1580
    }
1581
  }
1582 1583 1584 1585 1586 1587 1588 1589 1590
  argc -= optind;
  argv += optind;
  
  if (seed == 0) {
    if (getenv("ASSIGN_SEED") != NULL) {
      sscanf(getenv("ASSIGN_SEED"),"%d",&seed);
    } else {
      seed = time(NULL)+getpid();
    }
1591
  }
1592 1593 1594 1595

  if (viz_prefix.size() == 0) {
    if (getenv("ASSIGN_GRAPHVIZ") != NULL) {
      viz_prefix = getenv("ASSIGN_GRAPHVIZ");
1596
    }
1597
  }
Mac Newbold's avatar
Mac Newbold committed
1598

1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621
  if (argc == 0) {
    print_help();
  }

  // Convert options to the common.h parameters.
  parse_options(argv, options, noptions);
#ifdef SCORE_DEBUG
  dump_options("Configuration options:", options, noptions);
#endif

#ifdef GNUPLOT_OUTPUT
  scoresout = fopen("scores.out","w");
  tempout = fopen("temp.out","w");
  deltaout = fopen("delta.out","w");
#endif

  cout << "seed = " << seed << endl;
  std::srandom(seed);

  read_physical_topology(argv[0]);
  calculate_switch_MST();
  
  cout << "Generating physical equivalence classes:";
1622
  generate_pclasses(PG);
1623
  cout << pclasses.size() << endl;
1624

1625 1626 1627
#ifdef PCLASS_DEBUG
  pclass_debug();
#endif
1628 1629 1630

  read_virtual_topology(argv[1]);
 
1631
  cout << "Type preecheck:" << endl;
1632 1633
  // Type precheck
  bool ok=true;
1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655
  for (name_count_map::iterator vtype_it=vtypes.begin();
       vtype_it != vtypes.end();++vtype_it) {
    
    // Ignore LAN vnodes
    if (vtype_it->first == crope("lan")) {
	continue;
    }

    // Check to see if there were any pnodes of the type at all
    name_count_map::iterator ptype_it = ptypes.find(vtype_it->first);
    if (ptype_it == ptypes.end()) {
      cout << "  *** No physical nodes of type " << vtype_it->first << " found"
        << endl;
      ok = false;
    } else {
      // Okay, there are some - are there enough?
      if (ptype_it->second < vtype_it->second) {
	cout << "  *** " << vtype_it->second << " nodes of type " <<
	  vtype_it->first << " requested, but only " << ptype_it->second <<
	  " found" << endl;
	ok = false;
      }
1656 1657 1658 1659
    }
  }
  if (! ok) exit(-1);

1660
  cout << "Type preecheck passed." << endl;
1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736

#ifdef PER_VNODE_TT
  vvertex_iterator vit,vendit;
  tie(vit,vendit) = vertices(VG);

  for (;vit != vendit;vit++) {
      tb_vnode *v = get(vvertex_pmap,*vit);
      int size = type_table[v->type].first;
      pclass_vector *vec = new pclass_vector(size); // Could be an over-estimate
      vnode_type_table[v->name] = tt_entry(size,vec);
      pclass_vector::iterator it;
      int i = 0;
      // No reason to look for these for LAN nodes!
      if (!v->type.compare("lan")) {
	  continue;
      }
      for (it = type_table[v->type].second->begin();
	      it != type_table[v->type].second->end(); it++) {
	  tb_pnode *first = *((*it)->members[v->type]->L.begin());
	  //cout << "Checking " << first->total_interfaces << " >= " <<
	  //    v->num_links << " ";
	  if ((first->total_interfaces >= v->num_links) ||
		  (first->types[v->type] > 1)) {
	      (*vec)[i++] = *it;
	      //cout << "Allowing!" << endl;
	  } else {
	      //cout << "Skipping!" << endl;
	      vnode_type_table[v->name].first--;
	  }
      }
      assert(vnode_type_table[v->name].first >= 0);
      if (vnode_type_table[v->name].first == 0) {
	  cerr << "No possible mapping for " << v->name;
	  exit(1);
      }
#ifdef PCLASS_DEBUG
      cerr << v->name << " can map to " << vnode_type_table[v->name].first << " pclasses"
	  << endl;
#endif

  }
#endif

  // Output graphviz if necessary
  if (viz_prefix.size() != 0) {
    crope vviz = viz_prefix + "_virtual.viz";
    crope pviz = viz_prefix + "_physical.viz";
    crope sviz = viz_prefix + "_switch.viz";
    ofstream vfile,pfile,sfile;
    vfile.open(vviz.c_str());
    write_graphviz(vfile,VG,vvertex_writer(),vedge_writer(),graph_writer());
    vfile.close();
    pfile.open(pviz.c_str());
    write_graphviz(pfile,PG,pvertex_writer(),pedge_writer(),graph_writer());
    pfile.close();
    sfile.open(sviz.c_str());
    write_graphviz(sfile,SG,svertex_writer(),sedge_writer(),graph_writer());
    sfile.close();
  }
 
  timestart = used_time();
  anneal();
  timeend = used_time();
#ifdef GNUPLOT_OUTPUT
  fclose(scoresout);
  fclose(tempout);
  fclose(deltaout);
#endif

  if ((score > absbest) || (violated > absbestviolated)) {
    cerr << "Internal error: Invalid migration assumptions." << endl;
    cerr << "score:" << score << " absbest:" << absbest <<
      " violated:" << violated << " absbestviolated:" <<
      absbestviolated << endl;
    cerr << "  Contact calfeld" << endl;
  }
1737
  
1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753
  cout << "   BEST SCORE:  " << score << " in " << iters <<
    " iters and " << timeend-timestart << " seconds" << endl;
  cout << "With " << violated << " violations" << endl;
  cout << "Iters to find best score:  " << iters_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;
  cout << "  desires:    " << vinfo.desires << endl;
  cout << "  vclass:     " << vinfo.vclass << endl;
  cout << "  delay:      " << vinfo.delay << endl;
#ifdef FIX_PLINK_ENDPOINTS
  cout << "  endpoints:  " << vinfo.incorrect_endpoints << endl;
#endif
1754

1755
  print_solution();
1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770

  if (viz_prefix.size() != 0) {
    crope aviz = viz_prefix + "_solution.viz";
    ofstream afile;
    afile.open(aviz.c_str());
    write_graphviz(afile,VG,solution_vertex_writer(),
		   solution_edge_writer(),graph_writer());
    afile.close();
  }
  
  if (violated > 0) {
      return 2;
  } else {
      return 0;
  }
1771
}
1772