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

#include "anneal.h"

9 10 11 12 13 14 15
#include "virtual.h"
#include "maps.h"
#include "common.h"
#include "score.h"
#include "solution.h"
#include "vclass.h"

16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
/*
 * Internal variables
 */
// 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

// 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;
  
Robert Ricci's avatar
Robert Ricci committed
34
// Map of virtual node name to the physical node name it's fixed to.
35 36 37 38
// 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;

Robert Ricci's avatar
Robert Ricci committed
39 40 41 42 43
// 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;

44 45 46 47 48
// From assign.cc
#ifdef GNUPLOT_OUTPUT
extern FILE *scoresout, *tempout, *deltaout;
#endif

49 50 51 52 53 54 55 56 57 58 59 60
// Determines whether to accept a change of score difference 'change' at
// temperature 'temperature'.
inline int accept(double change, double temperature)
{
  double p;
  int r;

  if (change == 0) {
    p = 1000 * temperature / temp_prob;
  } else {
    p = expf(change/temperature) * 1000;
  }
61
  r = RANDOM() % 1000;
62 63 64 65 66 67
  if (r < p) {
    return 1;
  }
  return 0;
}

68 69 70 71
/*
 * This overly-verbose function returns true if it's okay to map vn to pn,
 * false otherwise
 */
