anneal.cc 38.4 KB
Newer Older
1
/*
Robert Ricci's avatar
Robert Ricci committed
2
 * Copyright (c) 2003-2010 University of Utah and the Flux Group.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 * 
 * {{{EMULAB-LICENSE
 * 
 * This file is part of the Emulab network testbed software.
 * 
 * This file is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or (at
 * your option) any later version.
 * 
 * This file is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 * License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License
 * along with this file.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * }}}
22 23
 */

24 25
static const char rcsid[] = "$Id: anneal.cc,v 1.46 2009-05-20 18:06:07 tarunp Exp $";

26 27
#include "anneal.h"

28 29 30 31 32 33
#include "virtual.h"
#include "maps.h"
#include "common.h"
#include "score.h"
#include "solution.h"
#include "vclass.h"
34
#include "neighborhood.h"
35

36 37 38 39
/*
 * Internal variables
 */
// These variables store the best solution.
40
solution best_solution;
41 42 43 44 45 46 47 48 49 50 51

// 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 physical node name to its vertex descriptor.
name_pvertex_map pname2vertex;
  
52
// Map of virtual node name to the physical node name it's fixed to.
53 54 55 56
// 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;

57 58 59 60 61
// Map of virtual node name to the physical node name that we should
// start the virtual node on. However, unlike fixed nodes, assign is
// allowed to move these.
name_name_map node_hints;

62 63 64 65 66
// From assign.cc
#ifdef GNUPLOT_OUTPUT
extern FILE *scoresout, *tempout, *deltaout;
#endif

67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
/*
 * Parameters used to control annealing
 */
int init_temp = 10;
int temp_prob = 130;
#ifdef LOW_TEMP_STOP
float temp_stop = .005;
#else
float temp_stop = 2;
#endif
int CYCLES = 20;

// The following are basically arbitrary constants
// Initial acceptance ratio for melting
float X0 = .95;
#ifdef LOCAL_DERIVATIVE
float epsilon = 0.0001;
#else
float epsilon = 0.01;
#endif
float delta = 2;

// Number of runs to spend melting
int melt_trans = 1000;
int min_neighborhood_size = 1000;

float temp_rate = 0.9;


96 97
// Determines whether to accept a change of score difference 'change' at
// temperature 'temperature'.
98
inline bool accept(double change, double temperature) {
99 100 101 102 103 104 105 106
  double p;
  int r;

  if (change == 0) {
    p = 1000 * temperature / temp_prob;
  } else {
    p = expf(change/temperature) * 1000;
  }
107
  r = RANDOM() % 1000;
108 109 110 111 112 113
  if (r < p) {
    return 1;
  }
  return 0;
}

114 115 116
// We put the temperature outside the function so that external stuff, like
// status_report in assign.cc, can see it.
double temp;
117 118

/* When this is finished the state will reflect the best solution found. */
119 120 121
void anneal(bool scoring_selftest, bool check_fixed_nodes,
        double scale_neighborhood, double *initial_temperature,
        double use_connected_pnode_find)
122 123 124
{
  cout << "Annealing." << endl;

125 126 127 128 129 130 131 132 133 134 135 136
  /*
   * The score and number of violations at the start of the inner annealing
   * loop
   */
  double prev_score = 0;
  int prev_violated = 0;

  /*
   * 
   */
  double new_score = 0;
  double scorediff;
137 138 139 140 141 142 143 144
 
  // The number of iterations that took place.
  iters = 0;
  iters_to_best = 0;
  int accepts = 0;
  

  int nnodes = num_vertices(VG);
145
  //int npnodes = num_vertices(PG);
146 147 148 149 150 151 152 153 154 155 156
  int npclasses = pclasses.size();
  
  float cycles = CYCLES*(float)(nnodes + num_edges(VG) + PHYSICAL(npnodes));

  int mintrans = (int)cycles;
  int trans;
  int naccepts = 20*(nnodes + PHYSICAL(npnodes));
  pvertex oldpos;
  bool oldassigned;
  int num_fixed=0;
  double meltedtemp;
157
  temp = init_temp;
158 159
  double deltatemp, deltaavg;

160
  // List of unassigned virtual nodes
161
  list<vvertex> unassigned_nodes;
162 163

#ifdef VERBOSE
164
  cout << "Initialized to cycles="<<cycles<<" mintrans="
165 166 167 168 169 170 171
       << mintrans<<" naccepts="<<naccepts<< endl;
#endif

  /* Set up the initial counts */
  init_score();

  /* Set up fixed nodes */
172 173 174 175 176
  /* Count of nodes which could not be fixed - we wait until we've tried to fix
   * all nodes before bailing, so that the user gets to see all of the
   * messages.
   */
  int fix_failed = 0;
177 178 179
  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()) {
180
      cout << "*** Fixed virtual node: " << (*fixed_it).first <<
181
	" does not exist." << endl;
182 183
      fix_failed++;
      continue;
184 185 186
    }
    vvertex vv = vname2vertex[(*fixed_it).first];
    if (pname2vertex.find((*fixed_it).second) == pname2vertex.end()) {
187
      cout << "*** Fixed physical node: " << (*fixed_it).second <<
188
	" not available." << endl;
189 190
      fix_failed++;
      continue;
191 192 193 194 195
    }
    pvertex pv = pname2vertex[(*fixed_it).second];
    tb_vnode *vn = get(vvertex_pmap,vv);
    tb_pnode *pn = get(pvertex_pmap,pv);
    if (vn->vclass != NULL) {
196 197 198 199 200 201 202 203 204 205 206 207
      // Find a type on this physical node that can satisfy something in the
      // virtual class
      if (pn->typed) {
        if (vn->vclass->has_type(pn->current_type)) {
          vn->type = pn->current_type;
        }
      } else {
        for (tb_pnode::types_list::iterator i = pn->type_list.begin();
            i != pn->type_list.end(); i++) {
          // For now, if we find more than one match, we pick the first. It's
          // possible that picking some other type would give us a better
          // score, but let's noty worry about that
208 209
          if (vn->vclass->has_type((*i)->get_ptype()->name())) {
            vn->type = (*i)->get_ptype()->name();
210 211 212 213 214
            break;
          }
        }
      }
      if (vn->type.empty()) {
215 216
        // This is an internal error, so it's okay to handle it in a different
        // way from the others
217
        cout << "*** Unable to find a type for fixed, vtyped, node " << vn->name
218 219 220 221 222 223
          << endl;
        exit(EXIT_FATAL);
      } else {
        cout << "Setting type of vclass node " << vn->name << " to "
          << vn->type << "\n";
      }
224
    }
