GeomPerfectMatching::REAL GeomPerfectMatching::SolveComplete() { if (node_num != node_num_max) { printf("ComputeCost() cannot be called before all points have been added!\n"); exit(1); } PointId p, q; int e = 0, E = node_num*(node_num-1)/2; PerfectMatching* pm = new PerfectMatching(node_num, E); for (p=0; p<node_num; p++) { for (q=p+1; q<node_num; q++) { pm->AddEdge(p, q, Dist(p, q)); } } pm->options = options; pm->Solve(); for (p=0; p<node_num; p++) { for (q=p+1; q<node_num; q++) { if (pm->GetSolution(e++)) { matching[p] = q; matching[q] = p; } } } delete pm; return ComputeCost(matching); }
// The step size should be chosen carefully to guarantee convergence given a // reasonable number of computations. int GradientDescent::RunGradientDescent(const Data &data) { assert(num_iters_ >= 1); const int kNumTrainEx = data.num_train_ex(); assert(kNumTrainEx >= 1); const arma::mat kTrainingFeatures = data.training_features(); const arma::vec kTrainingLabels = data.training_labels(); double *j_theta_array = new double[num_iters_]; // Recall that we are trying to minimize the following cost function: // ((training features) * (current weights) - (training labels))^2 // Each iteration of this algorithm updates the weights as a scaled // version of the gradient of this cost function. // This gradient is computed with respect to the weights. // Thus, each iteration of gradient descent performs the following: // (update) = (step size) * ((training features) * (current weights) - (training labels)) * (training features) // (new weights) = (current weights) - (update) for(int theta_index=0; theta_index<num_iters_; theta_index++) { const arma::vec kDiffVec = kTrainingFeatures*theta_-kTrainingLabels; const arma::mat kDiffVecTimesTrainFeat = \ join_rows(kDiffVec % kTrainingFeatures.col(0),\ kDiffVec % kTrainingFeatures.col(1)); const arma::vec kThetaNew = theta_-alpha_*(1/(float)kNumTrainEx)*\ (sum(kDiffVecTimesTrainFeat)).t(); j_theta_array[theta_index] = ComputeCost(data); set_theta(kThetaNew); } delete [] j_theta_array; return 0; }
void UpdateRHSandBptr(Node *u) { double temp; int x = u->x; int y = u->y; u->bptr = 0; u->rhs = DOUBLE_INF; for (int i = 0; i < lattice.n; ++i) { int x1 = x + lattice.dx[i]; int y1 = y + lattice.dy[i]; if (!isInMap(x1, y1)) continue; Node *t = memory[x1][y1]; if (t == 0 || t->bptr == u) continue; temp = ComputeCost(u, x1, y1); if (temp < u->rhs) { u->rhs = temp; u->bptr = t; } } }
void Mapper2d:: InitAddmask() { m_addmask_x0 = 0; m_addmask_y0 = 0; m_addmask_x1 = 0; m_addmask_y1 = 0; const ssize_t offset(static_cast<ssize_t>(ceil(grown_safe_distance / gridframe.Delta()))); for (ssize_t ix(-offset); ix <= offset; ++ix) { const double x2(sqr(ix * gridframe.Delta())); for (ssize_t iy(-offset); iy <= offset; ++iy) { int const cost(ComputeCost(sqrt(sqr(iy * gridframe.Delta()) + x2))); if (cost > m_travmap->freespace) { m_addmask.insert(make_pair(index_t(ix, iy), cost)); // update the addmask's bounding box if (ix < m_addmask_x0) m_addmask_x0 = ix; if (ix > m_addmask_x1) m_addmask_x1 = ix; if (iy < m_addmask_y0) m_addmask_y0 = iy; if (iy > m_addmask_y1) m_addmask_y1 = iy; } } } }
CUnit *Find(Iterator begin, Iterator end) const { CUnit *enemy = NULL; int best_cost = INT_MAX; for (Iterator it = begin; it != end; ++it) { const int cost = ComputeCost(*it); if (cost < best_cost) { enemy = *it; best_cost = cost; } } return enemy; }
void CRUTask::ComputeGain() { TInt32 gain=0, maxGain=0; // First, update the (local) cost estimate ComputeCost(); // Next, update the (global) gain estimate DSListPosition pos = pSuccList_->GetHeadPosition(); // Compute the maximum gain between successor tasks while (NULL != pos) { CRUTask *pSuccTask = pSuccList_->GetNext(pos); gain = pSuccTask->GetGain(); maxGain = (gain > maxGain) ? gain : maxGain; } // Update the gain gain_ = GetCost() + maxGain; }
/* --------------------------------------------------------------------------- * Auto-place selected components. */ bool AutoPlaceSelected (void) { NetListTypePtr Nets; PointerListType Selected = { 0, 0, NULL }; PerturbationType pt; double C0, T0; bool changed = false; /* (initial netlist processing copied from AddAllRats) */ /* the netlist library has the text form * ProcNetlist fills in the Netlist * structure the way the final routing * is supposed to look */ Nets = ProcNetlist (&PCB->NetlistLib); if (!Nets) { Message (_("Can't add rat lines because no netlist is loaded.\n")); goto done; } Selected = collectSelectedElements (); if (Selected.PtrN == 0) { Message (_("No elements selected to autoplace.\n")); goto done; } /* simulated annealing */ { /* compute T0 by doing a random series of moves. */ const int TRIALS = 10; const double Tx = 3e5, P = 0.95; double Cs = 0.0; int i; C0 = ComputeCost (Nets, Tx, Tx); for (i = 0; i < TRIALS; i++) { pt = createPerturbation (&Selected, 1e6); doPerturb (&pt, false); Cs += fabs (ComputeCost (Nets, Tx, Tx) - C0); doPerturb (&pt, true); } T0 = -(Cs / TRIALS) / log (P); printf ("Initial T: %f\n", T0); } /* now anneal in earnest */ { double T = T0; long steps = 0; int good_moves = 0, moves = 0; const int good_move_cutoff = CostParameter.m * Selected.PtrN; const int move_cutoff = 2 * good_move_cutoff; printf ("Starting cost is %.0f\n", ComputeCost (Nets, T0, 5)); C0 = ComputeCost (Nets, T0, T); while (1) { double Cprime; pt = createPerturbation (&Selected, T); doPerturb (&pt, false); Cprime = ComputeCost (Nets, T0, T); if (Cprime < C0) { /* good move! */ C0 = Cprime; good_moves++; steps++; } else if ((random () / (double) RAND_MAX) < exp (MIN (MAX (-20, (C0 - Cprime) / T), 20))) { /* not good but keep it anyway */ C0 = Cprime; steps++; } else doPerturb (&pt, true); /* undo last change */ moves++; /* are we at the end of a stage? */ if (good_moves >= good_move_cutoff || moves >= move_cutoff) { printf ("END OF STAGE: COST %.0f\t" "GOOD_MOVES %d\tMOVES %d\t" "T: %.1f\n", C0, good_moves, moves, T); /* is this the end? */ if (T < 5 || good_moves < moves / CostParameter.good_ratio) break; /* nope, adjust T and continue */ moves = good_moves = 0; T *= CostParameter.gamma; /* cost is T dependent, so recompute */ C0 = ComputeCost (Nets, T0, T); } } changed = (steps > 0); } done: if (changed) { DeleteRats (false); AddAllRats (false, NULL); ClearAndRedrawOutput (); } FreePointerListMemory (&Selected); return (changed); }
GeomPerfectMatching::REAL GeomPerfectMatching::Solve() { double start_time = get_time(); double perfect_matching_time = 0; double negative_edges_time = 0; if (options.verbose) { printf("starting geometric matching with %d points\n", node_num); fflush(stdout); } PointId p, q; Edge* e; int _e; int iter; bool success = false; PerfectMatching* pm = NULL; GPMKDTree* kd_tree; double init_matching_time = get_time(); if (gpm_options.init_Delaunay) InitDelaunay(); if (gpm_options.init_KNN > 0) InitKNN(gpm_options.init_KNN); if (gpm_options.init_greedy) CompleteInitialMatching(); init_matching_time = get_time() - init_matching_time; graph_update_time = 0; int iter_max = gpm_options.iter_max; for (iter=0; iter_max<=0 || iter<iter_max; iter++) { if (pm) { double negative_edges_start_time = get_time(); int edge_num0 = edge_num; pm->StartUpdate(); for (p=0; p<node_num; p++) { PerfectMatching::REAL s = pm->GetTwiceSum(p); if ( ((REAL)1 / 2) == 0 && ((PerfectMatching::REAL)1 / 2) != 0 ) sums[p] = (REAL)ceil((double)s); else sums[p] = (REAL)s; } if (options.verbose) { printf("building kd_tree..."); fflush(stdout); } { kd_tree = new GPMKDTree(DIM+1, node_num, coords, this); } if (options.verbose) { printf(" done. Now adding negative edges:\n "); fflush(stdout); } for (p=0; p<node_num; p++) { if (options.verbose && (p%(node_num/72)==0)) { printf("+"); fflush(stdout); } for (e=nodes[p].first[0]; e; e=e->next[0]) nodes[e->head[0]].is_marked = 1; for (e=nodes[p].first[1]; e; e=e->next[1]) nodes[e->head[1]].is_marked = 1; kd_tree->AddNegativeEdges(p, pm); for (e=nodes[p].first[0]; e; e=e->next[0]) nodes[e->head[0]].is_marked = 0; for (e=nodes[p].first[1]; e; e=e->next[1]) nodes[e->head[1]].is_marked = 0; } delete kd_tree; //if (edge_num - edge_num0 > node_num / 32) if ( 0 ) // always reuse previous computation { delete pm; pm = NULL; } else { pm->FinishUpdate(); if (edge_num0 == edge_num) success = true; } if (options.verbose) { printf("\ndone (%d edges added)\n", edge_num-edge_num0); fflush(stdout); } negative_edges_time += get_time() - negative_edges_start_time; } if (!pm) { int E = 5*node_num; if (E < 5*edge_num/4) E = 5*edge_num/4; pm = new PerfectMatching(node_num, E); for (e=edges->ScanFirst(); e; e=edges->ScanNext()) { p = e->head[1]; q = e->head[0]; pm->AddEdge(p, q, Dist(p, q)); } } if (options.verbose) printf("iter %d: ", iter+1); pm->options = options; double perfect_matching_start = get_time(); pm->Solve(); perfect_matching_time += get_time() - perfect_matching_start; if (success) break; } for (_e=0, e=edges->ScanFirst(); e; _e++, e=edges->ScanNext()) { if (pm->GetSolution(_e)) { p = e->head[1]; q = e->head[0]; matching[p] = q; matching[q] = p; } } delete pm; REAL cost = ComputeCost(matching); if (options.verbose) { printf("geometric matching finished [%.3f secs]. cost=%.1f \n", get_time()-start_time, (double)cost); printf(" selecting initial edges: [%.3f secs], perfect matching: [%.3f secs]\n", init_matching_time, perfect_matching_time); printf(" pricing: [%.3f secs] including graph updates: [%.3f secs]\n", negative_edges_time, graph_update_time); fflush(stdout); } return cost; }
void ComputeOrImprovePath() { while (1) { if (timesExpanded > MAX_TIMES_EXPANDED) { planningFailed = true; return; } Node *s1 = open->peekTop(); if (s1 == 0) { planningFailed = true; return; } if (less_than(s1->key.k1, startNode->key.k1) || (equals(s1->key.k1, startNode->key.k1) && less_than(s1->key.k2, startNode->key.k2)) || (greater_than(startNode->rhs, startNode->g)) || (startNode->rhs == DOUBLE_INF && startNode->g == DOUBLE_INF)) ; else break; Node *s = open->removeTop(); if (greater_than(s->g, s->rhs)) { s->g = s->rhs; if (!s->inClosed) { s->inClosed = true; closed.push_back(s); } for (int i = 0; i < lattice.n; ++i) { int x = s->x + lattice.dx[i]; int y = s->y + lattice.dy[i]; if (!isInMap(x, y)) continue; Node *v = GetOrCreateNode(x, y); if (s->bptr == v) continue; double newRhs = ComputeCost(v, s->x, s->y); if (greater_than(v->rhs, newRhs)) { v->bptr = s; v->rhs = newRhs; UpdateState(v); } } ++timesExpanded; } else { s->g = DOUBLE_INF; UpdateState(s); for (int i = 0; i < lattice.n; ++i) { int x = s->x + lattice.dx[i]; int y = s->y + lattice.dy[i]; Node *v = GetOrCreateNode(x, y); if (v != goalNode && v->bptr == s) { UpdateRHSandBptr(v); UpdateState(v); } } ++timesExpanded; } } }