anneal.cc 39.6 KB
Newer Older
1 2
/*
 * EMULAB-COPYRIGHT
3
 * Copyright (c) 2003-2009 University of Utah and the Flux Group.
4 5 6
 * All rights reserved.
 */

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

9 10
#include "anneal.h"

11 12 13 14 15 16
#include "virtual.h"
#include "maps.h"
#include "common.h"
#include "score.h"
#include "solution.h"
#include "vclass.h"
17
#include "neighborhood.h"
18

19 20 21 22
/*
 * Internal variables
 */
// These variables store the best solution.
23 24 25 26
//node_map absassignment;		// assignment field of vnode
//assigned_map absassigned;	// assigned field of vnode
//type_map abstypes;		// type field of vnode
solution best_solution;
27 28 29 30 31 32 33 34 35 36 37

// 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;
  
38
// Map of virtual node name to the physical node name it's fixed to.
39 40 41 42
// 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;

43 44 45 46 47
// 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;

48 49 50 51 52
// From assign.cc
#ifdef GNUPLOT_OUTPUT
extern FILE *scoresout, *tempout, *deltaout;
#endif

53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
/*
 * 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;


82 83
// Determines whether to accept a change of score difference 'change' at
// temperature 'temperature'.
84
inline bool accept(double change, double temperature) {
85 86 87 88 89 90 91 92
  double p;
  int r;

  if (change == 0) {
    p = 1000 * temperature / temp_prob;
  } else {
    p = expf(change/temperature) * 1000;
  }
93
  r = RANDOM() % 1000;
94 95 96 97 98 99
  if (r < p) {
    return 1;
  }
  return 0;
}

100 101

#ifdef SMART_UNMAP
102
/*
103 104
 * XXX - I pulled this code out of the anneal loop, and it needs to be fixed
 * up (and get some arguments and a return type) before it will compile
105
 */
106 107 108 109
void smart_unmap() {
	// XXX: Should probably randomize this
	// XXX: Add support for not using PER_VNODE_TT
	// XXX: Not very robust
110

111
	freednode = true;
112

113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
	tt_entry tt = vnode_type_table[vn->name];
	int size = tt.first;
	pclass_vector *acceptable_types = tt.second;
	// Find a node to kick out
	bool foundnode = false;
	int offi = RANDOM();
	int index;
	for (int i = 0; i < size; i++) {
	  index = (i + offi) % size;
	  if ((*acceptable_types)[index]->used_members.find(vn->type) ==
	      (*acceptable_types)[index]->used_members.end()) {
	    continue;
	  }
	  if ((*acceptable_types)[index]->used_members[vn->type]->size() == 0) {
	    continue;
	  }
	  foundnode = true;
130 131 132
	  break;
	}

133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
	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 = RANDOM() %
	    (*acceptable_types)[index]->used_members[vn->type]->size();
	  while (j > 0) {
	    it++;
	    j--;
	  }
	  tb_vnode_set::iterator it2 = (*it)->assigned_nodes.begin();
	  int k = RANDOM() % (*it)->assigned_nodes.size();
	  while (k > 0) {
	    it2++;
	    k--;
	  }
	  tb_vnode *kickout = *it2;
	  assert(kickout->assigned);
	  vvertex toremove = vname2vertex[kickout->name];
	  newpnode = *it;
	  remove_node(toremove);
	  unassigned_nodes.push(vvertex_int_pair(toremove,
		RANDOM()));
	} else {
	  cerr << "Failed to find a replacement!" << endl;
	}
#endif /* SMART_UNMAP */
160

161
#ifdef SMART_UNMAP
162
/*
163 164
 * Part II of the smart_unmap code - again, needs to be fixed before it
 * will compile.
165
 */
166
void smart_unmap_part2() {
167
#ifdef PER_VNODE_TT
168
	  tt_entry tt = vnode_type_table[vn->name];
169
#else
170
	  tt_entry tt = type_table[vn->type];
171
#endif
172
	  pclass_vector *acceptable_types = tt.second;
173

174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
	  while (1) {
	    bool keepgoing = false;
	    if (get(vvertex_pmap,virtual_nodes[toremove])->fixed) {
	      keepgoing = true;
	    } else if (! get(vvertex_pmap,virtual_nodes[toremove])->assigned) {
	      keepgoing = true;
	    } 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;
	      }
	    }