225 226 227 228 229 230 231 232 233 234 235

    /*
     * Normally, we want to bypass some checks in add_node for fixed nodes -
     * but not always (usually for testing purposes).
     */
    bool skip_checks = true;
    if (check_fixed_nodes) {
        skip_checks = false;
    }

    if (add_node(vv,pv,false,skip_checks,false) == 1) {
236
      cout << "*** Fixed node: Could not map " << vn->name <<
237
	" to " << pn->name << endl;
238 239
      fix_failed++;
      continue;
240 241
    }
    vn->fixed = true;
242 243 244 245 246 247
    /*
    if (vn->vclass != NULL) {
      vn->type = vn->vclass->choose_type();
      cout << "Picked type " << vn->type << " for " << vn->name << endl;
    }
    */
248 249 250
    num_fixed++;
  }

251 252 253 254 255
  if (fix_failed){
    cout << "*** Some fixed nodes failed to map" << endl;
    exit(EXIT_UNRETRYABLE);
  }

256 257 258 259
  // Subtract the number of fixed nodes from nnodes, since they don't really
  // count
  if (num_fixed) {
      cout << "Adjusting dificulty estimate for fixed nodes, " <<
260
	  (nnodes - num_fixed) << " remain.\n";
261 262
  }

263 264 265 266
  /* We'll check against this later to make sure that whe we've unmapped
   * everything, the score is the same */
  double initial_score = get_score();

267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
  /*
   * Handle node hints - we do this _after_ we've figured out the initial
   * score, since, unlike fixed nodes, hints get unmapped before we do the
   * final mapping. Also, we ignore any hints for vnodes which have already
   * been assigned - they must have been fixed, and that over-rides the hint.
   */
  for (name_name_map::iterator hint_it=node_hints.begin();
       hint_it!=node_hints.end();++hint_it) {
    if (vname2vertex.find((*hint_it).first) == vname2vertex.end()) {
      cout << "Warning: Hinted node: " << (*hint_it).first <<
	"does not exist." << endl;
      continue;
    }
    vvertex vv = vname2vertex[(*hint_it).first];
    if (pname2vertex.find((*hint_it).second) == pname2vertex.end()) {
      cout << "Warning: Hinted node: " << (*hint_it).second <<
	" not available." << endl;
      continue;
    }
    pvertex pv = pname2vertex[(*hint_it).second];
    tb_vnode *vn = get(vvertex_pmap,vv);
    tb_pnode *pn = get(pvertex_pmap,pv);
    if (vn->assigned) {
      cout << "Warning: Skipping hint for node " << vn->name << ", which is "
	<< "fixed in place" << endl;
      continue;
    }
294
    if (add_node(vv,pv,false,false,false) == 1) {
295 296 297 298 299
      cout << "Warning: Hinted node: Could not map " << vn->name <<
	" to " << pn->name << endl;
      continue;
    }
  }
300 301 302 303
       
  /*
   * Find out the starting temperature
   */
304 305
  prev_score = get_score();
  prev_violated = violated;
306 307

#ifdef VERBOSE
308
  cout << "Problem started with score "<<prev_score<<" and "<< violated
309 310 311
       << " violations." << endl;
#endif

312 313
  best_score = prev_score;
  best_violated = prev_violated;
314

315 316 317
  /*
   * Make a list of all nodes that are still unassigned
   */
318 319 320 321 322
  vvertex_iterator vit,veit;
  tie(vit,veit) = vertices(VG);
  for (;vit!=veit;++vit) {
    tb_vnode *vn = get(vvertex_pmap,*vit);
    if (vn->assigned) {
323 324
	best_solution.set_assignment(*vit,vn->assignment);
	best_solution.set_vtype_assignment(*vit,vn->type);
325
    } else {
326
	best_solution.clear_assignment(*vit);
327
	unassigned_nodes.push_front(*vit);
328 329
    }
  }