72
inline bool pnode_is_match(tb_vnode *vn, tb_pnode *pn) {
73 74 75 76 77 78 79 80 81 82
  // Find the type record for this type
  tb_pnode::types_map::iterator mit = pn->types.find(vn->type);
  if (mit == pn->types.end()) {
    // The node doesn't even have this type, we can exit early
    return false;
  }

  bool matched = false;
  tb_pnode::type_record *tr = mit->second;
  if (tr->is_static) {
83 84
    if ((tr->current_load + vn->typecount) > tr->max_load) {
      // This would put us over its max load
85
      if (allow_overload && (tr->max_load > 1)) {
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
	// That's okay, we're allowing overload
	matched = true;
      } else {
	// Nope, it's full
	matched = false;
      }
    } else {
      // Plenty of room for us
      matched = true;
    }
  } else { // the type is not static
    if (pn->typed) {
      if (pn->current_type.compare(vn->type)) {
	// Failure - the pnode has a type, and it isn't ours
	matched = false;
      } else {
102
	if ((pn->current_type_record->current_load + vn->typecount) >
103
	    pn->current_type_record->max_load) {
104
	  // This would put us over its max load
105 106 107
	  //if (allow_overload && (tr->max_load > 1) &&
	  //    ((pn->current_type_record->current_load + vn->typecount) <
	  //    (pn->current_type_record->max_load + 2))) {
108
	  if (allow_overload && (tr->max_load > 1)) {
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
	    // That's okay, we're allowing overload
	    matched = true;
	  } else {
	    // Failure - the type is right, but the pnode is full
	    matched = false;
	  }
	} else {
	  // It's under its max load, we can fit in
	  matched = true;
	}
      }
    } else {
      // pnode doesn't have a type
      matched = true;
    }
  }

126 127
  // Commented out for now because it's too slow!
#if 0
128 129 130 131 132 133 134
  // Check for 'local' desires - the reason we take the time to do this here is
  // that they are actually, in many ways, like types with vn->typecount > 1.
  if (matched && !vn->desires.empty()) {
    tb_vnode::desires_map::iterator desire_it;
    for (desire_it = vn->desires.begin();
	desire_it != vn->desires.end();
	desire_it++) {
135
      if (desire_it->is_l_additive() {
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
      tb_pnode::features_map::iterator feature_it =
	pn->features.find(desire_it->first);
      if (feature_it == pn->features.end()) {
	matched = false;
	break;
      }
      // If we are allowing overloading, do so only to a limited degree
      if (allow_overload) {
	if ((feature_it->second < desire_it->second)
	    && (feature_it->second - desire_it->second)
	        < (desire_it->second * 2)) {
	  matched = false;
	  break;
	}
      } else {
	// No overloading, and this would put us over the limit
	if (feature_it->second < desire_it->second) {
	  matched = false;
	  break;
	}
      }
    }
  }
159
#endif
160

161 162 163
  return matched;
}

164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
/*
 * Finds a pnode which:
 * 1) One of the vnode's neighbors is mapped to
 * 2) Satisifies the usual pnode mapping constraints
 * 3) The vnode is not already mapped to
 */
tb_pnode *find_pnode_connected(vvertex vv, tb_vnode *vn) {

  //cerr << "find_pnode_connected(" << vn->name << ") called" << endl;

  // We make a list of all neighboring vnodes so that we can go through
  // them in random order
  vector<vedge> visit_order(out_degree(vv,VG));
  voedge_iterator vedge_it,end_vedge_it;
  tie(vedge_it,end_vedge_it) = out_edges(vv,VG);	    
  for (int i = 0; vedge_it != end_vedge_it; vedge_it++, i++) {
    visit_order[i] = *vedge_it;
  }
  for (int i = 0; i < visit_order.size(); i++) {
183 184
	int i1 = RANDOM() % visit_order.size();
	int i2 = RANDOM() % visit_order.size();
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
	vedge tmp = visit_order[i1];
	visit_order[i1] = visit_order[i2];
	visit_order[i2] = tmp;
  }
  for (int i = 0; i < visit_order.size(); i++) {
    vvertex neighbor_vv = target(visit_order[i],VG);
    tb_vnode *neighbor_vn = get(vvertex_pmap,neighbor_vv);
    //cerr << "    trying " << neighbor_vn->name << endl;
    // Skip any that aren't assigned
    if (!neighbor_vn->assigned) {
      //cerr << "        not assigned" << endl;
      continue;
    }

    // Skip any that are assigned to the same pnode we are
    if (neighbor_vn->assignment == vn->assignment) {
      //cerr << "        same assignment" << endl;
      continue;
    }

    // Check to make sure that our vn can map to the neibor's assigment
    tb_pnode *neighbor_pnode = get(pvertex_pmap,neighbor_vn->assignment);
    //cerr << "        neighbor on " << neighbor_pnode->name << endl;
    if (pnode_is_match(vn,neighbor_pnode)) {
      //cerr << "        good" << endl;
      //cerr << "    worked" << endl;
      return neighbor_pnode;
    }
    //cerr << "        doesn't match" << endl;
  }

  //cerr << "    failed" << endl;
  return NULL;
}

220 221 222 223 224 225 226 227 228 229
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;
  
230
  tb_pnode *newpnode = NULL;
231 232
  
  //cerr << "Node is " << vn->name << " First = " << first << endl;
233

234 235 236 237
  // Randomize the order in which we go through the list of acceptable pclasses
  // We do this by making a randomly-ordered list of indicies into the
  // acceptable_types vector
  vector<int> traversal_order(num_types);
238
  for (int i = 0; i < num_types; i++) {
239 240 241
	traversal_order[i] = i;
  }
  for (int i = 0; i < num_types; i++) {
242 243
	int i1 = RANDOM() % num_types;
	int i2 = RANDOM() % num_types;
244 245 246
	int tmp = traversal_order[i1];
	traversal_order[i1] = traversal_order[i2];
	traversal_order[i2] = tmp;
247
  }
248

249
  for (int i = 0; i < num_types; i++) {
250

251 252
    int index = traversal_order[i];
    tb_pclass *pclass = (*acceptable_types)[index];
253

254 255 256
    // Skip pclasses that have been disabled
    if (pclass->disabled) {
	  continue;
257
    }
258 259 260

#ifndef FIND_PNODE_SEARCH
    // If not searching for the pnode, just grab the front one
261
    newpnode = pclass->members[vn->type]->front();
262
#else
263 264 265 266 267
#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
268
    if (pclass->members.find(vn->type) == pclass->members.end()) {
269 270 271
	continue;
    }
#endif
272

273 274
    list<tb_pnode*>::iterator it = pclass->members[vn->type]->L.begin();
    while (it != pclass->members[vn->type]->L.end()) {
275 276
	if (pnode_is_match(vn,*it)) {
	    break; 
Robert Ricci's avatar
Robert Ricci committed
277
	} else {
278
	    it++;
279 280
	}
    }
281
    if (it == pclass->members[vn->type]->L.end()) {
282 283 284 285
	newpnode = NULL;
    } else {
	newpnode = *it;
    }
286
#endif // FIND_PNODE_SEARCH
287 288
#ifdef PCLASS_DEBUG
    cerr << "Found pclass: " <<
289
      pclass->name << " and node " <<
290 291 292 293 294 295 296
      (newpnode == NULL ? "NULL" : newpnode->name) << "\n";
#endif
    if (newpnode != NULL) {
      RDEBUG(cout << " to " << newpnode->name << endl;)
      return newpnode;
    }
  }
297 298 299

  // Nope, didn't find one
  return NULL;
300 301
}

302 303 304
// We put the temperature outside the function so that external stuff, like
// status_report in assign.cc, can see it.
double temp;
305 306

/* When this is finished the state will reflect the best solution found. */
Robert Ricci's avatar
Robert Ricci committed
307
void anneal(bool scoring_selftest, double scale_neighborhood,
308
	double *initial_temperature, double use_connected_pnode_find)
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
{
  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);
  int 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);
    