193

194 195 196
	    if (!keepgoing) {
	      break;
	    }
197
	}
198 199
#endif	
	
200 201 202
// We put the temperature outside the function so that external stuff, like
// status_report in assign.cc, can see it.
double temp;
203 204

/* When this is finished the state will reflect the best solution found. */
205 206 207
void anneal(bool scoring_selftest, bool check_fixed_nodes,
        double scale_neighborhood, double *initial_temperature,
        double use_connected_pnode_find)
208 209 210 211 212 213 214 215 216 217 218 219 220 221
{
  cout << "Annealing." << endl;

  double newscore = 0;
  double bestscore = 0;
 
  // The number of iterations that took place.
  iters = 0;
  iters_to_best = 0;
  int accepts = 0;
  
  double scorediff;

  int nnodes = num_vertices(VG);
222
  //int npnodes = num_vertices(PG);
223 224 225 226 227 228 229 230 231 232 233 234
  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 bestviolated;
  int num_fixed=0;
  double meltedtemp;
235
  temp = init_temp;
236 237 238 239 240 241 242 243
  double deltatemp, deltaavg;

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

#ifdef VERBOSE
244
  cout << "Initialized to cycles="<<cycles<<" mintrans="
245 246 247 248 249 250 251
       << mintrans<<" naccepts="<<naccepts<< endl;
#endif

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

  /* Set up fixed nodes */
252 253 254 255 256
  /* 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;
257 258 259
  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()) {
260
      cout << "*** Fixed virtual node: " << (*fixed_it).first <<
261
	" does not exist." << endl;
262 263
      fix_failed++;
      continue;
264 265 266
    }
    vvertex vv = vname2vertex[(*fixed_it).first];
    if (pname2vertex.find((*fixed_it).second) == pname2vertex.end()) {
267
      cout << "*** Fixed physical node: " << (*fixed_it).second <<
268
	" not available." << endl;
269 270
      fix_failed++;
      continue;
271 272 273 274 275
    }
    pvertex pv = pname2vertex[(*fixed_it).second];
    tb_vnode *vn = get(vvertex_pmap,vv);
    tb_pnode *pn = get(pvertex_pmap,pv);
    if (vn->vclass != NULL) {
276 277 278 279 280 281 282 283 284 285 286 287
      // 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
288 289
          if (vn->vclass->has_type((*i)->get_ptype()->name())) {
            vn->type = (*i)->get_ptype()->name();
290 291 292 293 294
            break;
          }
        }
      }
      if (vn->type.empty()) {
295 296
        // This is an internal error, so it's okay to handle it in a different
        // way from the others
297
        cout << "*** Unable to find a type for fixed, vtyped, node " << vn->name
298 299 300 301 302 303
          << endl;
        exit(EXIT_FATAL);
      } else {
        cout << "Setting type of vclass node " << vn->name << " to "
          << vn->type << "\n";
      }
304
    }
305 306 307 308 309 310 311 312 313 314 315

    /*
     * 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) {
316
      cout << "*** Fixed node: Could not map " << vn->name <<
317
	" to " << pn->name << endl;
318 319
      fix_failed++;
      continue;
320 321
    }
    vn->fixed = true;
322 323 324 325 326 327
    /*
    if (vn->vclass != NULL) {
      vn->type = vn->vclass->choose_type();
      cout << "Picked type " << vn->type << " for " << vn->name << endl;
    }
    */
328 329 330
    num_fixed++;
  }

331 332 333 334 335
  if (fix_failed){
    cout << "*** Some fixed nodes failed to map" << endl;
    exit(EXIT_UNRETRYABLE);
  }