330 331 332 333 334 335 336 337 338 339 340 341
  
  /*
   * Set any links that have been assigned
   */
  vedge_iterator eit, eeit;
  tie(eit, eeit) = edges(VG);
  for (;eit!=eeit;++eit) {
      tb_vlink *vlink = get(vedge_pmap, *eit);
      if (vlink->link_info.type_used != tb_link_info::LINK_UNMAPPED) {
	  best_solution.set_link_assignment(*eit,vlink->link_info);
      }
  }
342

343 344 345 346 347 348
  /*
   * The neighborhood size is the number of solutions we can reach with one
   * transition operation - it's roughly the number of virtual nodes times the
   * number of pclasses. This is how long we usually stick with a given 
   * temperature.
   */
349
  int neighborsize;
350
  neighborsize = (nnodes - num_fixed) * npclasses;
351 352 353
  if (neighborsize < min_neighborhood_size) {
    neighborsize = min_neighborhood_size;
  }
354 355 356 357 358

  // Allow scaling of the neighborhood size, so we can make assign try harder
  // (or less hard)
  neighborsize = (int)(neighborsize * scale_neighborhood);

359 360 361 362
#ifdef CHILL
  double scores[neighborsize];
#endif

363
  if (num_fixed >= nnodes) {
364 365 366 367 368 369 370 371
    cout << "All nodes are fixed.  No annealing." << endl;
    goto DONE;
  }
  
  vvertex vv;
  tb_vnode *vn;

  // Crap added by ricci
372
#ifdef MELT
373
  bool melting;
374
#endif
375 376 377 378 379
  int nincreases, ndecreases;
  double avgincrease;
  double avgscore;
  double initialavg;
  double stddev;
380 381 382 383 384
  bool finished; 
  bool forcerevert; 
  // Lame, we have to do this on a seperate line, or the compiler gets mad about
  // the goto above crossing initialization. Well, okay, okay, I know the goto
  // itself is lame....
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
  finished = forcerevert = false;
  int tsteps;
  int mintsteps;

#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;

415 416 417
  /*
   * Initial temperature calcuation/melting
   */
418
#ifdef MELT
419 420 421 422 423 424 425
  if (initial_temperature == NULL) {
      melting = true;
  } else {
      melting = false;
      temp = *initial_temperature;
      cout << "Starting with initial temperature " << temp << endl;
  }
426 427 428 429 430 431 432
#ifdef TIME_TARGET
  meltstart = used_time();
#endif
#else
  melting = false;
#endif

433
  /*
434 435
   * When melting, this is the number of different solutions we will try during
   * this temperature step
436
   */
437
  melt_trans = neighborsize;
438 439 440 441 442 443 444 445
  
  /*
   * The main annealing loop!
   * Each iteration is a temperature step - how we get out of the loop depends
   * on what the termination condition is. Normally, we have a target temperature
   * at which we stop, but with EPSILON_TERMINATE, we watch the derivative of the
   * average temperature, and break out of the loop when it gets small enough.
   */
