void processState(GDExplorerRef explorer, GDExplorationStackItem state) { GDTriangleListPush(explorer->triangleList, state.node); GDBool closed = GDTriangleListIsLastTriangleClosed(explorer->triangleList, explorer->graph); if ( closed ) { saveSolution(explorer); } GDBool expanded = NO; if ( canExistsBetterSolution(explorer) ) { if ( !closed ) { expanded = expandToNeighbours(explorer, state); } else { expanded = expandToAnyNode(explorer, state); } } if ( !expanded ) { GDTriangleListPop(explorer->triangleList); if ( explorer->explorationStack->count > 0 ) { GDExplorationStackItem nextTopContext = GDExplorationStackTop(explorer->explorationStack); GDTriangleListPopMultiple(explorer->triangleList, state.level - nextTopContext.level); } } }
void nasolver<nr_type_t>::steepestDescent (void) { nr_double_t alpha = 1.0, sl, n; // compute solution deviation vector tvector<nr_type_t> dx = *x - *xprev; tvector<nr_type_t> dz = *z - *zprev; n = norm (*zprev); do { // apply current damping factor and see what happens *x = *xprev + alpha * dx; // recalculate Jacobian and right hand side saveSolution (); calculate (); createZVector (); // check gradient criteria, ThinkME: Is this correct? dz = *z - *zprev; sl = real (sum (dz * -dz)); if (norm (*z) < n + alpha * sl) break; alpha *= 0.7; } while (alpha > 0.001); // apply final damping factor *x = *xprev + alpha * dx; }
void nasolver<nr_type_t>::lineSearch (void) { nr_double_t alpha = 0.5, n, nMin, aprev = 1.0, astep = 0.5, adiff; int dir = -1; // compute solution deviation vector tvector<nr_type_t> dx = *x - *xprev; nMin = std::numeric_limits<nr_double_t>::max(); do { // apply current damping factor and see what happens *x = *xprev + alpha * dx; // recalculate Jacobian and right hand side saveSolution (); calculate (); createZVector (); // calculate norm of right hand side vector n = norm (*z); // TODO: this is not perfect, but usable astep /= 2; adiff = fabs (alpha - aprev); if (adiff > 0.005) { aprev = alpha; if (n < nMin) { nMin = n; if (alpha == 1) dir = -dir; alpha += astep * dir; } else { dir = -dir; alpha += 1.5 * astep * dir; } } } while (adiff > 0.005); // apply final damping factor assert (alpha > 0 && alpha <= 1); *x = *xprev + alpha * dx; }
bool MIQPSolver::Solve() { if (status < Formulated) return false; if (ContigCount == 1) { U[0] = true; T[0] = false; X[0] = 0; } else { try { cplex.setParam(cplex.ParallelMode, (Options.UseOpportunisticSearch ? -1 : 1)); cplex.setParam(cplex.Threads, Options.Threads); if (Options.SuppressOutput) { cplex.setOut(environment.getNullStream()); cplex.setError(environment.getNullStream()); cplex.setWarning(environment.getNullStream()); } if (Options.TimeLimit > 0) cplex.setParam(cplex.TiLim, Options.TimeLimit); if (Options.UseObjectiveHeuristic) cplex.use(BestObjectiveReachedCallback(environment, cplex.getParam(cplex.EpGap), false, bestObjective)); //cplex.setParam(cplex.NumericalEmphasis, 1); if (!cplex.solve()) { cout << cplex.getStatus() << endl; // REMOVE ME return false; } saveSolution(); } catch (...) { status = Fail; return false; } } status = Success; return true; }
void nasolver<nr_type_t>::applyNodeset (bool nokeep) { if (x == NULL || nlist == NULL) return; // set each solution to zero if (nokeep) for (int i = 0; i < x->size (); i++) x->set (i, 0); // then apply the nodeset itself for (nodeset * n = subnet->getNodeset (); n; n = n->getNext ()) { struct nodelist_t * nl = nlist->getNode (n->getName ()); if (nl != NULL) { x->set (nl->n, n->getValue ()); } else { logprint (LOG_ERROR, "WARNING: %s: no such node `%s' found, cannot " "initialize node\n", getName (), n->getName ()); } } if (xprev != NULL) *xprev = *x; saveSolution (); }
int main (int argc, char const *argv[]) { if (argc < 2){ std::cout << "Usage:\n./pso <filename> <pop_size>" << std::endl; return 0; } int pop_size = 2000; const std::string filename = argv[1]; if (argc > 2) pop_size = int(atoi(argv[2])); int iterations = 500; if (argc > 3) iterations = int(atoi(argv[3])); double alpha = 0.75; if (argc > 4) alpha = double(atof(argv[4])); double beta = 0.1; if (argc > 5) alpha = double(atof(argv[5])); std::vector<double> optHistory(iterations); srand((unsigned)time(NULL)); std::vector<double>* objCost = readObjFunArray(filename.c_str()); const int n_vars = (int)(sqrt(objCost->size())); std::clock_t start; start = std::clock(); // create X std::vector<std::vector<int> > X(pop_size, std::vector<int>(n_vars)); // these vector will store V std::vector<std::vector<swap> > V(pop_size, std::vector<swap>(0)); // these vectors will store best individual positions std::vector<std::vector<int> > P(pop_size, std::vector<int>(n_vars)); // this vector will store global best position std::vector<int> Pg(n_vars); // this will store global best obj function value double fevalsPg = 0; // this vector will store current obj function values std::vector<double> fevals(pop_size); // this vector will store individual best obj function values std::vector<double> fevalsP(pop_size); int n_swaps = 0; int first = 0; int second = 0; // generate random V == swap sequences // also generate random initial positions for (int i=0; i<pop_size; i++){ for (int j=0; j<n_vars; j++){ X[i][j] = j; // fill X with nodes from 0 to n_vars-1 } std::random_shuffle (X[i].begin(), X[i].end()); // shuffle P[i] = X[i]; // deep copy //for (int j=0; j<n_vars; j++){std::cout << X[i][j] << " ";} //std::cout << std::endl; n_swaps = rand() % (n_vars) + 1; for (int j=0; j<n_swaps; j++){ first = rand() % n_vars; second = rand() % n_vars; V[i].push_back(swap (first, second)); //std::cout << V[i][j].first << " " << V[i][j].second << std::endl; } //std::cout << V[i].size() << std::endl; } //evaluate global best for (int i=0; i<pop_size; i++){ fevals[i] = evalSolution(applySwaps(X[i], V[i]), objCost, n_vars); fevalsP[i] = evalSolution(applySwaps(X[i], V[i]), objCost, n_vars); //std::cout << evals[i] << std::endl; } int globBestIndex = distance(fevals.begin(), min_element(fevals.begin(), fevals.end())); // std::cout << globBestIndex << std::endl; // save global best position and value Pg = applySwaps(X[globBestIndex], V[globBestIndex]); fevalsPg = fevals[globBestIndex]; //start pso bool terminate = false; /* std::vector<int> pp1 = {1,2,3,4,5,6,7,8}; std::vector<int> pp2 = {3,2,1,6,8,5,7,4}; std::vector<swap> pp3 = diff(pp1, pp2); printarr1(pp1); printarr1(pp2); printarr2(pp3);*/ for (int k=0; k<iterations && !terminate; k++){ for (int i=0; i<pop_size; i++){ //3.1 calculate difference between P_i and X_i // A = P_i - X_i, where A is a basic sequence. std::vector<swap> A = diff(P[i], applySwaps(X[i], V[i])); std::vector<swap> B = diff(Pg, applySwaps(X[i], V[i])); // now lets compute A*alpha and B*beta for (int j=A.size()-1; j>=0; j--){ double p1 = ((double)rand()/(double)RAND_MAX); if (p1>alpha){ A.erase(A.begin() + j); } } for (int j=B.size()-1; j>=0; j--){ double p2 = ((double)rand()/(double)RAND_MAX); if (p2>beta){ B.erase(B.begin() + j); } } std::vector<swap> newV = V[i]; // concatenate all the swaps in a single sequence newV.insert(newV.end(), A.begin(), A.end()); newV.insert(newV.end(), B.begin(), B.end()); // transform the swap sequence in Basic sequence form V[i] = toBasicSequence(newV, n_vars); // update position with formula X_i = X_i + V_i // X[i] = applySwaps(X[i], newV); // V[i].clear(); // update fevals fevals[i] = evalSolution(applySwaps(X[i], V[i]), objCost, n_vars); // possibly update P if (fevals[i] < fevalsP[i]){ fevalsP[i] = fevals[i]; P[i] = applySwaps(X[i], V[i]); } } // possibly update Pg globBestIndex = distance(fevals.begin(), min_element(fevals.begin(), fevals.end())); Pg = applySwaps(X[globBestIndex], V[globBestIndex]); if (fevals[globBestIndex] < fevalsPg){ fevalsPg = fevals[globBestIndex]; Pg = applySwaps(X[globBestIndex], V[globBestIndex]); } optHistory[k] = fevalsPg; } double elapsedtime = (std::clock() - start) / (double)(CLOCKS_PER_SEC); //std::cout << "Time: " << elapsedtime << std::endl; //std::cout << "best: " << fevalsPg << std::endl; saveSolution(elapsedtime, fevalsPg, optHistory); //printarr1(shiftToFirst(Pg)); }
int nasolver<nr_type_t>::solve_nonlinear_continuation_Source (void) { qucs::exception * e; int convergence, run = 0, MaxIterations, error = 0; nr_double_t sStep, sPrev; // fetch simulation properties MaxIterations = getPropertyInteger ("MaxIter") / 4 + 1; updateMatrix = 1; fixpoint = 0; // initialize the stepper sPrev = srcFactor = 0; sStep = 0.01; srcFactor += sStep; do { // run solving loop until convergence is reached run = 0; do { subnet->setSrcFactor (srcFactor); error = solve_once (); if (!error) { // convergence check convergence = (run > 0) ? checkConvergence () : 0; savePreviousIteration (); run++; } else break; } while (!convergence && run < MaxIterations); iterations += run; // not yet converged, so decreased the source-step if (run >= MaxIterations || error) { if (error) sStep *= 0.1; else sStep *= 0.5; restorePreviousIteration (); saveSolution (); // here the absolute minimum step checker if (sStep < std::numeric_limits<nr_double_t>::epsilon()) { error = 1; e = new qucs::exception (EXCEPTION_NO_CONVERGENCE); e->setText ("no convergence in %s analysis after %d sourceStepping " "iterations", desc.c_str(), iterations); throw_exception (e); break; } srcFactor = std::min (sPrev + sStep, 1.0); } // converged, increased the source-step else if (run < MaxIterations / 4) { sPrev = srcFactor; srcFactor = std::min (srcFactor + sStep, 1.0); sStep *= 1.5; } else { srcFactor = std::min (srcFactor + sStep, 1.0); } } // continue until no source factor is necessary while (sPrev < 1); subnet->setSrcFactor (1); return error; }
int nasolver<nr_type_t>::solve_once (void) { qucs::exception * e; int error = 0, d; // run the calculation function for each circuit calculate (); // generate A matrix and z vector createMatrix (); // solve equation system try_running () { runMNA (); } // appropriate exception handling catch_exception () { case EXCEPTION_PIVOT: case EXCEPTION_WRONG_VOLTAGE: e = new qucs::exception (EXCEPTION_NA_FAILED); d = top_exception()->getData (); pop_exception (); if (d >= countNodes ()) { d -= countNodes (); e->setText ("voltage source `%s' conflicts with some other voltage " "source", findVoltageSource(d)->getName ()); } else { e->setText ("circuit admittance matrix in %s solver is singular at " "node `%s' connected to [%s]", desc.c_str(), nlist->get (d).c_str(), nlist->getNodeString (d).c_str()); } throw_exception (e); error++; break; case EXCEPTION_SINGULAR: do { d = top_exception()->getData (); pop_exception (); if (d < countNodes ()) { logprint (LOG_ERROR, "WARNING: %s: inserted virtual resistance at " "node `%s' connected to [%s]\n", getName (), nlist->get (d).c_str(), nlist->getNodeString (d).c_str()); } } while (top_exception() != NULL && top_exception()->getCode () == EXCEPTION_SINGULAR); break; default: estack.print (); break; } // save results into circuits if (!error) saveSolution (); return error; }