336 337 338 339
  // Subtract the number of fixed nodes from nnodes, since they don't really
  // count
  if (num_fixed) {
      cout << "Adjusting dificulty estimate for fixed nodes, " <<
340
	  (nnodes - num_fixed) << " remain.\n";
341 342
  }

343 344 345 346
  /* 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();

347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
  /*
   * 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;
    }
374
    if (add_node(vv,pv,false,false,false) == 1) {
375 376 377 378 379
      cout << "Warning: Hinted node: Could not map " << vn->name <<
	" to " << pn->name << endl;
      continue;
    }
  }
380 381 382 383
       
  /*
   * Find out the starting temperature
   */
384 385 386 387 388 389 390 391 392 393 394
  bestscore = get_score();
  bestviolated = violated;

#ifdef VERBOSE
  cout << "Problem started with score "<<bestscore<<" and "<< violated
       << " violations." << endl;
#endif

  absbest = bestscore;
  absbestviolated = bestviolated;

395 396 397
  /*
   * Make a list of all nodes that are still unassigned
   */
398 399 400 401 402
  vvertex_iterator vit,veit;
  tie(vit,veit) = vertices(VG);
  for (;vit!=veit;++vit) {
    tb_vnode *vn = get(vvertex_pmap,*vit);
    if (vn->assigned) {
403 404 405 406 407
	// XXX
//      absassignment[*vit] = vn->assignment;
//      abstypes[*vit] = vn->type;
	best_solution.set_assignment(*vit,vn->assignment);
	best_solution.set_vtype_assignment(*vit,vn->type);
408
    } else {
409 410
	best_solution.clear_assignment(*vit);
	unassigned_nodes.push(vvertex_int_pair(*vit,RANDOM()));
411 412
    }
  }
413 414 415 416 417 418 419 420 421 422 423 424
  
  /*
   * 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);
      }
  }
425

426 427 428 429 430 431
  /*
   * 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.
   */
432
  int neighborsize;
433
  neighborsize = (nnodes - num_fixed) * npclasses;
434 435 436
  if (neighborsize < min_neighborhood_size) {
    neighborsize = min_neighborhood_size;
  }
437 438 439 440 441

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

442 443 444 445
#ifdef CHILL
  double scores[neighborsize];
#endif

446
  if (num_fixed >= nnodes) {
447 448 449 450 451 452 453 454
    cout << "All nodes are fixed.  No annealing." << endl;
    goto DONE;
  }
  
  vvertex vv;
  tb_vnode *vn;

  // Crap added by ricci
455
#ifdef MELT
456
  bool melting;
457
#endif
458 459 460 461 462
  int nincreases, ndecreases;
  double avgincrease;
  double avgscore;
  double initialavg;
  double stddev;
463 464 465 466 467
  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....
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
  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;

498 499 500
  /*
   * Initial temperature calcuation/melting
   */
501
#ifdef MELT
502 503 504 505 506 507 508
  if (initial_temperature == NULL) {
      melting = true;
  } else {
      melting = false;
      temp = *initial_temperature;
      cout << "Starting with initial temperature " << temp << endl;
  }
509 510 511 512 513 514 515
#ifdef TIME_TARGET
  meltstart = used_time();
#endif
#else
  melting = false;
#endif

516
  /*
517 518
   * When melting, this is the number of different solutions we will try during
   * this temperature step
519
   */
520
  melt_trans = neighborsize;
521 522 523 524 525 526 527 528
  
  /*
   * 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.
   */