446 447 448 449 450
#ifdef EPSILON_TERMINATE
  while(1) {
#else
  while (temp >= temp_stop) {
#endif
451
      
452
#ifdef VERBOSE
453 454
    cout << "Temperature:  " << temp << " Best: " << best_score <<
      " (" << best_violated << ")" << endl;
455
#endif
456

457 458 459
    /*
     * Initialize this temperature step
     */
460 461 462 463
    trans = 0;
    accepts = 0;
    nincreases = ndecreases = 0;
    avgincrease = 0.0;
464
    avgscore = prev_score;
465
#ifdef CHILL
466
    scores[0] = prev_score;
467 468
#endif

469 470
    // Adjust the number of transitions we're going to do based on the number
    // of pclasses that are actually 'in play'
471 472
    int transitions = (int)(neighborsize *
      (count_enabled_pclasses() *1.0 / pclasses.size()));
473 474
    assert(transitions <= neighborsize);

475 476 477 478
    if (melting) {
      cout << "Doing melting run" << endl;
    }

479 480 481 482 483 484
    /*
     * The inner loop - 
     * Each iteration of this inner loop corresponds to one attempt to try a new
     * solution. When we're melting, we have a special number of transitions
     * we're shooting for.
     */
485 486
    while ((melting && (trans < melt_trans))
#ifdef NEIGHBOR_LENGTH
487
	    || (trans < transitions)) {
488 489 490 491
#else
	    || (!melting && (trans < mintrans && accepts < naccepts))) {
#endif

492 493 494
    RDEBUG(cout << "ANNEALING: Loop starts with score " << get_score() <<
            " violations " << violated << endl;)

495 496 497 498 499 500 501 502 503 504
#ifdef STATS
      cout << "STATS temp:" << temp << " score:" << get_score() <<
	" violated:" << violated << " trans:" << trans <<
	" accepts:" << accepts << " current_time:" <<
	used_time() << endl;
#endif 
      pvertex newpos;
      trans++;
      iters++;

505 506 507 508 509 510
      /*
       * Find a virtual node to map -
       * If there are any virtual nodes that are not yet mapped, start with
       *   those
       * If not, find some other random vnode, which we'll unmap then remap
       */
511
      if (! unassigned_nodes.empty()) {
512 513
        // Pick a random node from the list of unassigned nodes
        int choice = RANDOM() % unassigned_nodes.size();
514
        list<vvertex>::iterator uit = unassigned_nodes.begin();
515 516 517 518
        for (int i = 0; i < choice; i++) { uit++; }
        assert(uit != unassigned_nodes.end());

        vv = *uit;
519
	assert(!get(vvertex_pmap,vv)->assigned);
520 521 522 523
        unassigned_nodes.erase(uit);
        RDEBUG(cout << "Using unassigned node " << choice << ": " <<
                get(vvertex_pmap,vv)->name << " (" <<
                unassigned_nodes.size() << " in queue)" << endl;)
524
      } else {
525
	int start = RANDOM()%nnodes;
526 527 528 529 530 531 532 533 534 535 536
	int choice = start;
	while (get(vvertex_pmap,virtual_nodes[choice])->fixed) {
	  choice = (choice +1) % nnodes;
	  if (choice == start) {
	      choice = -1;
	      break;
	  }
	}
	if (choice >= 0) {
	    vv = virtual_nodes[choice];
	} else {
537
	    cout << "**** Error, unable to find any non-fixed nodes" << endl;
538 539
	    goto DONE;
	}
540
      }      
541 542
      vn = get(vvertex_pmap,vv);
      RDEBUG(cout << "Reassigning " << vn->name << endl;)
543 544 545 546
	  
      /*
       * Keep track of the old assignment for this node
       */
547 548
      oldassigned = vn->assigned;
      oldpos = vn->assignment;
549 550 551 552 553

      if (oldassigned) {
          RDEBUG(cout << "   was assigned to " <<
                  get(pvertex_pmap,oldpos)->name << endl;)
      }
554
      
555 556 557 558 559
      /*
       * Problem: If we free the chosen vnode now, we might just try remapping
       * it to the same pnode. If FREE_IMMEDIATELY is not set, we do the 
       * later, after we've chosen a pnode unmapping
       */
560 561 562 563 564 565 566
#ifdef FREE_IMMEDIATELY
      if (oldassigned) {
	remove_node(vv);
	RDEBUG(cout << "Freeing up " << vn->name << endl;)
      }
#endif
      
567 568 569 570
      /*
       * We have to handle vnodes with vtypes (vclasses) specially - we have
       * to make the vtype pick a type to masquerade as for now.
       */
571 572 573
      if (vn->vclass != NULL) {
	vn->type = vn->vclass->choose_type();
#ifdef SCORE_DEBUG
574
	cerr << "vclass " << vn->vclass->get_name()  << ": choose type for " <<
575
	    vn->name << " = " << vn->type << " dominant = " <<
576
	    vn->vclass->get_dominant() << endl;
577 578
#endif
      }
579 580 581 582 583 584 585
      
      // Did we free a node?
      bool freednode = false;
      
      /* 
       * Find a pnode to map this vnode to
       */
586 587
      tb_pnode *newpnode = NULL;
      if ((use_connected_pnode_find != 0)
588
	  && ((RANDOM() % 1000) < (use_connected_pnode_find * 1000))) {
589
        RDEBUG(cout << "   using find_pnode_connected" << endl;)
590 591
	newpnode = find_pnode_connected(vv,vn);
      }
592 593 594 595 596
      
      /* 
       * If not using the connected find, or it failed to find a node, then
       * fall back on the regular algorithm to find a pnode
       */
597
      if (newpnode == NULL) {
598
        RDEBUG(cout << "   using find_pnode" << endl;)
599 600
	newpnode = find_pnode(vn);
      }
601 602 603 604
      
      /*
       * If we didn't free the vnode up above, do it now
       */
605
#ifndef FREE_IMMEDIATELY
606 607
      if (oldassigned) {
	RDEBUG(cout << "removing: !lan, oldassigned" << endl;)
608
	remove_node(vv);
609
      }
610
#endif
611 612 613 614 615
      
      /*
       * If we didn't find a node to map this vnode to, free up some other
       * vnode so that we can make progress - otherwise, we could get stuck
       */
616
      if (newpnode == NULL) {
617
	// Push this node back onto the unassigned map
618
	unassigned_nodes.push_front(vv);
619
	int start = RANDOM()%nnodes;
620
	int toremove = start;
621 622 623 624 625
	while (get(vvertex_pmap,virtual_nodes[toremove])->fixed ||
	       (! get(vvertex_pmap,virtual_nodes[toremove])->assigned)) {
	    toremove = (toremove +1) % nnodes;
	  if (toremove == start) {
	    toremove = -1;
626
            RDEBUG(cout << "Not removing a node" << endl;)
627 628
	    break;
	  }	
629 630 631 632 633 634 635
        }	
        if (toremove >= 0) {
          RDEBUG(cout << "removing: freeing up node " <<
                  get(vvertex_pmap,virtual_nodes[toremove])->name << endl;)
          remove_node(virtual_nodes[toremove]);
          unassigned_nodes.push_front(virtual_nodes[toremove]);
        }	
636
      
637 638 639 640 641 642 643
        /*
         * Start again with another vnode - which will probably be the same one,
         * since we just marked it as unmapped. But now, there will be at least one
         * free pnode
         */
        RDEBUG(cout << "Failed to find a possible mapping; try again..." << endl;)
        continue;	
644 645 646 647 648 649
      }
    
      /*
       * Okay, we've got pnode to map this vnode to - let's do it
       */
      if (newpnode != NULL) {	
650
        RDEBUG(cout << "MOVE: " << vn->name << " to " << newpnode->name << " " << endl;)
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
        newpos = pnode2vertex[newpnode];
        if (scoring_selftest) {
	  // Run a little test here - see if the score we get by adding	
	  // this node, then removing it, is the same one we had before
	  double oldscore = get_score();
	  int oldviolated = violated;
	  double tempscore;
	  int tempviolated;
	  if (!add_node(vv,newpos,false,false,false)) {
	    tempscore = get_score();
	    tempviolated = violated;
	    remove_node(vv);
	  }	
	  if ((oldscore != get_score()) || (oldviolated != violated)) {
	    cerr << "Scoring problem adding a mapping - oldscore was " <<
666
		oldscore <<  " current score is " << get_score() << " tempscore was "
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
		<< tempscore << endl;
	    cerr << "oldviolated was " << oldviolated << " newviolated is "
		<< violated << " tempviolated was " << tempviolated << endl;
	    cerr << "I was tring to map " << vn->name << " to " <<
		newpnode->name << endl;
	    print_solution(best_solution);
	    cerr << vinfo;
	    abort();
          }
        }
      
        /*
         * Actually try the new mapping - if it fails, the node is still
         * unassigned, and we go back and try with another
         */
        if (add_node(vv,newpos,false,false,false) != 0) {
683
	  unassigned_nodes.push_front(vv);
684
          RDEBUG(cout << "failed" << endl;)
685 686 687 688 689 690 691
	  continue;
        }
      } else { // pnode != NULL
        if (freednode) {
	  continue;
        }	
      }
692

693 694 695
      /*
       * Okay, now that we've mapped some new node, let's check the scoring
       */
696 697
      new_score = get_score();
      assert(new_score >= 0);
698 699

      // Negative means bad
700
      scorediff = prev_score - new_score;
701 702 703
      // This looks funny, because < 0 means worse, which means an increase in
      // score
      if (scorediff < 0) {
704 705 706
        nincreases++;
        avgincrease = avgincrease * (nincreases -1) / nincreases +
  		    (-scorediff)  / nincreases;
707
      } else {
708 709 710 711 712 713 714
        ndecreases++;
      }	
   
      /*
       * Here are all the various conditions for deciding if we're going to accept
       * this transition
       */
715
      bool accepttrans = false;
716
      if (melting) {
717 718 719
        // When melting, we take everything!
	accepttrans = true;
	RDEBUG(cout << "accept: melting" << endl;)
720
      } else {
721
#ifdef NO_VIOLATIONS
722 723
        // Here, we don't consider violations at all, just whether the regular
        // simulated annealing accept conditions
724
	if (new_score < prev_score) {
725
	    accepttrans = true;
726
	    RDEBUG(cout << "accept: better (" << new_score << "," << prev_score
727 728 729
		   << ")" << endl;)
        } else if (accept(scorediff,temp)) {
  	  accepttrans = true;
730 731
	  RDEBUG(cout << "accept: metropolis (" << new_score << ","
		 << prev_score << "," << expf(scorediff/(temp*sensitivity))
732 733
		 << ")" << endl;)
        }
734
#else
735
#ifdef SPECIAL_VIOLATION_TREATMENT
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
        /*
         * In this ifdef, we always accept new solutions that have fewer
         * violations than the old solution, and when we're trying to
         * determine whether or not to accept a new solution with a higher
         * score, we don't take violations into the account.
         *
         * The problem with this shows up at low temperatures. What can often
         * happen is that we accept a solution with worse violations but a
         * better (or similar) score. Then, if we were to try, say the first
         * solution (or a score-equivalent one) again, we'd accept it again.
         *
         * What this leads to is 'thrashing', where we have a whole lot of
         * variation of scores over time, but are not making any real
         * progress. This prevents the cooling schedule from converging for
         * much, much longer than it should really take.
         */
752
        RDEBUG(cout << "CRITERIA: v=" << violated << " bv=" <<
753
                prev_violated << " ns=" << new_score << " ps=" <<
754 755
                prev_score << " sd=" << scorediff << " t=" << temp << endl;)
        if ((violated == prev_violated) && (new_score < prev_score)) {
756
	  accepttrans = true;
757
	  RDEBUG(cout << "accept: better (" << new_score << "," << prev_score
758
		 << ")" << endl;)
759
	} else if (violated < prev_violated) {
760
	  accepttrans = true;
761 762
	  RDEBUG(cout << "accept: better (violations) (" << new_score << ","
		 << prev_score << "," << violated << "," << prev_violated
763 764 765 766 767
		 << ")" << endl;
	    cout << "Violations: (new) " << violated << endl;
	    cout << vinfo;)
        } else if (accept(scorediff,temp)) {
	  accepttrans = true;
768 769
	  RDEBUG(cout << "accept: metropolis (" << new_score << ","
		 << prev_score << "," << scorediff << "," << temp
770 771
		 << ")" << endl;)
        }
772
#else // no SPECIAL_VIOLATION_TREATMENT
773 774 775 776 777 778 779 780 781 782 783
        /*
         * In this branch of the ifdef, we give violations no special
         * treatment when it comes to accepting new solution - we just add
         * them into the score. This makes assign behave in a more 'classic'
         * simulated annealing manner.
         *
         * One consequence, though, is that we have to be more careful with
         * scores. We do not want to be able to get into a situation where
         * adding a violation results in a _lower_ score than a solution with
         * fewer violations.
         */
784 785
        double adjusted_new_score = new_score + violated * VIOLATION_SCORE;
        double adjusted_old_score = prev_score + prev_violated * VIOLATION_SCORE;
786 787 788 789 790 791

        if (adjusted_new_score < adjusted_old_score) {
          accepttrans = true;
        } else if (accept(adjusted_old_score - adjusted_new_score,temp)) {
	  accepttrans = true;
        }
792 793 794 795

#endif // SPECIAL_VIOLATION_TREATMENT

      }
796
#endif // NO_VIOLATIONS
797

798 799 800
      /* 
       * Okay, we've decided to accep this transition - do some bookkeeping
       */
801
      if (accepttrans) {
802 803 804
	// Accept change
	prev_score = new_score;
	prev_violated = violated;
805

806 807
#ifdef GNUPLOT_OUTPUT
	fprintf(tempout,"%f\n",temp);
808
	fprintf(scoresout,"%f\n",new_score);
809
	fprintf(deltaout,"%f\n",-scorediff);
810
#endif // GNUPLOT_OUTPUT
811

812
	avgscore += new_score;
813 814 815 816
	accepts++;

#ifdef CHILL
	 if (!melting) {
817
	     scores[accepts] = new_score;
818
	 }
819
#endif // CHILL
820

821 822 823 824
        /*
         * Okay, if this is the best score we've gotten so far, let's do some
	 * further bookkeeping - copy it into the structures for our best solution
	 */
825
#ifdef NO_VIOLATIONS
826
	if (new_score < best_score) {
827
#else // NO_VIOLATIONS
828 829 830
	if ((violated < best_violated) ||
	    ((violated == best_violated) &&
	     (new_score < best_score))) {
831 832
#endif // NO_VIOLATIONS
	    
833 834
#ifdef SCORE_DEBUG
	  cerr << "New best solution." << endl;
835
#endif // SCORE_DEBUG
836 837
	  tie(vit,veit) = vertices(VG);
	  for (;vit!=veit;++vit) {
838 839 840 841
	      tb_vnode *vnode = get(vvertex_pmap,*vit);
	      if (vnode->assigned) {
		  best_solution.set_assignment(*vit,vnode->assignment);
		  best_solution.set_vtype_assignment(*vit,vnode->type);
842 843 844
	      } else {
		  best_solution.clear_assignment(*vit);
	      }
845
	  }
846
	  
847 848 849 850
	  vedge_iterator edge_it, edge_it_end;
	  tie(edge_it, edge_it_end) = edges(VG);
	  for (;edge_it!=edge_it_end;++edge_it) {
	      tb_vlink *vlink = get(vedge_pmap, *edge_it);
851
	      if (vlink->link_info.type_used != tb_link_info::LINK_UNMAPPED) {
852
		  best_solution.set_link_assignment(*edge_it,vlink->link_info);
853
	      } else {
854
		  best_solution.clear_link_assignment(*edge_it);
855 856 857
	      }
	  }	
	  
858 859
	  best_score = new_score;
	  best_violated = violated;
860 861 862 863 864
	  iters_to_best = iters;
#ifdef SCORE_DEBUG
	  cerr << "New best recorded" << endl;
#endif
	}
865 866
      } else { // !acceptrans
	// Reject change, go back to the state we were in before
867 868 869
	RDEBUG(cout << "removing: rejected change" << endl;)
	remove_node(vv);
	if (oldassigned) {
870
	  add_node(vv,oldpos,false,false,false);
871 872 873
	} else {
          unassigned_nodes.push_front(vv);
        }
874 875
      }

876 877 878 879 880
      /*
       * If we're melting, we do a little extra bookkeeping to do, becuase the
       * goal of melting is to come up with an initial temperature such that
       * almost every transition will be accepted
       */
881 882 883 884 885 886 887
      if (melting) {
	temp = avgincrease /
	  log(nincreases/ (nincreases * X0 - ndecreases * (1 - X0)));
	if (!(temp > 0.0)) {
	    temp = 0.0;
	}
      }
888 889 890 891
      
      /*
       * With TIME_TERMINATE, we just give up after our time limit
       */
892 893 894 895 896 897 898 899 900
#ifdef TIME_TERMINATE
      if (timelimit && ((used_time() - timestart) > timelimit)) {
	printf("Reached end of run time, finishing\n");
	forcerevert = true;
	finished = true;
	goto NOTQUITEDONE;
      }
#endif

901 902
    } /* End of inner annealing loop */
     
903 904

NOTQUITEDONE:
905 906 907 908 909 910 911 912 913
    RDEBUG(printf("avgscore: %f = %f / %i\n",avgscore / (accepts +1),avgscore,accepts+1);)
	
    /*
     * Most of the code past this point concerns itself with the cooling
     * schedule (what the next temperature step should be
     */
	
    // Keep an average of the score over this temperature step	
    avgscore = avgscore / (accepts +1);
914

915 916 917
    /*
     * If we were melting, then we we need to pick an initial temperature
     */
918 919 920 921 922 923 924 925 926 927 928
    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;
      }
929 930 931 932 933
      /*
       * With TIME_TARGET, we look at how long melting took, then use that to
       * estimate how many temperature steps it will take to hit our time
       * target. We adjust our cooling schedule accordingly.
       */
934 935 936 937 938 939 940 941 942 943 944 945 946
#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 {
947 948 949 950 951
      /*
       * The CHILL cooling schedule is the standard one from the Simulated
       * Annealing literature - it lower the temperature based on the standard
       * deviation of the scores of accepted configurations
       */
952 953 954 955 956 957 958 959 960 961 962
#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
963 964 965 966
      /* 
       * This is assign's original cooling schedule - more predictable, but not
       * at all reactive to the problem at hand
       */
967 968 969 970 971
      temp *= temp_rate;
#endif
    }


972 973 974
    /*
     * Debugging
     */
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
#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
    
997 998 999
    RDEBUG(
    printf("temp_end: temp: %f ratio: %f stddev: %f\n",temp,temp * avgscore / initialavg,stddev);
    );
1000

1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
    /*
     * The next section of code deals with termination conditions - how do we
     * decide that we're done?
     */
    
    /*
     * Keep a history of the average scores over the last MAX_AVG_HIST
     * temperature steps. We treat the avghist array like a ring buffer.
     * Add this temperature step to the history, and computer a smoothed
     * average.
     */
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
    smoothedavg = avgscore / (nhist + 1);
    for (int j = 0; j < nhist; j++) {
      smoothedavg += avghist[(hstart + j) % MAX_AVG_HIST] / (nhist + 1);
    }

    avghist[(hstart + nhist) % MAX_AVG_HIST] = avgscore;
    if (nhist < MAX_AVG_HIST) {
      nhist++;
    } else {
      hstart = (hstart +1) % MAX_AVG_HIST;
    }

1024 1025 1026 1027
    /*
     * Are we computing the derivative of the average temperatures over the
     * whole history, or just the most recent one?
     */
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
#ifdef LOCAL_DERIVATIVE
    deltaavg = lastsmoothed - smoothedavg;
    deltatemp = lasttemp - temp;
#else
    deltaavg = initialavg - smoothedavg;
    deltatemp = meltedtemp - temp;
#endif

    lastsmoothed = smoothedavg;
    lasttemp = temp;

1039 1040 1041 1042 1043
    /*
     * EPSILON_TERMINATE means that we define some small number, epsilon, and
     * the derivative of the average change in temperature gets below that
     * epsilon (ie. we have stopped getting improvements in score), we're done
     */
1044 1045 1046 1047 1048
#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));
1049
    );
