assign.cc 49 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;
Christopher Alfeld's avatar
 
Christopher Alfeld committed
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()
Christopher Alfeld's avatar
 
Christopher Alfeld committed
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);
  }
Christopher Alfeld's avatar
 
Christopher Alfeld committed
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])));
Christopher Alfeld's avatar
 
Christopher Alfeld committed
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;
Christopher Alfeld's avatar
 
Christopher Alfeld committed
355
  
356
  tb_pnode *newpnode;
Christopher Alfeld's avatar
 
Christopher Alfeld committed
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
#ifdef LOAD_BALANCE
REDO_SEARCH:
    tb_pnode* firstmatch = NULL;
#endif
#ifdef FIND_PNODE_SEARCH
375 376 377 378 379 380 381 382 383 384
#ifdef PER_VNODE_TT
    // If using PER_VNODE_TT and vclasses, it's possible that there are
    // some pclasses in this node's type table that can't be used right now,
    // becuase they contain entires that don't contain the vnodes _current_
    // type
    if ((*acceptable_types)[i]->members.find(vn->type) ==
	    (*acceptable_types)[i]->members.end()) {
	continue;
    }
#endif
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 449 450 451 452 453 454 455 456 457 458
    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
  }
Christopher Alfeld's avatar
 
Christopher Alfeld committed
459
}
Mac Newbold's avatar
Mac Newbold committed
460

461 462 463 464
/* When this is finished the state will reflect the best solution found. */
void anneal()
{
  cout << "Annealing." << endl;
Mac Newbold's avatar
Mac Newbold committed
465

466 467 468 469 470 471 472 473
  double newscore = 0;
  double bestscore = 0;
  
  iters = 0;
  iters_to_best =0;
  accepts = 0;
  
  double scorediff;
474

475 476 477 478 479 480 481
  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
482 483 484
#ifdef STATS
  cout << "STATS_OPTIMAL = " << optimal << endl;
#endif
485

Mac Newbold's avatar
Mac Newbold committed
486 487
  int mintrans = (int)cycles;
  int trans;
488 489 490
  int naccepts = 20*(nnodes + PHYSICAL(npnodes));
  pvertex oldpos;
  bool oldassigned;
Mac Newbold's avatar
Mac Newbold committed
491
  int bestviolated;
492
  int num_fixed=0;
493 494 495
  double meltedtemp;
  double temp = init_temp;
  double deltatemp, deltaavg;
496 497 498

#ifdef VERBOSE
  cout << "Initialized to cycles="<<cycles<<" optimal="<<optimal<<" mintrans="
499
       << mintrans<<" naccepts="<<naccepts<< endl;
500
#endif
501

Mac Newbold's avatar
Mac Newbold committed
502 503 504
  /* Set up the initial counts */
  init_score();

505
  /* Set up fixed nodes */
506 507 508 509 510
  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;
511 512
      exit(1);
    }
513 514 515 516
    vvertex vv = vname2vertex[(*fixed_it).first];
    if (pname2vertex.find((*fixed_it).second) == pname2vertex.end()) {
      cerr << "Fixed node: " << (*fixed_it).second <<
	" not available." << endl;
517 518
      exit(1);
    }
519 520 521 522 523
    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";
524 525
      exit(1);
    }
526 527 528
    if (add_node(vv,pv,false) == 1) {
      cerr << "Fixed node: Could not map " << vn->name <<
	" to " << pn->name << endl;
529 530
      exit(1);
    }
531
    vn->fixed = true;
532
    num_fixed++;
533
  }
534

Mac Newbold's avatar
Mac Newbold committed
535 536
  bestscore = get_score();
  bestviolated = violated;
537

538 539
#ifdef VERBOSE
  cout << "Problem started with score "<<bestscore<<" and "<< violated
540
       << " violations." << endl;
541
#endif
542

Mac Newbold's avatar
Mac Newbold committed
543
  absbest = bestscore;
544 545 546 547 548 549 550 551 552 553 554 555 556 557
  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()));
    }
558 559
  }

560 561 562 563 564 565 566 567
  int neighborsize;
  neighborsize = nnodes * npclasses;
  if (neighborsize < min_neighborhood_size) {
    neighborsize = min_neighborhood_size;
  }
#ifdef CHILL
  double scores[neighborsize];
#endif
568 569 570 571

  if (num_fixed == nnodes) {
    cout << "All nodes are fixed.  No annealing." << endl;
    goto DONE;
Mac Newbold's avatar
Mac Newbold committed
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 617 618 619 620 621 622 623 624 625 626
  
  // 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
627

628 629 630 631 632
  melt_trans = neighborsize;
#ifdef EPSILON_TERMINATE
//  while ((initialavg) && ((temp * avgscore / initialavg) >= epsilon)) {
  while(1) {
#else
633
  while (temp >= temp_stop) {
634
#endif
Mac Newbold's avatar
Mac Newbold committed
635
#ifdef VERBOSE
636 637
    cout << "Temperature:  " << temp << " AbsBest: " << absbest <<
      " (" << absbestviolated << ")" << endl;
Mac Newbold's avatar
Mac Newbold committed
638 639 640
#endif
    trans = 0;
    accepts = 0;
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
    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
658 659 660 661

#ifdef STATS
      cout << "STATS temp:" << temp << " score:" << get_score() <<
	" violated:" << violated << " trans:" << trans <<
662 663 664 665
	" accepts:" << accepts << " current_time:" <<
	used_time() << endl;
#endif 
      pvertex newpos;
Mac Newbold's avatar
Mac Newbold committed
666 667 668
      trans++;
      iters++;

669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
      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;
	}
Christopher Alfeld's avatar
 
Christopher Alfeld committed
695
      }
696 697 698 699 700 701 702 703 704 705
      
      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;)