#ifdef STATS
  cout << "STATS_OPTIMAL = " << optimal << endl;
#endif

  int mintrans = (int)cycles;
  int trans;
  int naccepts = 20*(nnodes + PHYSICAL(npnodes));
  pvertex oldpos;
  bool oldassigned;
  int bestviolated;
  int num_fixed=0;
  double meltedtemp;
341
  temp = init_temp;
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
  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
  cout << "Initialized to cycles="<<cycles<<" optimal="<<optimal<<" mintrans="
       << mintrans<<" naccepts="<<naccepts<< endl;
#endif

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

  /* Set up fixed nodes */
  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()) {
361
      cout << "*** Fixed node: " << (*fixed_it).first <<
362
	" does not exist." << endl;
363
      exit(EXIT_UNRETRYABLE);
364 365 366
    }
    vvertex vv = vname2vertex[(*fixed_it).first];
    if (pname2vertex.find((*fixed_it).second) == pname2vertex.end()) {
367
      cout << "*** Fixed node: " << (*fixed_it).second <<
368
	" not available." << endl;
369
      exit(EXIT_UNRETRYABLE);
370 371 372 373 374
    }
    pvertex pv = pname2vertex[(*fixed_it).second];
    tb_vnode *vn = get(vvertex_pmap,vv);
    tb_pnode *pn = get(pvertex_pmap,pv);
    if (vn->vclass != NULL) {
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
      // 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
          if (vn->vclass->has_type((*i)->ptype->name())) {
            vn->type = (*i)->ptype->name();
            break;
          }
        }
      }
      if (vn->type.empty()) {
394
        cout << "*** Unable to find a type for fixed, vtyped, node " << vn->name
395 396 397 398 399 400
          << endl;
        exit(EXIT_FATAL);
      } else {
        cout << "Setting type of vclass node " << vn->name << " to "
          << vn->type << "\n";
      }
401
    }
402
    if (add_node(vv,pv,false,true) == 1) {
403
      cout << "*** Fixed node: Could not map " << vn->name <<
404
	" to " << pn->name << endl;
405
      exit(EXIT_UNRETRYABLE);
406 407
    }
    vn->fixed = true;
408 409 410 411 412 413
    /*
    if (vn->vclass != NULL) {
      vn->type = vn->vclass->choose_type();
      cout << "Picked type " << vn->type << " for " << vn->name << endl;
    }
    */
414 415 416
    num_fixed++;
  }

417 418 419 420
  // Subtract the number of fixed nodes from nnodes, since they don't really
  // count
  if (num_fixed) {
      cout << "Adjusting dificulty estimate for fixed nodes, " <<
421
	  (nnodes - num_fixed) << " remain.\n";
422 423
  }