1050
    if ((tsteps >= mintsteps) &&
1051 1052 1053 1054
    /*
     * ALLOW_NEGATIVE_DELTA controls whether we're willing to stop if the
     * derivative gets small and negative, not just small and positive.
     */
1055
#ifdef ALLOW_NEGATIVE_DELTA
1056 1057 1058
	((temp < 0) || isnan(temp) ||
//	 || (fabs((temp / initialavg) * (deltaavg/ deltatemp)) < epsilon))) {
	 ((temp / initialavg) * (deltaavg/ deltatemp)) < epsilon)) {
1059 1060 1061 1062
#else
	(deltaavg > 0) && ((temp / initialavg) * (deltaavg/ deltatemp) < epsilon)) {
#endif
#ifdef FINISH_HILLCLIMB
1063
        if (!finishedonce && ((best_violated <= violated) && (best_score < prev_score))) {
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
	    // 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
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
    
    /*
     * RANDOM_ASSIGNMENT is not really very random, but we stop after the first
     * valid solution we get
     */
#ifdef RANDOM_ASSIGNMENT
    if (violated == 0) {
       finished = true;
    }
#endif

    /*
     * REALLY_RANDOM_ASSIGNMENT stops after we've assigned all nodes, whether or
     * not our solution is valid
     */
#ifdef REALLY_RANDOM_ASSIGNMENT
    if (unassigned_nodes.size() == 0) {
      finished = true;
    }
#endif
1097

1098 1099 1100 1101 1102 1103 1104
    /*
     * The following section deals with reverting. This is not standard
     * Simulated Annealing at all. In assign, a revert means that we go back
     * to some previous solution (usually a better one). There are lots of
     * things that could trigger this, so we use a bool to check if any of
     * them happened.
     */
1105
    bool revert = false;
1106 1107 1108 1109 1110 1111 1112
    
    /*
     * Some of the termination condidtions force a revert when they decide
     * they're finished. This is fine - of course, we want to return the best
     * solution we ever found, which might not be the one we're sitting at right
     * now.
     */
1113
    if (forcerevert) {
1114 1115 1116 1117 1118 1119
      cout << "Reverting: forced" << endl;
      revert = true;
    }
    if (REVERT_LAST && (temp < temp_stop)) {
       cout << "Reverting: REVERT_LAST" << endl;
       revert = true;
1120 1121
    }

1122 1123 1124 1125 1126 1127 1128 1129 1130
    
    /*
     * Okay, NO_REVERT is not the best possible name for this ifdef. 
     * Historically, assign used to revert to the best solution at the end of
     * every temperature step. This is definitely NOT kosher. In my mind, it
     * assign too susceptible to falling into local minima. Anyhow, the idea is
     * that we go back to the best soltion if the current solution is worse than
     * it either in violations or in score.
     */
1131
#ifndef NO_REVERT
1132
    if (REVERT_VIOLATIONS && (best_violated < violated)) {
1133 1134 1135
	cout << "Reverting: REVERT_VIOLATIONS" << endl;
	revert = true;
    }
1136
    if (best_score < prev_score) {
1137 1138 1139 1140 1141
	cout << "Reverting: best score" << endl;
	revert = true;
    }
#endif

1142 1143 1144 1145 1146 1147 1148 1149 1150
    /*
     * This is the code to do the actual revert.
     * IMPORTANT: At this time, a revert does not take you back to _exactly_ the
     * same state as before, because there are some things, like link
     * assignments, that we don't save. Since the way these get mapped is
     * dependant on the order they happen in, and this order is almost certainly
     * different than the order they got mapped during annealing, there can be
     * discrepancies (ie. now we have violations, when before we had none.)
     */
1151
    vvertex_iterator vvertex_it,end_vvertex_it;
1152
    vedge_iterator vedge_it,end_vedge_it;
1153
    if (revert) {
1154
      cout << "Reverting to best solution\n";
1155 1156 1157
      /*
       * We start out by unmapping every vnode that's currently allocated
       */
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
      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;)
	}
      }