529 530 531 532 533
#ifdef EPSILON_TERMINATE
  while(1) {
#else
  while (temp >= temp_stop) {
#endif
534
      
535 536 537 538
#ifdef VERBOSE
    cout << "Temperature:  " << temp << " AbsBest: " << absbest <<
      " (" << absbestviolated << ")" << endl;
#endif
539 540 541 542
    
    /*
     * Initialize this temperature step
     */
543 544 545 546 547 548 549 550 551
    trans = 0;
    accepts = 0;
    nincreases = ndecreases = 0;
    avgincrease = 0.0;
    avgscore = bestscore;
#ifdef CHILL
    scores[0] = bestscore;
#endif

552 553
    // Adjust the number of transitions we're going to do based on the number
    // of pclasses that are actually 'in play'
554 555
    int transitions = (int)(neighborsize *
      (count_enabled_pclasses() *1.0 / pclasses.size()));
556 557
    assert(transitions <= neighborsize);

558 559 560 561
    if (melting) {
      cout << "Doing melting run" << endl;
    }

562 563 564 565 566 567
    /*
     * 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.
     */
568 569
    while ((melting && (trans < melt_trans))
#ifdef NEIGHBOR_LENGTH
570
	    || (trans < transitions)) {
571 572 573 574 575 576 577 578 579 580 581 582 583 584
#else
	    || (!melting && (trans < mintrans && accepts < naccepts))) {
#endif

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

585 586 587 588 589 590
      /*
       * 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
       */
591 592 593 594 595
      if (! unassigned_nodes.empty()) {
	vv = unassigned_nodes.top().first;
	assert(!get(vvertex_pmap,vv)->assigned);
	unassigned_nodes.pop();
      } else {
596
	int start = RANDOM()%nnodes;
597 598 599 600 601 602 603 604 605 606 607
	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 {
608
	    cout << "**** Error, unable to find any non-fixed nodes" << endl;
609 610
	    goto DONE;
	}
611
      }      
612 613
      vn = get(vvertex_pmap,vv);
      RDEBUG(cout << "Reassigning " << vn->name << endl;)
614 615 616 617
	  
      /*
       * Keep track of the old assignment for this node
       */
618 619 620
      oldassigned = vn->assigned;
      oldpos = vn->assignment;
      
621 622 623 624 625
      /*
       * 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
       */
626 627 628 629 630 631 632
#ifdef FREE_IMMEDIATELY
      if (oldassigned) {
	remove_node(vv);
	RDEBUG(cout << "Freeing up " << vn->name << endl;)
      }
#endif
      
633 634 635 636
      /*
       * We have to handle vnodes with vtypes (vclasses) specially - we have
       * to make the vtype pick a type to masquerade as for now.
       */
637 638 639
      if (vn->vclass != NULL) {
	vn->type = vn->vclass->choose_type();
#ifdef SCORE_DEBUG
640
	cerr << "vclass " << vn->vclass->get_name()  << ": choose type for " <<
641
	    vn->name << " = " << vn->type << " dominant = " <<
642
	    vn->vclass->get_dominant() << endl;
643 644
#endif
      }
645 646 647 648 649 650 651
      
      // Did we free a node?
      bool freednode = false;
      
      /* 
       * Find a pnode to map this vnode to
       */
652 653
      tb_pnode *newpnode = NULL;
      if ((use_connected_pnode_find != 0)
654
	  && ((RANDOM() % 1000) < (use_connected_pnode_find * 1000))) {
655 656
	newpnode = find_pnode_connected(vv,vn);
      }
657 658 659 660 661
      
      /* 
       * If not using the connected find, or it failed to find a node, then
       * fall back on the regular algorithm to find a pnode
       */
662 663 664
      if (newpnode == NULL) {
	newpnode = find_pnode(vn);
      }
665 666 667 668
      
      /*
       * If we didn't free the vnode up above, do it now
       */
669
#ifndef FREE_IMMEDIATELY
670 671
      if (oldassigned) {
	RDEBUG(cout << "removing: !lan, oldassigned" << endl;)
672
	remove_node(vv);
673
      }
674
#endif
675 676 677 678 679
      
      /*
       * 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
       */
680
      if (newpnode == NULL) {
681
#ifndef SMART_UNMAP
682
	// Push this node back onto the unassigned map
683 684
	unassigned_nodes.push(vvertex_int_pair(vv,RANDOM()));
	int start = RANDOM()%nnodes;
685
	int toremove = start;
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
	while (get(vvertex_pmap,virtual_nodes[toremove])->fixed ||
	       (! get(vvertex_pmap,virtual_nodes[toremove])->assigned)) {
	    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], RANDOM()));
      }	
      
      /*
       * 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
       */
      continue;	
#else /* SMART_UNMAP */
      // XXX: This code is broken for now, which is okay, because we weren't
      // using it
      smart_unmap();
      smart_unmap_part2();
711
#endif
712 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
      }
    
      /*
       * Okay, we've got pnode to map this vnode to - let's do it
       */
      if (newpnode != NULL) {	
        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 " <<
		oldscore <<  " newscore is " << newscore << " tempscore was "
		<< 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) {
	  unassigned_nodes.push(vvertex_int_pair(vv,RANDOM()));
	  continue;
        }
      } else { // pnode != NULL
754
#ifdef SMART_UNMAP
755
        unassigned_nodes.push(vvertex_int_pair(vv,RANDOM()));
756
#endif
757 758 759 760
        if (freednode) {
	  continue;
        }	
      }