424 425 426 427
  /* 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();

Robert Ricci's avatar
Robert Ricci committed
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
  /*
   * 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;
    }
455
    if (add_node(vv,pv,false,false) == 1) {
Robert Ricci's avatar
Robert Ricci committed
456 457 458 459 460 461
      cout << "Warning: Hinted node: Could not map " << vn->name <<
	" to " << pn->name << endl;
      continue;
    }
  }

462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
  bestscore = get_score();
  bestviolated = violated;

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

  absbest = bestscore;
  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) {
      absassignment[*vit] = vn->assignment;
      abstypes[*vit] = vn->type;
    } else {
482
      unassigned_nodes.push(vvertex_int_pair(*vit,RANDOM()));
483 484 485 486
    }
  }

  int neighborsize;
487
  neighborsize = (nnodes - num_fixed) * npclasses;
488 489 490
  if (neighborsize < min_neighborhood_size) {
    neighborsize = min_neighborhood_size;
  }
491 492 493 494 495

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

496 497 498 499
#ifdef CHILL
  double scores[neighborsize];
#endif

500
  if (num_fixed >= nnodes) {
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
    cout << "All nodes are fixed.  No annealing." << endl;
    goto DONE;
  }
  
  // Annealing loop!
  vvertex vv;
  tb_vnode *vn;

  // Crap added by ricci
  bool melting;
  int nincreases, ndecreases;
  double avgincrease;
  double avgscore;
  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
Robert Ricci's avatar
Robert Ricci committed
550 551 552 553 554 555 556
  if (initial_temperature == NULL) {
      melting = true;
  } else {
      melting = false;
      temp = *initial_temperature;
      cout << "Starting with initial temperature " << temp << endl;
  }
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
#ifdef TIME_TARGET
  meltstart = used_time();
#endif
#else
  melting = false;
#endif

  melt_trans = neighborsize;
#ifdef EPSILON_TERMINATE
  while(1) {
#else
  while (temp >= temp_stop) {
#endif
#ifdef VERBOSE
    cout << "Temperature:  " << temp << " AbsBest: " << absbest <<
      " (" << absbestviolated << ")" << endl;
#endif
    trans = 0;
    accepts = 0;
    nincreases = ndecreases = 0;
    avgincrease = 0.0;
    avgscore = bestscore;
#ifdef CHILL
    scores[0] = bestscore;
#endif

583 584
    // Adjust the number of transitions we're going to do based on the number
    // of pclasses that are actually 'in play'
585 586
    int transitions = (int)(neighborsize *
      (count_enabled_pclasses() *1.0 / pclasses.size()));
587 588
    assert(transitions <= neighborsize);

589 590 591 592 593 594
    if (melting) {
      cout << "Doing melting run" << endl;
    }

    while ((melting && (trans < melt_trans))
#ifdef NEIGHBOR_LENGTH
595
	    || (trans < transitions)) {
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
#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++;

      bool freednode = false;
      if (! unassigned_nodes.empty()) {
	vv = unassigned_nodes.top().first;
	assert(!get(vvertex_pmap,vv)->assigned);
	unassigned_nodes.pop();
      } else {
616
	int start = RANDOM()%nnodes;
617 618 619 620 621 622 623 624 625 626 627
	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 {
628
	    cout << "**** Error, unable to find any non-fixed nodes" << endl;
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
	    goto DONE;
	}
      }
      
      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;)
      }
#endif
      
      if (vn->vclass != NULL) {
	vn->type = vn->vclass->choose_type();
#ifdef SCORE_DEBUG
	cerr << "vclass " << vn->vclass->name  << ": choose type for " <<
	    vn->name << " = " << vn->type << " dominant = " <<
	    vn->vclass->dominant << endl;
#endif
      }
653 654 655 656

      // Actually find a pnode
      tb_pnode *newpnode = NULL;
      if ((use_connected_pnode_find != 0)
657
	  && ((RANDOM() % 1000) < (use_connected_pnode_find * 1000))) {
658 659 660 661 662
	newpnode = find_pnode_connected(vv,vn);
      }
      if (newpnode == NULL) {
	newpnode = find_pnode(vn);
      }
663
#ifndef FREE_IMMEDIATELY
664 665
      if (oldassigned) {
	RDEBUG(cout << "removing: !lan, oldassigned" << endl;)
666
	  remove_node(vv);
667
      }
668
#endif
669 670
      if (newpnode == NULL) {
	// We're not going to be re-assigning this one
671
#ifndef SMART_UNMAP
672
	unassigned_nodes.push(vvertex_int_pair(vv,RANDOM()));
673
#endif
674
	// need to free up nodes
675
#ifdef SMART_UNMAP
676 677 678 679 680 681 682 683 684 685 686
	// XXX: Should probably randomize this
	// XXX: Add support for not using PER_VNODE_TT
	// XXX: Not very robust

	freednode = true;

	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;
687
	int offi = RANDOM();
688 689 690 691 692 693 694 695 696
	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;
697
	  }
698 699 700
	  foundnode = true;
	  break;
	}
701

702 703
	if (foundnode) {
	  assert((*acceptable_types)[index]->used_members[vn->type]->size());
704 705
	  tb_pclass::tb_pnodeset::iterator it =
	    (*acceptable_types)[index]->used_members[vn->type]->begin();
706
	  int j = RANDOM() %
707
	    (*acceptable_types)[index]->used_members[vn->type]->size();
708 709 710 711 712
	  while (j > 0) {
	    it++;
	    j--;
	  }
	  tb_vnode_set::iterator it2 = (*it)->assigned_nodes.begin();
713
	  int k = RANDOM() % (*it)->assigned_nodes.size();
714 715 716
	  while (k > 0) {
	    it2++;
	    k--;
717
	  }
718 719 720 721 722 723
	  tb_vnode *kickout = *it2;
	  assert(kickout->assigned);
	  vvertex toremove = vname2vertex[kickout->name];
	  newpnode = *it;
	  remove_node(toremove);
	  unassigned_nodes.push(vvertex_int_pair(toremove,
724
		RANDOM()));
725 726 727
	} else {
	  cerr << "Failed to find a replacement!" << endl;
	}
728 729

#else
730
	int start = RANDOM()%nnodes;
731
	int toremove = start;
732 733 734
#ifdef SMART_UNMAP

#ifdef PER_VNODE_TT
735
	  tt_entry tt = vnode_type_table[vn->name];
736 737 738 739 740 741
#else
	  tt_entry tt = type_table[vn->type];
#endif
	  pclass_vector *acceptable_types = tt.second;

	  while (1) {
742 743 744 745 746 747 748 749 750 751 752
	    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) {
753
		  break;
754 755 756 757
		}
	      }
	      if (j == acceptable_types->size()) {
		keepgoing = true;
758
	      }
759 760 761 762 763 764
	    }

	    if (!keepgoing) {
	      break;
	    }

765
#else
766 767
	    while (get(vvertex_pmap,virtual_nodes[toremove])->fixed ||
		(! get(vvertex_pmap,virtual_nodes[toremove])->assigned)) {
768 769 770
#endif
	      toremove = (toremove +1) % nnodes;
	      if (toremove == start) {
771 772
		toremove = -1;
		break;
773
	      }
774 775
	    }
	    if (toremove >= 0) {
776
	      RDEBUG(cout << "removing: freeing up nodes" << endl;)
777
		remove_node(virtual_nodes[toremove]);
778
	      unassigned_nodes.push(vvertex_int_pair(virtual_nodes[toremove],
779
		    RANDOM()));
780 781
	    }
	    continue;
782 783
#endif /* SMART_UNMAP */
#ifndef SMART_UNMAP
784
	  } else {
785
#else
786
	  }
