void Solver::findDroneAssignment(){ DroneAssignmentHelper *droneSite = createDroneSiteInfo(); bool toContinue = true; const bool debug = debug2; int count = 0; const int threshold = 10; double best = getSolution(); while (toContinue && count < threshold) { toContinue = false; ++count; if (debug) std::cout << "Round " << count << std::endl; for (int i = 0; i < numCustomer - 1; ++i) { if (debug) std::cout << "Checked site " << i << ", Best = " << best << "." << std::endl; int index = droneSite[i].nodeID; flipDroneSite(index); double obj = getSolution(); if (obj < best) { toContinue = true; best = obj; } else { flipDroneSite(index); } if (best <= stoptingObject) { delete [] droneSite; return; } } } delete [] droneSite; }
//tries to add a solution in the repository if it is non-dominated //param - the candidate solution to be inserted in the repository bool Repository::add(Solution &candidate){ bool isDominated=false; bool equal=false; int dom; bool enteredArchive=false; if(actualSize==0){ //if the repository is empty, insert the solution insert(candidate); enteredArchive=true; }else{ for(int s=0;s<repositorySize+1;s++){ if(controlSolutions[s]){//if this solution is valid if(!candidate.isEqual(getSolution(s))){ //if the solutions are not equal //verify the dominance relation between two vectors //return 1 if sol1 dominates sol2, -1 if sol2 dominates sol1, 0 if they do not dominate each other, 2 if they are equal if(!strcmp(archiverType, "pbi") || !strcmp(archiverType, "tch") || !strcmp(archiverType, "wcp") || !strcmp(archiverType, "wsum") || !strcmp(archiverType, "r-ideal"))//repositories based on decomposition, if decomposition do not check dominance dom=0; else dom=dominance(candidate.objectiveVector, getSolution(s).objectiveVector, objectiveNumber); if(dom == 1){//if the candidate dominates the solution in the repository exclude(s); }else{ if(dom == -1){//if a solution in the repository dominates the candidate isDominated=true; if(vectorZero(getSolution(s).objectiveVector, objectiveNumber)){ fprintf(stderr, "\nERROR! Trying to insert in the repository a solution whose objectives are all 0\n"); exit(1); } break; } } }else{ //if the solutions are equal, discard the candidate equal=true; break; } } } if(!isDominated && !equal){ //if the solution is non-dominated candidate.dominated=false; if(actualSize<repositorySize){//if the repository is not empty nor full insert(candidate);//insert the solution enteredArchive=true; }else{ //if the repository is full enteredArchive=archiver(candidate); } }else{ candidate.dominated=true; enteredArchive=false; } } return enteredArchive; }
vector<vector<string> > solveNQueens(int n) { vector<vector<string> > solutionSet; vector<string> curSolution(n, string(n, '.')); getSolution(curSolution, 0, solutionSet); return solutionSet; }
int totalNQueens(int n) { int solutions = 0; vector<string> curSolution(n, string(n, '.')); getSolution(curSolution, 0, solutions); return solutions; }
::Ice::DispatchStatus RoboCompPlanning::Planning::___getSolution(::IceInternal::Incoming& __inS, const ::Ice::Current& __current) { __checkMode(::Ice::Normal, __current.mode); ::IceInternal::BasicStream* __is = __inS.startReadParams(); ::std::string Domain; ::std::string Problem; __is->read(Domain); __is->read(Problem); __inS.endReadParams(); ::RoboCompPlanning::Plan solution; try { bool __ret = getSolution(Domain, Problem, solution, __current); ::IceInternal::BasicStream* __os = __inS.__startWriteParams(::Ice::DefaultFormat); __os->write(solution); __os->write(__ret); __inS.__endWriteParams(true); return ::Ice::DispatchOK; } catch(const ::RoboCompPlanning::ServerException& __ex) { __inS.__writeUserException(__ex, ::Ice::DefaultFormat); } return ::Ice::DispatchUserException; }
BlisSolution * VrpModel::userFeasibleSolution(const double *solution, bool &userFeasible) { double objValue = 0.0; CoinPackedVector *solVec = getSolution(solution); VrpSolution *vrpSol = NULL; int msgLevel = AlpsPar_->entry(AlpsParams::msgLevel); userFeasible = true; createNet(solVec); if (!n_->isIntegral_){ if (msgLevel > 200) { std::cout << "UserFeasible: not integral" << std::endl; } userFeasible = false; } else { int rcnt = n_->connected(); int i; for (i = 0; i < rcnt; i++){ if (n_->compCuts_[i+1] < 2 - etol_){ userFeasible = false; if (msgLevel > 200) { std::cout << "UserFeasible: not 2" << std::endl; } break; } else if (n_->compDemands_[i+1] > capacity_){ userFeasible = false; if (msgLevel > 200) { std::cout << "UserFeasible: greater than capacity" << std::endl; } break; } } } if (userFeasible) { // Compute obj value for (int k = 0; k < numCols_; ++k) { objValue += objCoef_[k] * solution[k]; } // Create a VRP solution vrpSol = new VrpSolution(getNumCols(), solution, objValue, this); // TODO: add tour } // Free memory. delete solVec; return vrpSol; }
void MtxLP::getSupport(strvec& support, strvec queries, int kind) const{ stomap sol; getSolution(&sol, queries, kind, false); support.resize(sol.size()); strvec::iterator jt = support.begin(); for (stomap::iterator it = sol.begin(); it != sol.end(); ++it) *jt++ = it->first; }
element_type exact_project(const space_ptrtype & Xh, const double & val) { ex solution = getSolution(val); auto mesh = Xh->mesh(); auto gproj = vf::project( _space=Xh, _range=elements( mesh ), _expr=expr(solution,vars) ); return gproj; }
std::pair<Point, Point> getIntersection(const Point &a, const Point &b, const double &r) { Point d = b - a; double A = dot(d, d); double B = 2.0 * dot(d, a); double C = dot(a, a) - r * r; std::pair<double, double> s = getSolution(A, B, C); return std::make_pair(a + d * s.first, a + d * s.second); }
element_type grad_exact_project(const space_ptrtype & Xh) { ex solution = getSolution(); auto gradg = expr<1,Dim,2>(grad(solution,vars), vars ); auto mesh = Xh->mesh(); auto gproj = vf::project( _space=Xh, _range=elements( mesh ), _expr=expr(gradg,vars) ); return gproj; }
void solve() { scanf("%d", &n); while (n--) { scanf("%d", &k); int res = getSolution(k); printf("%d %d\n", res / MOD2, res % MOD2); } }
double L2_error(const space_ptrtype & Xh, const element_type & T, const double & values) const { // replace params by specified values ex solution = getSolution(values); auto g = expr(solution,vars); auto mesh = Xh->mesh(); return math::sqrt( integrate( elements(mesh), Px()*(idv(T) - g)*(idv(T) - g) ).evaluate()(0,0) ); }
//archiver wich consider the crowding distance to keep/exclude a solution //param - the solution to be submitted to the archiver bool Repository::crowdingDistanceArchiver(Solution &candidate){ //Solution temp[repositorySize+1]; //create a temporary repository to contain all the solutions plus the candidate double smallerCrowdingDistance=MAXDOUBLE; int idxSmallerCrowdingDistance=-1; //sync(temp); //sincronize the new repository with the solutions already found // for(int i=0;i<actualSize;i++) // temp[i]=solutions[i]; //memcpy(temp, solutions, sizeof(Solution)*actualSize); //solutions[actualSize]=candidate;//insert the new one insert(candidate); organize(); updateCrowdingDistances(solutions, actualSize); //update the crowing distances for(int i=0;i<actualSize;i++){//find the valid solution with smallest crowding distance if(controlSolutions[i] && getSolution(i).crowdingDistance<=smallerCrowdingDistance){ smallerCrowdingDistance=getSolution(i).crowdingDistance; idxSmallerCrowdingDistance=i; } } if(idxSmallerCrowdingDistance == -1){ fprintf(stderr,"\nCrowding Distance archiver error!\n The crowding distances of all particles in the repository is:\n"); for(int i=0;i<actualSize;i++) fprintf(stderr,"%f\n", getSolution(i).crowdingDistance); exit(1); } // if(!solutions[idxSmallerCrowdingDistance].isEqual(candidate)){ //if the candidate is not the solution with smallest crowding distance bool ret=true; if(candidate.isEqual(solutions[idxSmallerCrowdingDistance])) ret=false; exclude(idxSmallerCrowdingDistance); //remove the solution with the smallest crowding distance return ret; //insert(candidate);//insert the new solution // } //free(temp); }
bool Map::load (const std::string& name) { ScopedPtr<IMapContext> ctx(getMapContext(name)); resetCurrentMap(); if (name.empty()) { info(LOG_MAP, "no map name given"); return false; } info(LOG_MAP, "load map " + name); if (!ctx->load(false)) { error(LOG_MAP, "failed to load the map " + name); return false; } ctx->save(); _settings = ctx->getSettings(); _startPositions = ctx->getStartPositions(); _name = ctx->getName(); _title = ctx->getTitle(); _width = getSetting(msn::WIDTH, "-1").toInt(); _height = getSetting(msn::HEIGHT, "-1").toInt(); _solution = getSolution(); const std::string solutionSteps = string::toString(_solution.length()); _settings.insert(std::make_pair("best", solutionSteps)); info(LOG_MAP, "Solution has " + solutionSteps + " steps"); if (_width <= 0 || _height <= 0) { error(LOG_MAP, "invalid map dimensions given"); return false; } const std::vector<MapTileDefinition>& mapTileList = ctx->getMapTileDefinitions(); for (std::vector<MapTileDefinition>::const_iterator i = mapTileList.begin(); i != mapTileList.end(); ++i) { const SpriteType& t = i->spriteDef->type; info(LOG_MAP, "sprite type: " + t.name + ", " + i->spriteDef->id); MapTile *mapTile = new MapTile(*this, i->x, i->y, getEntityTypeForSpriteType(t)); mapTile->setSpriteID(i->spriteDef->id); mapTile->setAngle(randBetweenf(-0.1, 0.1f)); loadEntity(mapTile); } info(LOG_MAP, String::format("map loading done with %i tiles", mapTileList.size())); ctx->onMapLoaded(); _frontend->onMapLoaded(); const LoadMapMessage msg(_name, _title); _serviceProvider->getNetwork().sendToAllClients(msg); _mapRunning = true; return true; }
double H1_error(const space_ptrtype & Xh, const element_type & T, const double & values) const { // replace params by specified values ex solution = getSolution(values); auto gradg = expr<1,Dim,2>(grad(solution,vars), vars ); auto mesh = Xh->mesh(); double L2error = L2_error(Xh, T, values); double H1seminorm = math::sqrt( integrate( elements(mesh), Px()*(gradv(T) - gradg)*trans(gradv(T) - gradg) ).evaluate()(0,0) ); return math::sqrt( L2error*L2error + H1seminorm*H1seminorm); }
void SplitLP::minExchangeSets(solvec& solutions, stomap* obj, int dir, long nmax){ strvec externals = getExternals(); strvec txs(externals.size());// - obj->size()); strvec::iterator ti = txs.begin(); stomap::iterator oend = obj->end(); for (strvec::iterator it = externals.begin(); it != externals.end(); ++it){ string xname = *it; string txname = getTransporterName(xname, dir); stomap::iterator jt = obj->find(xname); if (jt != oend){ double coef = jt->second; coef /= this->vmax; fix(txname, coef, true, txname + "_mxs"); } else if (dir > 0){ fix(txname, 0, true); } *ti++ = get_opp_name(txname); } setObjDir(false); setLenObjective(txs, true); strvec itxs = get_int_names(txs); long i = 0; while(i < nmax){ stomap conv; stomap sol; Solve(true); getConversion(&conv); if (!isSolved()) break; getSolution(&sol, itxs, INT, false); if (!conv.empty()){ i++; if (dir < 0){ minimiseInput(&conv, txs); setLenObjective(txs, true); } solutions.push_back(conv); } if (i < nmax) cutSolution(&sol, true); } // cleanTmpRows(); }
//archiver wich consider the contributing HV to keep/exclude a solution //param - the solution to be submitted to the archiver bool Repository::HVArchiver(Solution &candidate){ double smallestHV=MAXDOUBLE; int idxSmallestHV=-1; insert(candidate); for(int i=0;i<actualSize;i++) getSolutions()[i].crowdingDistance=-1; organize(); updateContributingHypervolume(*this); //update the contributing HV of all solutions // updateContributingHypervolume(*this); for(int i=0;i<actualSize;i++){//find the valid solution with smallest contributing HV (stored on the crowding distance field) if(controlSolutions[i] && getSolution(i).crowdingDistance<=smallestHV){ smallestHV=getSolution(i).crowdingDistance; idxSmallestHV=i; } } if(idxSmallestHV == -1){ fprintf(stderr,"\nHV archiver error!\n The HV of all particles in the repository is:\n"); for(int i=0;i<actualSize;i++) fprintf(stderr,"%f\n", getSolution(i).crowdingDistance); exit(1); } // fprintf(stderr,"%d --> %f (%d)\n",idxSmallerR2, smallerR2, actualSize); // if(actualSize > repositorySize)//test of removing all solutions with no contribution bool ret=true; if(candidate.isEqual(solutions[idxSmallestHV])) ret=false; exclude(idxSmallestHV); //remove the solution with the smallest contribution return ret; }
//add a solution ignoring whether the repository is full or not void Repository::forceAdd(Solution &candidate){ bool isDominated=false; bool equal=false; if(actualSize==0){ //if the repository is empty, insert the solution insert(candidate); }else{ for(int s=0;s<repositorySize+1;s++){ if(controlSolutions[s]){//if this solution is valid if(!candidate.isEqual(getSolutions()[s])){ //if the solutions are not equal //verify the dominance relation between two vectors //return 1 if sol1 dominates sol2, -1 if sol2 dominates sol1, 0 if they do not dominate each other, 2 if they are equal if(dominance(candidate.objectiveVector, getSolution(s).objectiveVector, objectiveNumber) == 1){//if the candidate dominates the solution in the repository exclude(s); }else{ if(dominance(candidate.objectiveVector, getSolution(s).objectiveVector, objectiveNumber) == -1){//if a solution in the repository dominates the candidate isDominated=true; break; } } }else{ //if the solutions are equal, discard the candidate equal=true; break; } } } if(!isDominated && !equal){ //if the solution is non-dominated if(actualSize<repositorySize+1){//if there is memory left insert(candidate);//insert the solution }else{ //if there is not memory left fprintf(stderr,"REPOSITORY MEMORY UNAVAILABLE, INCREASE THE REPOSITORY MAXIMUM SIZE\n"); //exit(1); } } } }
void print() const { LOG(INFO) << "============================================================\n"; LOG(INFO) << "Error Information\n"; LOG(INFO) << " exact : " << getSolution() << "\n"; LOG(INFO) << " params : "; boost::for_each( parameters, [](symbol const& s ) {LOG(INFO) << s.get_name() << " ";}); LOG(INFO) << "\n"; if ( !M_rhs.empty() ) { LOG(INFO) << " rhs : " << getRhs() << "\n"; } LOG(INFO) << " convergence : " << convergence() << "\n"; LOG(INFO) << " convergence steps : " << numberOfConvergenceSteps() << "\n"; }
// TODO there's a seriouxx need for refactoring here ! Solution LpsolveAdaptator::getAdmissibleSolution(LinearProblem * lp) { lprec *lprec; int nbCol = lp->getVariables().size(); lprec = make_lp(0, nbCol); if (lprec == NULL) { // TODO raise an exception } /* set variables name to ease debugging */ for (int i = 0; i < (int)lp->getVariables().size(); ++i) { Variable * var = (lp->getVariables())[i]; set_col_name(lprec, i+1, var->getNameToChar()); if (var->isBinary()) { set_binary(lprec, i+1, TRUE); } } /* to build the model faster when adding constraints one at a time */ set_add_rowmode(lprec, TRUE); for (int i = 0; i < (int)(lp->getConstraints().size()); ++i) { // FIXME there's a bug here but I can't find it Constraint c = (Constraint)(lp->getConstraints()[i]); TermList terms = c.getTerms(); int col[terms.size()]; REAL row[terms.size()]; int j = 0; for (TermList::const_iterator it = terms.begin(); it != terms.end(); ++it, ++j) { // TODO check if this is fixed col[j] = ((Term)*it).getVariable().getPosition(); row[j] = ((Term)*it).getCoeff(); } // WARNING the Consraint uses the same operator values than in lp_lib.h if (!add_constraintex(lprec, j, row, col, c.getOperator(), c.getBound())) { // TODO raise an exception } } /* the objective function requires rowmode to be off */ set_add_rowmode(lprec, FALSE); return getSolution(lprec); }
void SDCFsiSolver::implicitSolve( bool corrector, const int k, const int kold, const scalar t, const scalar dt, const fsi::vector & qold, const fsi::vector & rhs, fsi::vector & f, fsi::vector & result ) { Eigen::Map<const fsi::vector> qoldFluid( qold.data(), dofFluid ); Eigen::Map<const fsi::vector> qoldSolid( qold.data() + dofFluid, dofSolid ); Eigen::Map<const fsi::vector> rhsFluid( rhs.data(), dofFluid ); Eigen::Map<const fsi::vector> rhsSolid( rhs.data() + dofFluid, dofSolid ); fluid->prepareImplicitSolve( corrector, k, kold, t, dt, qoldFluid, rhsFluid ); solid->prepareImplicitSolve( corrector, k, kold, t, dt, qoldSolid, rhsSolid ); // Perform FSI iterations to solve the coupled problem postProcessing->fsi->newMeasurementSeries(); // Initial solution fsi::vector x0; if ( corrector ) x0 = xStages.at( k + 1 ); else x0 = xStages.at( k ); postProcessing->initStage( k ); postProcessing->performPostProcessing( x0, postProcessing->fsi->x ); postProcessing->finalizeStage(); getSolution( result, f ); evaluateFunction( k, result, t, f ); xStages.at( k + 1 ) = postProcessing->fsi->x; fluid->finalizeImplicitSolve( k ); solid->finalizeImplicitSolve( k ); }
void getSolution(vector<string> &_curSolution, int _row, int &_solutions) { if (_row == _curSolution.size()) { _solutions++; return; } const int cols = _curSolution[0].size(); for (int colInd = 0; colInd < cols; colInd++) { _curSolution[_row][colInd] = 'Q'; if (validateSolution(_curSolution, _row, colInd)) { getSolution(_curSolution, _row + 1, _solutions); } _curSolution[_row][colInd] = '.'; } }
void test1() { size_t maxw = 4; size_t n = 4; size_t w[4] = {1,2,3,4}; size_t v[4] = {0,1,4,2}; size_t val, size; size_t* soln; Knapsack k = makeKnapsack(maxw, n, w, v); val = solve(k); printTable(k); printf("val %lu\n", val); assert(val == 4); soln = getSolution(k, &size); printf("size %lu soln[0] %lu\n", size, soln[0]); assert(size == 1); assert(soln[0] == 2); destroyKnapsack(k); free(soln); }
int makeOptStep(emb_optimizer optim, emb_opt_context opt_context, const double xcur[], const double uprev[], double ucur[]) { // Scale state double x_scaling[] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0}; double scaled_x[8]; unsigned int i; for(i = 0; i < 8; i++) { scaled_x[i] = xcur[i] / x_scaling[i]; } eval(scaled_x); getSolution(ucur); ucur[0] = ucur[0]; ucur[1] = ucur[1]; return 0; }
void test2() { /* http://cse.unl.edu/~goddard/Courses/CSCE310J/Lectures/Lecture8-DynamicProgramming.pdf */ size_t maxw = 5; size_t n = 4; size_t w[4] = {2,3,4,5}; size_t v[4] = {3,4,5,6}; size_t val, size; size_t* soln; Knapsack k = makeKnapsack(maxw, n, w, v); val = solve(k); printTable(k); printf("val %lu\n", val); assert(val == 7); soln = getSolution(k, &size); printf("size %lu soln[0] %lu soln[1] %lu\n", size, soln[0], soln[1]); assert(size == 2); assert(soln[0] == 1 && soln[1] == 0); destroyKnapsack(k); free(soln); }
TEST(MathLibCVodeTest, ExponentialWithJacobianNewton) { // initial values const double y0 = 1.0; const double t0 = 0.0; boost::property_tree::ptree tree; tree.put("linear_multistep_method", "BDF"); tree.put("nonlinear_solver_iteration", "Newton"); auto ode_solver = make_ode_solver<1>(tree); ASSERT_EQ(any_ode_solver_libs_available(), !!ode_solver); // Don't run the test if the ODE solver could not be constructed. if (!ode_solver) return; ode_solver->setFunction(f, df); ode_solver->setTolerance(abs_tol, rel_tol); ode_solver->setIC(t0, {y0}); ode_solver->preSolve(); const double dt = 1e-1; for (unsigned i = 1; i <= 10; ++i) { const double time = dt * i; ASSERT_TRUE(ode_solver->solve(time)); auto const y = ode_solver->getSolution(); auto const time_reached = ode_solver->getTime(); auto const y_dot = ode_solver->getYDot(time_reached, y); auto const y_ana = exp(-15.0 * time); auto const y_dot_ana = -15.0 * exp(-15.0 * time); check(time_reached, y[0], y_dot[0], time, y_ana, y_dot_ana); } }
void __stdcall RVExtension(char *output, int outputSize, const char *function) { ZERO_OUTPUT(); if (!strcmp(function, "version")) { strncpy(output, ACE_FULL_VERSION_STR, outputSize); } else { std::vector<std::string> argStrings = splitString(function); double initSpeed = std::stod(argStrings[0]); double airFriction = std::stod(argStrings[1]); double angleTarget = std::stod(argStrings[2]); double distance = std::stod(argStrings[3]); double result = getSolution(initSpeed, airFriction, angleTarget, distance); std::stringstream sstream; sstream << result; strcpy(output, sstream.str().c_str()); output[outputSize - 1] = '\0'; } EXTENSION_RETURN(); }
void MtxLP::optLenSol(stomap* sol, bool max, strvec queries, bool withzeroes, bool presolve){ optimiseLen(max, queries, presolve); getSolution(sol, queries, CONT, withzeroes); }
void Tableau::traceBasis(const TCHAR *label) const { if(isTracing(TRACE_SOLUTIONS)) trace(_T("%s\n%s"), label, getSolution().toString().cstr()); }
void MtxLP::getOptSol(stomap* sol, stomap* targ, bool max, int kind, bool withzeroes, bool presolve){ optimise(targ, max, presolve); getSolution(sol, kind, withzeroes); }