761

762 763 764
      /*
       * Okay, now that we've mapped some new node, let's check the scoring
       */
765 766 767 768 769 770 771 772
      newscore = get_score();
      assert(newscore >= 0);

      // Negative means bad
      scorediff = bestscore - newscore;
      // This looks funny, because < 0 means worse, which means an increase in
      // score
      if (scorediff < 0) {
773 774 775
        nincreases++;
        avgincrease = avgincrease * (nincreases -1) / nincreases +
  		    (-scorediff)  / nincreases;
776
      } else {
777 778 779 780 781 782 783
        ndecreases++;
      }	
   
      /*
       * Here are all the various conditions for deciding if we're going to accept
       * this transition
       */
784
      bool accepttrans = false;
785
      if (melting) {
786 787 788
        // When melting, we take everything!
	accepttrans = true;
	RDEBUG(cout << "accept: melting" << endl;)
789
      } else {
790
#ifdef NO_VIOLATIONS
791 792 793 794 795 796 797 798 799 800 801 802
        // Here, we don't consider violations at all, just whether the regular
        // simulated annealing accept conditions
	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;)
        }
803
#else
804
#ifdef SPECIAL_VIOLATION_TREATMENT
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
        /*
         * 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.
         */
        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 << vinfo;)
        } else if (accept(scorediff,temp)) {
	  accepttrans = true;
	  RDEBUG(cout << "accept: metropolis (" << newscore << ","
		 << bestscore << "," << expf(scorediff/(temp*sensitivity))
		 << ")" << endl;)
        }
838
#else // no SPECIAL_VIOLATION_TREATMENT
839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
        /*
         * 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.
         */
        double adjusted_new_score = newscore + violated * VIOLATION_SCORE;
        double adjusted_old_score = bestscore + bestviolated * VIOLATION_SCORE;

        if (adjusted_new_score < adjusted_old_score) {
          accepttrans = true;
        } else if (accept(adjusted_old_score - adjusted_new_score,temp)) {
	  accepttrans = true;
        }
858 859 860 861

#endif // SPECIAL_VIOLATION_TREATMENT

      }
862
#endif // NO_VIOLATIONS
863

864 865 866
      /* 
       * Okay, we've decided to accep this transition - do some bookkeeping
       */
867 868 869
      if (accepttrans) {
	bestscore = newscore;
	bestviolated = violated;
870

871 872 873 874
#ifdef GNUPLOT_OUTPUT
	fprintf(tempout,"%f\n",temp);
	fprintf(scoresout,"%f\n",newscore);
	fprintf(deltaout,"%f\n",-scorediff);
875
#endif // GNUPLOT_OUTPUT
876

877 878 879 880 881 882 883
	avgscore += newscore;
	accepts++;

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

886 887 888 889
        /*
         * 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
	 */
890 891
#ifdef NO_VIOLATIONS
	if (newscore < absbest) {
892
#else // NO_VIOLATIONS
893 894 895
	if ((violated < absbestviolated) ||
	    ((violated == absbestviolated) &&
	     (newscore < absbest))) {
896 897
#endif // NO_VIOLATIONS
	    
898 899
#ifdef SCORE_DEBUG
	  cerr << "New best solution." << endl;
900
#endif // SCORE_DEBUG
901 902
	  tie(vit,veit) = vertices(VG);
	  for (;vit!=veit;++vit) {
903 904 905 906
	      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);
907 908 909 910 911 912
	      } else {
		  best_solution.clear_assignment(*vit);
	      }
	    //absassignment[*vit] = get(vvertex_pmap,*vit)->assignment;
	    //absassigned[*vit] = get(vvertex_pmap,*vit)->assigned;
	    //abstypes[*vit] = get(vvertex_pmap,*vit)->type;
913
	  }
914
	  
915 916 917 918
	  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);