787 788
#endif
	  if (newpnode != NULL) {
789 790 791 792 793 794
	    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 would have
	      // gotten otherwise
	      double oldscore = get_score();
795
	      int oldviolated = violated;
Robert Ricci's avatar
Robert Ricci committed
796
	      double tempscore;
797
	      int tempviolated;
798
	      if (!add_node(vv,newpos,false,false)) {
Robert Ricci's avatar
Robert Ricci committed
799
		tempscore = get_score();
800
		tempviolated = violated;
801
		remove_node(vv);
802
	      }
803
	      if ((oldscore != get_score()) || (oldviolated != violated)) {
Robert Ricci's avatar
Robert Ricci committed
804 805 806
		cerr << "Scoring problem adding a mapping - oldscore was " <<
		  oldscore <<  " newscore is " << newscore << " tempscore was "
		  << tempscore << endl;
807 808
		cerr << "oldviolated was " << oldviolated << " newviolated is "
		  << violated << " tempviolated was " << tempviolated << endl;
Robert Ricci's avatar
Robert Ricci committed
809 810
		cerr << "I was tring to map " << vn->name << " to " <<
		  newpnode->name << endl;
811 812
		print_solution();
		cerr << vinfo;
Robert Ricci's avatar
Robert Ricci committed
813 814
		abort();
	      }
815
	    }
816
	    if (add_node(vv,newpos,false,false) != 0) {
817
	      unassigned_nodes.push(vvertex_int_pair(vv,RANDOM()));
818 819
	      continue;
	    }
820 821
	  } else {
#ifdef SMART_UNMAP
822
	    unassigned_nodes.push(vvertex_int_pair(vv,RANDOM()));
823
#endif
824 825 826
	    if (freednode) {
	      continue;
	    }
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
	  }
#ifndef SMART_UNMAP
	}
#endif

      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) {
	nincreases++;
	avgincrease = avgincrease * (nincreases -1) / nincreases +
	  (-scorediff)  / nincreases;
      } else {
	ndecreases++;
      }
      
      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;)