1169 1170 1171

      // Check to make sure that our 'clean' solution scores the same as
      // the initial score - if not, that indicates a bug
1172
      if (!compare_scores(get_score(),initial_score)) {
1173
	  cout << "*** WARNING: 'Clean' score does not match initial score" <<
1174 1175 1176
	      endl << "     This indicates a bug - contact the operators" <<
	      endl << "     (initial score: " << initial_score <<
	      ", current score: " << get_score() << ")" << endl;
1177 1178 1179 1180 1181
	  // One source of this can be pclasses that are still used - check for
	  // those
	  pclass_list::iterator pit = pclasses.begin();
	  for (;pit != pclasses.end();pit++) {
	      if ((*pit)->used_members != 0) {
1182
		  cout << (*pit)->name << " is " << (*pit)->used_members
1183 1184 1185
		      << "% used" << endl;
	      }
	  }
1186
      }
1187 1188 1189 1190 1191
      
      /* 
       * Now, go through the previous best solution, and add all of the node
       * mappings back in.
       */
1192 1193 1194 1195
      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;
1196
	if (best_solution.is_assigned(*vvertex_it)) {
1197
	  if (vnode->vclass != NULL) {
1198
	    vnode->type = best_solution.get_vtype_assignment(*vvertex_it);
1199
	  }
1200
	  assert(!add_node(*vvertex_it,best_solution.get_assignment(*vvertex_it),true,false,true));
1201 1202
	}
      }