706
      }
707 708 709 710
#endif
      
      if (vn->vclass != NULL) {
	vn->type = vn->vclass->choose_type();
711
#ifdef SCORE_DEBUG
712 713
	cerr << "vclass " << vn->vclass->name  << ": choose type = "
	     << vn->type << " dominant = " << vn->vclass->dominant << endl;
714
#endif
715
      }
716 717 718 719 720 721 722
      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
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 888 889 890 891 892 893 894 895 896 897
#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;
	      }
898
	  }
899
#ifndef SMART_UNMAP
900
	}
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
#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
934

935
#endif
Mac Newbold's avatar
Mac Newbold committed
936

Christopher Alfeld's avatar
 
Christopher Alfeld committed
937
      newscore = get_score();
938 939 940 941 942 943 944 945 946 947 948 949 950 951
      /*
      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;
Christopher Alfeld's avatar
 
Christopher Alfeld committed
952 953
      
      // Negative means bad
Mac Newbold's avatar
Mac Newbold committed
954
      scorediff = bestscore - newscore;
955 956 957 958 959 960 961 962 963
      // 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++;
      }
Christopher Alfeld's avatar
 
Christopher Alfeld committed
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 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
      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
1013 1014
	bestscore = newscore;
	bestviolated = violated;
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
#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
1025
	accepts++;
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037

#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
1038
	     (newscore < absbest))) {
1039 1040 1041 1042 1043 1044 1045 1046 1047
#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
1048 1049
	  }
	  absbest = newscore;
1050 1051 1052 1053 1054
	  absbestviolated = violated;
	  iters_to_best = iters;
#ifdef SCORE_DEBUG
	  cerr << "New best recorded" << endl;
#endif
Mac Newbold's avatar
Mac Newbold committed
1055 1056
	}
	if (newscore < optimal) {
1057
	  cout << "OPTIMAL ( " << optimal << ")" << endl;
Mac Newbold's avatar
Mac Newbold committed
1058 1059
	  goto DONE;
	}
Christopher Alfeld's avatar
 
Christopher Alfeld committed
1060 1061 1062
	// Accept change
      } else {
	// Reject change
1063 1064 1065 1066 1067 1068 1069
	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
1070 1071
	}
      }
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091

      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
1092 1093
    }

1094 1095 1096
#ifdef RANDOM_ASSIGNMENT
      if (violated == 0) {
	  finished = true;
1097
      }
1098 1099 1100 1101 1102
#endif

#ifdef REALLY_RANDOM_ASSIGNMENT
      if (unassigned_nodes.size() == 0) {
	  finished = true;
1103
      }
1104 1105 1106 1107 1108 1109
#endif

NOTQUITEDONE:
   /* if (melting) {
	printf("Melting: avgscore: %f = %f / %i\n",avgscore / melttrials,avgscore,melttrials);
      avgscore = avgscore / melttrials;
1110
    } else {
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 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
    */
      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
1155 1156 1157
    }


1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
#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
1179
    
1180 1181 1182 1183
    // 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
1184 1185


1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
    // 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
1202

1203 1204 1205 1206 1207 1208 1209
#ifdef LOCAL_DERIVATIVE
    deltaavg = lastsmoothed - smoothedavg;
    deltatemp = lasttemp - temp;
#else
    deltaavg = initialavg - smoothedavg;
    deltatemp = meltedtemp - temp;
#endif
1210

1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
    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
1242

1243 1244 1245 1246 1247
    bool revert = false;
    if (forcerevert) {
	cout << "Reverting: forced" << endl;
	revert = true;
    }
1248

1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
#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
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 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
    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;
1335 1336
}

Mac Newbold's avatar
Mac Newbold committed
1337 1338
void print_solution()
{
1339 1340 1341
  vvertex_iterator vit,veit;
  tb_vnode *vn;
  
Mac Newbold's avatar
Mac Newbold committed
1342
  cout << "Nodes:" << endl;
1343 1344 1345 1346 1347
  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
1348
    } else {
1349 1350
      cout << vn->name << " "
	   << get(pvertex_pmap,vn->assignment)->name << endl;
Mac Newbold's avatar
Mac Newbold committed
1351 1352 1353 1354
    }
  }
  cout << "End Nodes" << endl;
  cout << "Edges:" << endl;
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
  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
1370
	")" << endl;
1371
    } else if (vlink->link_info.type == tb_link_info::LINK_INTERSWITCH) {
1372
      cout << " interswitch ";
1373 1374 1375 1376 1377
      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 << ")";