919
	      if (vlink->link_info.type_used != tb_link_info::LINK_UNMAPPED) {
920
		  best_solution.set_link_assignment(*edge_it,vlink->link_info);
921
	      } else {
922
		  best_solution.clear_link_assignment(*edge_it);
923 924 925
	      }
	  }	
	  
926 927 928 929 930 931 932 933
	  absbest = newscore;
	  absbestviolated = violated;
	  iters_to_best = iters;
#ifdef SCORE_DEBUG
	  cerr << "New best recorded" << endl;
#endif
	}
	// Accept change
934 935
      } else { // !acceptrans
	// Reject change, go back to the state we were in before
936 937 938
	RDEBUG(cout << "removing: rejected change" << endl;)
	remove_node(vv);
	if (oldassigned) {
939
	  add_node(vv,oldpos,false,false,false);
940 941 942
	}
      }

943 944 945 946 947
      /*
       * 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
       */
948 949 950 951 952 953 954
      if (melting) {
	temp = avgincrease /
	  log(nincreases/ (nincreases * X0 - ndecreases * (1 - X0)));
	if (!(temp > 0.0)) {
	    temp = 0.0;
	}
      }
955 956 957 958
      
      /*
       * With TIME_TERMINATE, we just give up after our time limit
       */
959 960 961 962 963 964 965 966 967
#ifdef TIME_TERMINATE
      if (timelimit && ((used_time() - timestart) > timelimit)) {
	printf("Reached end of run time, finishing\n");
	forcerevert = true;
	finished = true;
	goto NOTQUITEDONE;
      }
#endif

968 969
    } /* End of inner annealing loop */
     
970 971

NOTQUITEDONE:
972 973 974 975 976 977 978 979 980
    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);
981

982 983 984
    /*
     * If we were melting, then we we need to pick an initial temperature
     */
985 986 987 988 989 990 991 992 993 994 995
    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;
      }
996 997 998 999 1000
      /*
       * 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.
       */
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
#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 {
1014 1015 1016 1017 1018
      /*
       * 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
       */
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
#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
1030 1031 1032 1033
      /* 
       * This is assign's original cooling schedule - more predictable, but not
       * at all reactive to the problem at hand
       */
1034 1035 1036 1037 1038
      temp *= temp_rate;
#endif
    }


1039 1040 1041
    /*
     * Debugging
     */
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
#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
    
1064 1065 1066
    RDEBUG(
    printf("temp_end: temp: %f ratio: %f stddev: %f\n",temp,temp * avgscore / initialavg,stddev);
    );
1067

1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
    /*
     * 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.
     */
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
    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;
    }

1091 1092 1093 1094
    /*
     * Are we computing the derivative of the average temperatures over the
     * whole history, or just the most recent one?
     */
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
#ifdef LOCAL_DERIVATIVE
    deltaavg = lastsmoothed - smoothedavg;
    deltatemp = lasttemp - temp;
#else
    deltaavg = initialavg - smoothedavg;
    deltatemp = meltedtemp - temp;
#endif

    lastsmoothed = smoothedavg;
    lasttemp = temp;

1106 1107 1108 1109 1110
    /*
     * 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
     */
1111 1112 1113 1114 1115
#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));
1116
    );