1203 1204 1205 1206 1207 1208 1209
      
      /*
       * Add back in the old link resolutions
       */
      tie(vedge_it,end_vedge_it) = edges(VG);
      for (;vedge_it != end_vedge_it; ++vedge_it) {
	  tb_vlink *vlink = get(vedge_pmap,*vedge_it);
1210 1211
          tb_vnode *src_vnode = get(vvertex_pmap,vlink->src);
          tb_vnode *dst_vnode = get(vvertex_pmap,vlink->dst);
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
	  if (best_solution.link_is_assigned(*vedge_it)) {
	      // XXX: It's crappy that I have to do all this work here - something
	      // needs re-organzing
	      /*
	       * This line does the actual link mapping revert
		*/
	      vlink->link_info = best_solution.get_link_assignment(*vedge_it);
	      
	      if (!dst_vnode->assigned || !src_vnode->assigned) {
		  // This shouldn't happen, but don't try to score links which
		  // don't have both endpoints assigned.
		  continue;
	      }
1225 1226 1227 1228 1229
              if (dst_vnode->fixed && src_vnode->fixed) {
                  // If both endpoints were fixed, this link never got
                  // unmapped, so don't map it again
                  continue;
              }
1230 1231 1232 1233 1234 1235 1236
	      tb_pnode *src_pnode = get(pvertex_pmap,src_vnode->assignment);
	      tb_pnode *dst_pnode = get(pvertex_pmap,dst_vnode->assignment);
	      
	      /*
	       * Okay, now that we've jumped through enough hoops, we can actually
	       * do the scoring
	       */
1237
              mark_vlink_assigned(vlink);
1238 1239
	      score_link_info(*vedge_it, src_pnode, dst_pnode, src_vnode, dst_vnode);
	  } else {
1240 1241 1242 1243 1244 1245
              /*
               * If one endpoint or the other was unmapped, we just note that
               * the link wasn't mapped - however, if both endpoints were
               * mapped, then we have to make sure the score reflects that.
               */
	      if (!dst_vnode->assigned || !src_vnode->assigned) {
1246 1247 1248
                  if (!vlink->no_connection) {
                      mark_vlink_unassigned(vlink);
                  }
1249
              }
1250 1251 1252
	  }
      }
    } // End of reverting code
1253

1254 1255 1256
    /*
     * Whew, that's it!
     */
1257 1258 1259 1260 1261
    tsteps++;

    if (finished) {
      goto DONE;
    }
1262 1263
  } /* End of outer annealing loop */
DONE:
1264
  cout << "Done" << endl;
1265 1266
} // End of anneal()