855
      } else {
856 857 858 859 860 861 862 863 864 865 866 867
#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
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
#ifdef SPECIAL_VIOLATION_TREATMENT
	  /*
	   * 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.
	   */
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
          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;)
	  }
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
#else // no SPECIAL_VIOLATION_TREATMENT
	  /*
	   * 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;
	  }

#endif // SPECIAL_VIOLATION_TREATMENT

      }
927 928 929 930 931
#endif

      if (accepttrans) {
	bestscore = newscore;
	bestviolated = violated;
932

933 934 935 936 937
#ifdef GNUPLOT_OUTPUT
	fprintf(tempout,"%f\n",temp);
	fprintf(scoresout,"%f\n",newscore);
	fprintf(deltaout,"%f\n",-scorediff);
#endif
938

939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
	avgscore += newscore;

	accepts++;

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

#ifdef NO_VIOLATIONS
	if (newscore < absbest) {
#else
	if ((violated < absbestviolated) ||
	    ((violated == absbestviolated) &&
	     (newscore < absbest))) {
#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;
	  }
	  absbest = newscore;
	  absbestviolated = violated;
	  iters_to_best = iters;
#ifdef SCORE_DEBUG
	  cerr << "New best recorded" << endl;
#endif
	}
	if (newscore < optimal) {
	  cout << "OPTIMAL ( " << optimal << ")" << endl;
	  goto DONE;
	}
	// Accept change
      } else {
	// Reject change
	RDEBUG(cout << "removing: rejected change" << endl;)
	remove_node(vv);
	if (oldassigned) {
982
	  add_node(vv,oldpos,false,false);
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 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
	}
      }

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

    }

#ifdef RANDOM_ASSIGNMENT
      if (violated == 0) {
	  finished = true;
      }
#endif

#ifdef REALLY_RANDOM_ASSIGNMENT
      if (unassigned_nodes.size() == 0) {
	  finished = true;
      }
#endif

NOTQUITEDONE:
      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
    }


#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
    
1082 1083 1084
    RDEBUG(
    printf("temp_end: temp: %f ratio: %f stddev: %f\n",temp,temp * avgscore / initialavg,stddev);
    );
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114

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

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

#ifdef LOCAL_DERIVATIVE
    deltaavg = lastsmoothed - smoothedavg;
    deltatemp = lasttemp - temp;
#else
    deltaavg = initialavg - smoothedavg;
    deltatemp = meltedtemp - temp;
#endif

    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));
1115
    );
1116 1117
    if ((tsteps >= mintsteps) &&
#ifdef ALLOW_NEGATIVE_DELTA
1118 1119 1120
	((temp < 0) || isnan(temp) ||
//	 || (fabs((temp / initialavg) * (deltaavg/ deltatemp)) < epsilon))) {
	 ((temp / initialavg) * (deltaavg/ deltatemp)) < epsilon)) {
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 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
#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

    bool revert = false;
    if (forcerevert) {
	cout << "Reverting: forced" << endl;
	revert = true;
    }

#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

    if (REVERT_LAST && (temp < temp_stop)) {
	cout << "Reverting: REVERT_LAST" << endl;
	revert = true;
    }

    // Only revert if the best configuration has better violations
    vvertex_list lan_nodes;
    vvertex_iterator vvertex_it,end_vvertex_it;
1165
    if (revert) {
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
      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;)
	}
      }
1179 1180 1181

      // Check to make sure that our 'clean' solution scores the same as
      // the initial score - if not, that indicates a bug
1182
      if (!compare_scores(get_score(),initial_score)) {
1183
	  cout << "*** WARNING: 'Clean' score does not match initial score" <<
1184 1185 1186
	      endl << "     This indicates a bug - contact the operators" <<
	      endl << "     (initial score: " << initial_score <<
	      ", current score: " << get_score() << ")" << endl;
1187 1188 1189 1190 1191
	  // 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) {
1192
		  cout << (*pit)->name << " is " << (*pit)->used_members
1193 1194 1195
		      << "% used" << endl;
	      }
	  }
1196
      }
1197 1198 1199 1200 1201
      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]) {
1202 1203
	  if (vnode->vclass != NULL) {
	    vnode->type = abstypes[*vvertex_it];
1204
	  }
1205
	  assert(!add_node(*vvertex_it,absassignment[*vvertex_it],true,false));
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
	}
      }
    }

    tsteps++;

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