1117
    if ((tsteps >= mintsteps) &&
1118 1119 1120 1121
    /*
     * ALLOW_NEGATIVE_DELTA controls whether we're willing to stop if the
     * derivative gets small and negative, not just small and positive.
     */
1122
#ifdef ALLOW_NEGATIVE_DELTA
1123 1124 1125
	((temp < 0) || isnan(temp) ||
//	 || (fabs((temp / initialavg) * (deltaavg/ deltatemp)) < epsilon))) {
	 ((temp / initialavg) * (deltaavg/ deltatemp)) < epsilon)) {
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
#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
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
    
    /*
     * 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
1164

1165 1166 1167 1168 1169 1170 1171
    /*
     * 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.
     */
1172
    bool revert = false;
1173 1174 1175 1176 1177 1178 1179
    
    /*
     * 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.
     */
1180
    if (forcerevert) {
1181 1182 1183 1184 1185 1186
      cout << "Reverting: forced" << endl;
      revert = true;
    }
    if (REVERT_LAST && (temp < temp_stop)) {
       cout << "Reverting: REVERT_LAST" << endl;
       revert = true;
1187 1188
    }

1189 1190 1191 1192 1193 1194 1195 1196 1197
    
    /*
     * 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.
     */
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
#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

1209 1210 1211 1212 1213 1214 1215 1216 1217
    /*
     * 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.)
     */
1218
    vvertex_iterator vvertex_it,end_vvertex_it;
1219
    vedge_iterator vedge_it,end_vedge_it;
1220
    if (revert) {
1221
      cout << "Reverting to best solution\n";
1222 1223 1224
      /*
       * We start out by unmapping every vnode that's currently allocated
       */
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
      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;)
	}
      }
1236 1237 1238

      // Check to make sure that our 'clean' solution scores the same as
      // the initial score - if not, that indicates a bug
1239
      if (!compare_scores(get_score(),initial_score)) {
1240
	  cout << "*** WARNING: 'Clean' score does not match initial score" <<
1241 1242 1243
	      endl << "     This indicates a bug - contact the operators" <<
	      endl << "     (initial score: " << initial_score <<
	      ", current score: " << get_score() << ")" << endl;
1244 1245 1246 1247 1248
	  // 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) {
1249
		  cout << (*pit)->name << " is " << (*pit)->used_members
1250 1251 1252
		      << "% used" << endl;
	      }
	  }
1253
      }
1254 1255 1256 1257 1258
      
      /* 
       * Now, go through the previous best solution, and add all of the node
       * mappings back in.
       */
1259 1260 1261 1262
      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;
1263
	if (best_solution.is_assigned(*vvertex_it)) {
1264
	  if (vnode->vclass != NULL) {
1265
	    vnode->type = best_solution.get_vtype_assignment(*vvertex_it);
1266
	  }
1267
	  assert(!add_node(*vvertex_it,best_solution.get_assignment(*vvertex_it),true,false,true));
1268 1269
	}
      }
1270 1271 1272 1273 1274 1275 1276
      
      /*
       * 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);
1277 1278
          tb_vnode *src_vnode = get(vvertex_pmap,vlink->src);
          tb_vnode *dst_vnode = get(vvertex_pmap,vlink->dst);
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
	  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;
	      }
1292 1293 1294 1295 1296
              if (dst_vnode->fixed && src_vnode->fixed) {
                  // If both endpoints were fixed, this link never got
                  // unmapped, so don't map it again
                  continue;
              }
1297 1298 1299 1300 1301 1302 1303 1304 1305
	      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
	       */
	      score_link_info(*vedge_it, src_pnode, dst_pnode, src_vnode, dst_vnode);
	  } else {
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
              /*
               * 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) {
                  vlink->link_info.type_used = tb_link_info::LINK_UNMAPPED;
              } else {
                  mark_vlink_unassigned(vlink);
              }
1316 1317 1318
	  }
      }
    } // End of reverting code
1319

1320 1321 1322
    /*
     * Whew, that's it!
     */
1323 1324 1325 1326 1327
    tsteps++;

    if (finished) {
      goto DONE;
    }
1328 1329
  } /* End of outer annealing loop */
DONE:
1330
  cout << "Done" << endl;
1331 1332
} // End of anneal()