static SLocSolver* createSolver(BNBProblemData* pd, const std::string &sdata) { std::map<std::string, std::string> tls; std::string sheur, locsearch; XMLPars pars; double delta; pars.parse(sdata, tls); if(tls.find(SLOC_LS_TAG) == tls.end()) { BNB_ERROR_REPORT("Local search not set"); } else { locsearch = tls[SLOC_LS_TAG]; } if(tls.find(DELTA_TAG) == tls.end()) { delta = 0.; } else { delta = atof(tls[DELTA_TAG].c_str()); } GOInitialData < double > *id; id = dynamic_cast<GOInitialData < double > *> (pd); LocalOptimizer<double>* lo; lo = LocalOptimizerFactory::create(locsearch, id->mObj); SLocSolver* slocsolver = new SLocSolver(); slocsolver->setLocalOptimizer(lo); slocsolver->setDelta(delta); return slocsolver; }
static void processModel(const JSONNode & nd, MatModel& model) { bool nlayset = false; bool rangeset = false; bool lengthset = false; bool heightset = false; bool atomsset = false; for (auto i = nd.begin(); i != nd.end(); i++) { if (i->name() == JsonNames::numlayers) { model.mNumLayers = i->as_int(); nlayset = true; } else if (i->name() == JsonNames::range) { model.mRadius = i->as_float(); rangeset = true; } else if (i->name() == JsonNames::length) { model.mLength = i->as_float(); lengthset = true; } else if (i->name() == JsonNames::height) { model.mHeight = i->as_float(); heightset = true; } else if (i->name() == JsonNames::atoms) { BNB_ASSERT(nlayset); readIntVector(*i, model.mNumLayers, model.mLayersAtoms); atomsset = true; } else { BNB_ERROR_REPORT("Illegal name on parsing model data"); } } BNB_ASSERT(nlayset && rangeset && lengthset && heightset && atomsset); }
Solution getSolutionFromString(std::string& s) { class SP : public XMLListener { public: SP(Solution* sol) { mSol = sol; } void fireTag(int level, const std::string& tag, const std::string& s, int begin, int end) { std::string ss(s, begin, end - begin + 1); std::istringstream iss(ss); if(tag == "x"){ int n; n = mSol->mDim; for(int i = 0; i < n; i ++) { if(!iss.good()) { fprintf(stderr, "at %d\n", i); BNB_ERROR_REPORT("Parsing X-vector for a Solution failed\n"); } iss >> mSol->mX[i]; fprintf(stderr, "%d: %lf\n", i, mSol->mX[i]); } } else if(tag == "f") {
/** * Generates perturbed point * @param x source point * @param y resulting (perturbed) point */ void perturb(const FT * x, FT * y) { int n = mProblem.mBox.mDim; for (int i = 0; i < n; i++) { FT r = BnbRandom::get(x[i] + mR * mVicinity.mA[i], x[i] + mR * mVicinity.mB[i]); FT u; if (!mProblem.mVariables.empty()) { if (mProblem.mVariables[i] == NlpProblem<FT>::VariableTypes::GENERIC) { u = r; } else if (mProblem.mVariables[i] == NlpProblem<FT>::VariableTypes::INTEGRAL) { FT p = floor(r); u = ((r - p) > 0.5) ? p + 1 : p; } else if (mProblem.mVariables[i] == NlpProblem<FT>::VariableTypes::BOOLEAN) { u = (r > 0.5) ? 1 : 0; } else { BNB_ERROR_REPORT("Unknown variable type"); } } else { u = r; } u = BNBMAX(u, mProblem.mBox.mA[i]); u = BNBMIN(u, mProblem.mBox.mB[i]); y[i] = u; } }
/** * Creates problem data instance according to * problem descriptor * @param problemdsc problem descriptor * @return problem data structure pointer */ static BNBProblemData * createProblemData(const std::string& problemDsc) { BNBProblemData* pd; XMLPars pars; std::map<std::string, std::string> tls; pars.parse(problemDsc, tls); std::string pname, pdata; pname = tls.begin()->first; pdata = tls.begin()->second; if(pname == BNB_GLOB_TAG) { std::string objdata, boxdata; Objective<double>* obj; GOInitialData<double>* gid; tls.clear(); pars.parse(pdata, tls); if(tls.find(BNB_OBJECTIVE_TAG) == tls.end()) { BNB_ERROR_REPORT("Objective not set"); } else { objdata = tls[BNB_OBJECTIVE_TAG]; } if(tls.find(BNB_BOX_TAG) == tls.end()) { BNB_ERROR_REPORT("Box not set"); } else { boxdata = tls[BNB_BOX_TAG]; } gid = new GOInitialData<double>(); obj = ObjFactory<double>::create(objdata); gid->mObj = obj; BoxFactory::create(boxdata, gid); pd = gid; } else if(pname == BNB_CRYPTO_TAG) { std::string cnf; tls.clear(); pars.parse(pdata, tls); if(tls.find(CRYPTO_CNF_TAG) == tls.end()) { BNB_ERROR_REPORT("CNF not found"); } else { cnf = tls[CRYPTO_CNF_TAG]; } CryptoData * cd = new CryptoData(); cd->fromString(cnf); pd = (BNBProblemData*)cd; } else BNB_ERROR_REPORT("Unsupported problem type"); return pd; }
void processCommand(std::vector< std::string > &args) { /* printf("PROCESS: "); for(int i = 0; i < args.size(); i ++) { printf("[%s] ", args[i].c_str()); } printf("\n");*/ if(args.empty()) { *mAction = BNBActions::ERASE; } else if(args[0] == "forward") { *mAction = BNBActions::FORWARD | BNBActions::ERASE; eraseCommand(); } else if(args[0] == "drop") { *mAction = BNBActions::DROP | BNBActions::ERASE; eraseCommand(); } else if(args[0] == "var") { BNB_ASSERT(args.size() == 2); processVar(args[1]); } else if(args[0] == "set") { BNB_ASSERT(args.size() == 3); processAssign(args[1], args[2]); } else if(args[0] == "inc") { BNB_ASSERT(args.size() == 3); processInc(args[1], args[2]); } else if(args[0] == "cat") { BNB_ASSERT(args.size() == 3); processCat(args[1], args[2]); } else if(args[0] == "wait") { BNB_ASSERT(args.size() == 4); processWait(args[1], args[2], args[3]); } else if(args[0] == "echo") { processEcho(args); } else if(args[0] == "erase") { *mAction = BNBActions::ERASE; eraseCommand(); } else if(args[0] == "save") { processSave(args[1], args[2]); } else if(args[0] == "append") { processAppend(args[1], args[2]); } else if(args[0] == "load") { processLoad(args[1], args[2]); } else if(args[0] == "mkdir") { processMkdir(args[1]); } else if(args[0] == "skip") { eraseCommand(); } else if(args[0] == "exec") { processExec(args[1]); } else if(args[0] == "exit") { *mAction = BNBActions::EXIT; eraseCommand(); } else { printf("%s\n", args[0].c_str()); BNB_ERROR_REPORT("Unrecognized command"); } }
static void processLattice(const JSONNode & nd, int n, double& v, double* x) { for (auto i = nd.begin(); i != nd.end(); i++) { if (i->name() == JsonNames::evalue) { v = i->as_float(); } else if (i->name() == JsonNames::lvector) { readDoubleVector(*i, n, x); } else { BNB_ERROR_REPORT("Unknown name while processing lattice description"); } } }
static void processBox(const JSONNode & nd, Box<double> & box) { int n = box.mDim; for (auto i = nd.begin(); i != nd.end(); i++) { if (i->name() == JsonNames::boxa) { readDoubleVector(*i, n, (double*) (box.mA)); } else if (i->name() == JsonNames::boxb) { readDoubleVector(*i, n, (double*) (box.mB)); } else { BNB_ERROR_REPORT("Unknown name while processing box description"); } } }
std::string* getSpecVar(std::string* var) { std::string *rv; if(*var == "time") { evalTime(); return &mTime; } else if(*var == BNB_COMMAND_DESCRIPTION){ rv = &(mCurCommand->mDsc); } else BNB_ERROR_REPORT("Unrecognized special variable"); return rv; }
/** * Extracts JSON model from a string input * @param input JSON string * @param model model to fill in */ static void parseModelData(const std::string& input, MatModel& model) { JSONNode nd = libjson::parse(input); bool modelset = false; for (auto i = nd.begin(); i != nd.end(); i++) { if (i->name() == JsonNames::modelname) { processModel(*i, model); modelset = true; break; } } if (!modelset) BNB_ERROR_REPORT("Model data missing\n"); }
/** * Parses lattice definition vector from JSON string * @param input JSON string * @param model material model * @param v energy value to store * @param x vector to fill in */ static void parseLatticeData(const std::string& input, const MatModel& model, double& v, double* x) { JSONNode nd = libjson::parse(input); bool latticeset = false; for (auto i = nd.begin(); i != nd.end(); i++) { if (i->name() == JsonNames::lattice) { processLattice(*i, model.mNumLayers * 3, v, x); latticeset = true; break; } } if (!latticeset) BNB_ERROR_REPORT("Lattice data missing\n"); }
/** * Parses box data * @param input input string with JSON description * @param box to fill in */ static void parseBoxData(const std::string& input, Box<double>& box) { JSONNode nd = libjson::parse(input); bool boxset = false; for (auto i = nd.begin(); i != nd.end(); i++) { if (i->name() == JsonNames::box) { processBox(*i, box); boxset = true; break; } } if (!boxset) BNB_ERROR_REPORT("Lattice data missing\n"); }
/** * Create objective for Rastrigin * @param odata objective data * @return objective */ static Objective<FT>* create(const std::string& odata) { XMLPars pars; std::map<std::string, std::string> tls; Potential<FT>* pot; int natoms, dim; pars.parse(odata, tls); if(tls.find(RASTR_DIM_TAG) == tls.end()){ BNB_ERROR_REPORT("Space dimension not set"); } else { dim = atoi(tls[MOLEC_DIM_TAG].c_str()); } Objective<FT>* obj = new Rastr<FT> (dim, 10.); return obj; }
/** * Create serial solver from problem data and solver type * * @param pd pointer to the problem data * * @param solverType type of the solver * * @return created solver * */ static SerialSolver* createSolver(BNBProblemData* pd, const std::string& solverType) { SerialSolver* solver = NULL; std::string stype, sdata; std::map<std::string, std::string> mp; XMLPars pars; pars.parse(solverType, mp); stype = mp.begin()->first; sdata = mp.begin()->second; if(stype == BNB_SLOC_SOLVER) { solver = SLocSolverFactory::createSolver(pd, sdata); } else { BNB_ERROR_REPORT("Solver type not recognized\n"); } return solver; }
/** * Allocate memory for this pointer * * @param num number of items * */ void alloc (unsigned int num) { if(mMemManager == NULL) { mMemManager = MMRegistry::getMemManager(); } //BNB_ASSERT(mMemManager == MMRegistry::getMemManager()); if(mDim != 0) { BNB_ERROR_REPORT("Trying to allocate non-null pointer"); } if(num > 0) { setDim(num); mCounterBlock = mMemManager->alloc(sizeof(int)); *((int*)mCounterBlock.mP) = 1; mXBlock = mMemManager->alloc(sizeof(T) * num); } }
void processWait(std::string& lop, std::string& sign, std::string &rop) { std::string *lopv, *ropv; int ilop, irop; lopv = getIdent(lop); ropv = getIdent(rop); ilop = atoi(lopv->c_str()); irop = atoi(ropv->c_str()); if(sign == "<") { if(ilop < irop) { eraseCommand(); } else { *mAction = BNBActions::SKIP; } } else { BNB_ERROR_REPORT("Unsupported comparison"); } }
int main(int argc, char** argv) { int ntries = 100; if (argc != 2) BNB_ERROR_REPORT("Usage: genpoints.exe json_file\n"); std::string jsons; FileUtils::getStringFromFile(argv[1], jsons); lur::MatModel mm; lur::ParseJson::parseModelData(jsons, mm); int n = mm.mNumLayers * 3; lur::PairPotentialEnergy enrg(mm, ljpotent); const int N = mm.mNumLayers * 3; lur::LurieObj obj(enrg, mm); Box<double> box(N); double x[N]; lur::ParseJson::parseBoxData(jsons, box); std::cout << "Searching in box " << BoxUtils::toString(box) << "\n"; RndFill<double> rfill(box); double v; auto output = [ & ] (int I){ std::string json; json += "{\n"; lur::GenJSON::genModel(mm, json); json += ", \n"; lur::GenJSON::genBox(box, json); json += ", \n"; lur::GenJSON::genLattice(mm, v, x, json); json += "\n}\n"; //std::cout << json << "\n"; std::ostringstream os; os << I; FileUtils::updateFileWithContent(os.str().c_str(), json.c_str()); }; for (int i = 0; i < ntries; i++) { rfill.getPoint(x); v = obj.func(x); VecUtils::vecPrint(n, x); std::cout << "Found v = " << v << "\n"; output(i); } return 0; }
void simulator::resolver::setSearchStrategy(int strategy) { solvable = (strategy != SearchStrategies::NOS); if (solvable) { switch (strategy) { // best-first search case SearchStrategies::BFS : task_pool.set_strategy(pools::pool_strategy::BFS); break; // depth-first search case SearchStrategies::DFS : task_pool.set_strategy(pools::pool_strategy::DFS); break; // width-first search case SearchStrategies::WFS : task_pool.set_strategy(pools::pool_strategy::WFS); break; // this case can't occur default: BNB_ERROR_REPORT("No such strategy"); } } }
/* * Testing the perturbers */ int main(int argc, char** argv) { if (argc != 2) BNB_ERROR_REPORT("Usage: searchmbh.exe json_file\n"); std::string jsons; FileUtils::getStringFromFile(argv[1], jsons); lur::ParseJson::parseModelData(jsons, mm); double ev; lur::ParseJson::parseLatticeData(jsons, mm, ev, x); #if 0 lur::PotentialCutter pc(6, 0.5, lur::ljpotent); lur::PairPotentialEnergy enrg(mm, pc); #endif #if 0 // Morse lur::PairPotentialEnergy enrg(mm, morsepotent); #endif #if 1 // Tersoff lur::TersoffParams tparam; lur::fillCarbonParametersTersoffOriginal(tparam); lur::TersoffUtils tutils(tparam); lur::TersoffEnergy enrg(mm, tutils); //enrg.setFixedAtoms(true); #endif const int N = mm.mNumLayers * 3; lur::LurieObj obj(enrg, mm); NumGradObjective<double> nobj(obj); nobj.setH(1E-8); Box<double> box(N); lur::ParseJson::parseBoxData(jsons, box); NlpProblem<double> prob; prob.mBox = box; prob.mObj = &obj; BBStopper stp; BBBoxDescent<double> locs(box, &stp); locs.getOptions().mHInit = 4; locs.getOptions().mDec = 0.5; locs.getOptions().mHLB = 1e-6; locs.getOptions().mInc = 1.75; locs.setObjective(&nobj); RndFill<double> rfill(box); Box<double> vicinity(N); initVicinity(N, vicinity); #if 0 StaticPerturber<double> perturber(prob, vicinity); #else AdaptPerturber<double> perturber(prob, vicinity, AdaptPerturber<double>::Params({1, .01, 2, 0.1, 1.1})); #endif #if 0 MBHBoxCon<double> mbhbc(prob, perturber, H); #else MBHBoxCon<double> mbhbc(prob, perturber, H, &locs); #endif signal(SIGINT, output); bv = mbhbc.search(x); std::cout << "Found v = " << bv << "\n"; VecUtils::vecPrint(N, x); std::string json; json += "{\n"; lur::GenJSON::genModel(mm, json); json += ", \n"; lur::GenJSON::genBox(box, json); json += ", \n"; lur::GenJSON::genLattice(mm, bv, x, json); json += "\n}\n"; std::cout << json << "\n"; return 0; }
int main(int argc, char** argv) { // Dimension int n = 2; // Box size int d = 3; // Accuracy double eps = 0.1; // Cut analysis depth int ldepth = 1; // Use or not boxed cut bool boxedcut = true; if (argc != 7) BNB_ERROR_REPORT("Usage runpolymi.exe dimension box_size polynom cut_depth use_boxed_cut (0/1) record"); n = atoi(argv[1]); d = atoi(argv[2]); ldepth = atoi(argv[4]); boxedcut = (atoi(argv[5]) == 0) ? false : true; double record = atof(argv[6]); PolyMIFactory polymifact(n, d, argv[3]); NlpProblem<double>* nlp = polymifact.getProb(); /* Setup cut generators */ /* Cut generator for objective*/ NlpRecStore<double> ors(record, nlp); PointCutFactory<double> pfact(&ors); PolyObjective<double>* obj = dynamic_cast<PolyObjective<double>*> (nlp->mObj); PolyEigenSupp objEigenSupp(obj); EigenCutFactory<double> objEigenCutFact(&ors, &objEigenSupp, obj, eps); /* Setup composite cut factory */ CompCutFactory <double> fact; fact.push(&pfact); fact.push(&objEigenCutFact); /* Setup cut applicator */ SmartCutApplicator<double> sca(nlp->mVariables); if (boxedcut == 0) sca.getOptions() = SmartCutApplicator<double>::Options::CUT_BALL_SIMPLE; if (boxedcut == 1) sca.getOptions() = SmartCutApplicator<double>::Options::CUT_BALL_BOXED; if (boxedcut == 2) sca.getOptions() = (SmartCutApplicator<double>::Options::CUT_BALL_SIMPLE | SmartCutApplicator<double>::Options::CUT_BALL_BOXED); /* Setup splitter */ //StdBoxSplitter<double> splt; MIBoxSplitter<double> splt(nlp->mVariables); /* Setup solver */ BNCSolver<double> bnc(&fact, &sca, &splt, ldepth); BNBTree tree(makeRootNode(*nlp)); BNBNode* root = tree.getRoot(); WFSDFSManager manager; manager.setOptions(WFSDFSManager::Options::DFS); manager.reg(root); BNCState<double> state(&manager, &ors); state.mForest.push_back(&tree); /* Solving problem */ bool ru; long long int iters = 10000000; bnc.solve(iters, state, ru); /* Printing results*/ std::cout << iters << " iterations\n"; std::cout << "Record = " << state.mRecord->getValue() << "\n"; VecUtils::vecPrint(n, (double*) ors.getX()); return 0; }
/** * MANDATORY, upper bound for the function values. * * return lowest bound */ static ValueType absoluteBound () { BNB_ERROR_REPORT("Absolute bound for mutivalue function is not implmented\n"); }
double getFuncLipzConstant(double* a, double* b) { BNB_ERROR_REPORT("NOT IMPLEMENTED"); }
main(int argc, char* argv[]) { typedef GOFactory < double > Fact; #ifdef PARALLEL_VERSION typedef PTraverse < Fact > Traverse; #else typedef WTraverse < Fact > Traverse; #endif // typedef WTraverse < Fact, std::stack <Fact::Set> > Traverse; typedef BNBSeqSolver < Traverse > Solver; int n = 4; double eps = 0.0000001; double delta = 0.000000; F f; C1 c1; C2 c2; C3 c3; LinObjective<double> lo1; lo1.setDim(4); double lcoe1[5] = {-1., 0., 0.0193, 0., 0.}; lo1.setCoeff(lcoe1); LinObjective<double> lo2; lo2.setDim(4); double lcoe2[5] = {0., -1., 0.00954, 0., 0.}; lo2.setCoeff(lcoe2); //c1.setTolerance(2 * delta); GOInitialData<double> id; SegVecDecomp<Fact> decomp; //Decomposer<Fact> decomp; LipzFuncDiscarder<double> dscf; LipzGradDiscarder<double> dscg; LipzFuncDiscarder<double> dsccons1; LipzFuncDiscarder<double> dsccons2; LipzFuncDiscarder<double> dsccons3; LipzGradDiscarder<double> dscgcons1; LipzGradDiscarder<double> dscgcons2; LipzGradDiscarder<double> dscgcons3; LinConsDiscarder<double> lcons1; LinConsDiscarder<double> lcons2; SimpleConstraintChecker<double> scheck; Fact fact; std::map<int, double> steps; steps[0] = 0.0625; steps[1] = 0.0625; IntStepDiscarder<double> stepd(steps); IntSolumak<double> solumak(steps); init(n, &f, id); fact.setInitialData(&id); fact.setSolutionMaker(&solumak); scheck.addInequalityConstraint(&c1, delta); scheck.addInequalityConstraint(&c2, delta); scheck.addInequalityConstraint(&c3, delta); fact.setConstraintChecker(&scheck); dscf.setEps(eps); dscf.setObjective(&f); //decomp.setBallExcludeLevel(0); dscg.setEps(eps); dscg.setObjective(&f); dscg.getOptions() &= ~LipzGradDiscarder<double>::Options::CHECK_GRAD; dscg.getOptions() &= ~LipzGradDiscarder<double>::Options::CHECK_GRAD_COMP; dscg.getOptions() &= ~LipzGradDiscarder<double>::Options::UPDATE_RECORD; //dscg.getOptions() |= LipzGradDiscarder<double>::Options::DO_PRIMARY_BALL_CUT; dscg.setInitialData(&id); dsccons1.setObjective(&c1); dsccons2.setObjective(&c2); dsccons3.setObjective(&c3); /* fact.addDiscarder(&dsccons1); fact.addDiscarder(&dsccons2); fact.addDiscarder(&dsccons3); fact.addDiscarder(&dscf);*/ dscgcons1.setObjective(&c1); dscgcons2.setObjective(&c2); dscgcons3.setObjective(&c3); dscgcons1.setInitialData(&id); dscgcons2.setInitialData(&id); dscgcons3.setInitialData(&id); //dscgcons3.getOptions() |= LipzGradDiscarder<double>::Options::DO_PRIMARY_BALL_CUT; lcons1.setObjective(&lo1); lcons1.getOptions() |= LinConsDiscarder<double>::Options::DO_CUT; lcons2.setObjective(&lo2); lcons2.getOptions() |= LinConsDiscarder<double>::Options::DO_CUT; fact.addDiscarder(&decomp); fact.addDiscarder(&stepd); #if 0 fact.addDiscarder(&dscgcons1); fact.addDiscarder(&dscgcons2); #else fact.addDiscarder(&lcons1); fact.addDiscarder(&lcons2); #endif fact.addDiscarder(&dscgcons3); fact.addDiscarder(&dscg); Solver solver(&fact); #ifdef PARALLEL_VERSION if(argc < 2) BNB_ERROR_REPORT("Usage: main.exe #threads\n"); int nt = atoi(argv[1]); solver.setNumThreads(nt); solver.init(MAX_MEM_SIZE, 1024 * 1024, 32); solver.setPutChunk(32); solver.setLocalSteps(100 * 1024*1024); solver.setUpdateRatio(128); #endif solver.setDebugOptions( Solver::Options::PRINT_RESULTING_STAT // | Solver::Options::PRINT_STATE ); // solver.Traverse::setDebugOptions(Traverse::Options::PRINT_STEP); // solver.setDebugOptions(Solver::Options::PRINT_RESULTING_STAT | Solver::Options::PRINT_INITIAL_VAL); //solver.setRecord(n - 1); solver.solve(); c1.setTolerance(0.0); if(solver.getSolutionContainer()->empty()) printf("Empty container\n"); printf("Minimum = %s\n", solver.getSolutionContainer()->top().toString().c_str()); scheck.print((double*)solver.getSolutionContainer()->top().mX); double corr[4]; for(int i = 0; i < 4; i ++) corr[i] = solver.getSolutionContainer()->top().mX[i]; correct(corr); printf("Corrected = [%lf, %lf, %lf, %lf]->%lf\n", corr[0], corr[1], corr[2], corr[3], f.func(corr)); scheck.print(corr); double Sandren[4] = {1.125, 0.625, 47.70, 117.701}; printf("Sandren = %lf\n", f.func(Sandren)); scheck.print(Sandren); double Coello[4] = {0.8125, 0.4375, 42.097398, 176.654047}; printf("Coello = %lf\n", f.func(Coello)); scheck.print(Coello); double LINGO[4] = {0.75, 0.375, 38.860, 221.365}; printf("LINGO = %lf\n", f.func(LINGO)); scheck.print(LINGO); /* double Gergel[4] = {0.29, 0.32, 14.13, 145.85}; Gergel[0] = 0.299364613880741; Gergel[1] = 0.323802541544474; Gergel[2] = 14.137341153470189; Gergel[3] = 145.850439882697940; scheck.print(Gergel); printf("Gergel = %lf\n", f.func(Gergel)); */ }
/* * Testing the perturbers */ int main(int argc, char** argv) { if (argc != 4) BNB_ERROR_REPORT("Usage: searchall.exe json_file log_for_incumbents log_for_allvalues\n"); std::string jsons; FileUtils::getStringFromFile(argv[1], jsons); lur::MatModel mm; lur::ParseJson::parseModelData(jsons, mm); double x[mm.mNumLayers * 3]; double y[mm.mNumLayers * 3]; double ev; lur::ParseJson::parseLatticeData(jsons, mm, ev, x); #if 0 // Lennard Jones lur::PotentialCutter pc(3 * 3, 3 * 3 - 2.8 * 2.8, lur::ljpotent); lur::PairPotentialEnergy enrg(mm, pc); #endif #if 0 // Morse lur::PairPotentialEnergy enrg(mm, morsepotent); #endif #if 1 // Tersoff lur::TersoffParams tparam; lur::fillCarbonParametersTersoffOriginal(tparam); lur::TersoffUtils tutils(tparam); lur::TersoffEnergy enrg(mm, tutils); #endif const int N = mm.mNumLayers * 3; lur::LurieObj obj(enrg, mm); Box<double> box(N); lur::ParseJson::parseBoxData(jsons, box); BBStopper stp; BBBoxDescent<double> locs(box, &stp); locs.getOptions().mHInit = 4; locs.getOptions().mDec = 0.5; locs.getOptions().mHLB = 1e-6; locs.getOptions().mInc = 1.75; locs.setObjective(&obj); BoxconProblem<double> bp; bp.mBox = box; bp.mObj = &obj; LipBounder<double> lb(bp.mObj); const double lipconst = 128; lb.setLipConst(lipconst); BoxconBNB<double> bnb; bnb.addBounder(&lb); bnb.getOptions().mEps = 0.1; bnb.init(bp); double bestv = 0; int cnt = 0; time_t tstart = time(NULL); auto hndl = [&](BoxconBNB<double>::Solution& incum, BoxconBNB<double>::Sub & sub) { BoxUtils::getCenter(sub.mBox, y); double u = obj.func(y); //std::cout << "u = " << u << "\n"; // if ((u < 0.9 * incum.mValue) && ((cnt++ % 100) == 0)) { //if ((cnt++ % 100) == 0) { if (true) { //if (BoxUtils::radius(sub.mBox) < 2) { std::cout << "Search from " << u << "\n"; std::cout << "In box " << BoxUtils::toString(sub.mBox) << "\n"; std::cout << " with radius " << BoxUtils::radius(sub.mBox) << "\n"; std::cout << " with lb " << sub.mBound << "\n"; VecUtils::vecPrint(N, y); double v; locs.search(y, &v); auto logval = [&] (const char* fname, double v) { time_t tcur = time(NULL) - tstart; std::ostringstream os; os << tcur << " " << v << "\n"; FileUtils::updateFileWithContent(fname, os.str().c_str()); }; std::cout << "Found v = " << v << "\n"; logval(argv[3], v); VecUtils::vecPrint(N, y); if (v < bestv) { bestv = v; std::cout << "Improved incumbent " << bestv << " from " << u << "\n"; incum.mValue = v; VecUtils::vecPrint(N, y); VecUtils::vecCopy(N, y, x); logval(argv[2], v); enrg.setFixedAtoms(true); double v; locs.search(y, &v); enrg.setFixedAtoms(false); std::cout << "Free configuration " << v << "\n"; VecUtils::vecPrint(N, y); } } }; bnb.setHandler(hndl); long long steps = 1000000; bnb.solve(steps); std::cout << steps << " performed\n"; #if 0 std::cout << "The solution is " << bnb.getIncumbent().mValue << " found in " << steps << " steps \n"; VecUtils::vecPrint(N, (double*) bnb.getIncumbent().mX); VecUtils::vecCopy(N, (double*) bnb.getIncumbent().mX, x); #endif #if 0 std::cout << "Searching in box " << BoxUtils::toString(box) << "\n"; double v = mbhbc.search(x); #endif enrg.setFixedAtoms(true); double v; locs.search(x, &v); std::cout << "Found v = " << v << "\n"; VecUtils::vecPrint(N, x); std::string json; json += "{\n"; lur::GenJSON::genModel(mm, json); json += ", \n"; lur::GenJSON::genBox(box, json); json += ", \n"; lur::GenJSON::genLattice(mm, v, x, json); json += "\n}\n"; std::cout << json << "\n"; return 0; }
int main(int argc, char** argv) { if (argc != 2) BNB_ERROR_REPORT("Usage: searchgdsc.exe json_file\n"); std::string jsons; FileUtils::getStringFromFile(argv[1], jsons); lur::ParseJson::parseModelData(jsons, mm); double ev; lur::ParseJson::parseLatticeData(jsons, mm, ev, x); #if 0 // Lennard Jones lur::PairPotentialEnergy enrg(mm, lur::ljpotent); #endif #if 0 // Cutted Lennard Jones lur::PairPotentialEnergy enrg(mm, ljcutpotent); #endif #if 0 // Morse lur::PairPotentialEnergy enrg(mm, lur::morsepotent); #endif #if 0 lur::PotentialCutter pc(6, 0.5, lur::ljpotent); lur::PairPotentialEnergy enrg(mm, pc); #endif #if 1 // Tersoff lur::TersoffParams tparam; lur::fillCarbonParametersTersoffOriginal(tparam); lur::TersoffUtils tutils(tparam); lur::TersoffEnergy enrg(mm, tutils); //enrg.setFixedAtoms(true); #endif #if 1 // Sets the fixed atoms attribute // enrg.setFixedAtoms(true); #endif const int N = mm.mNumLayers * 3; lur::LurieObj obj(enrg, mm); NumGradObjective<double> nobj(obj); nobj.setH(1E-4); Box<double> box(N); lur::ParseJson::parseBoxData(jsons, box); std::cout << "Searching in box " << BoxUtils::toString(box) << "\n"; #if 0 GbdStopper stp(box); GradBoxDescent<double> locs(box, &stp); locs.getOptions().mGInit = .1; #endif #if 1 BBStopper stp; BBBoxDescent<double> locs(box, &stp); locs.getOptions().mHInit = 4; locs.getOptions().mDec = 0.5; locs.getOptions().mHLB = 1e-6; locs.getOptions().mInc = 1.75; //locs.getOptions().mOnlyCoordinateDescent = true; #endif // TMP DEBUG #if 0 double xxx[12] = {0.866173, 0.982091, 0.982755, 0.950314, 2.08087, 1.84751, 0.4, 2.99746, 1.86217, 0.865676, 1.49372, 0.974428}; std::cout << nobj.func(xxx) << "\n"; double ggg[12]; nobj.grad(xxx, ggg); VecUtils::vecPrint(12, ggg); exit(0); #endif // TMP signal(SIGINT, output); VecUtils::vecPrint(N, x); locs.setObjective(&nobj); locs.search(x, &bv); std::cout << "Found v = " << bv << "\n"; VecUtils::vecPrint(N, x); std::string json; json += "{\n"; lur::GenJSON::genModel(mm, json); json += ", \n"; lur::GenJSON::genBox(box, json); json += ", \n"; lur::GenJSON::genLattice(mm, bv, x, json); json += "\n}\n"; std::cout << json << "\n"; return 0; }
void action(Event& event, const SolverInfo& info, Action& action) { while (true) { switch (mState) { case States::I: BNB_ASSERT(event.mCode == Events::START); mState = States::ZERO_STRAT_I; action.mCode = BNBScheduler::Actions::SET_SEARCH_STRATEGY; action.mArgs[0] = SearchStrategies::NOS; break; case States::ZERO_STRAT_I: BNB_ASSERT(event.mCode == Events::SEARCH_STRATEGY_SET); mState = States::SETTING_BOUNDER; action.mCode = BNBScheduler::Actions::SET_BOUNDING_METHOD; action.mArgs[0] = mParams.mMB; break; case States::SETTING_BOUNDER: BNB_ASSERT(event.mCode == Events::BOUNDING_METHOD_SET); mState = States::SETTINGHEUR_I; action.mCode = BNBScheduler::Actions::SET_HEURISTIC; action.mArgs[0] = mParams.mIH; break; case States::SETTINGHEUR_I: BNB_ASSERT(event.mCode == Events::HEURISTIC_SET); mState = States::SOLVING_I; action.mCode = BNBScheduler::Actions::SOLVE; action.mArgs[0] = mParams.mIHS; break; case States::SOLVING_I: BNB_ASSERT(event.mCode == Events::DONE); mState = States::CHECKING; continue; case States::CHECKING: if (info.mNSub == 0) { mState = States::T; action.mCode = BNBScheduler::Actions::EXIT; } else { mState = States::SETTINGHEUR_M; action.mCode = BNBScheduler::Actions::SET_HEURISTIC; action.mArgs[0] = mParams.mMH; } break; case States::SETTINGHEUR_M: BNB_ASSERT(event.mCode == Events::HEURISTIC_SET); mState = States::ZERO_STRAT_M; action.mCode = BNBScheduler::Actions::SET_SEARCH_STRATEGY; action.mArgs[0] = SearchStrategies::NOS; break; case States::ZERO_STRAT_M: BNB_ASSERT(event.mCode == Events::SEARCH_STRATEGY_SET); mState = States::SOLVING_M_H; action.mCode = BNBScheduler::Actions::SOLVE; action.mArgs[0] = mParams.mMHS; break; case States::SOLVING_M_H: BNB_ASSERT(event.mCode == Events::DONE); mState = States::ZERO_HEUR_M; action.mCode = BNBScheduler::Actions::SET_HEURISTIC; action.mArgs[0] = 0; break; case States::ZERO_HEUR_M: BNB_ASSERT(event.mCode == Events::HEURISTIC_SET); mState = States::SETTINGSTRAT_M; action.mCode = BNBScheduler::Actions::SET_SEARCH_STRATEGY; action.mArgs[0] = mParams.mMBR; break; case States::SETTINGSTRAT_M: BNB_ASSERT(event.mCode == Events::SEARCH_STRATEGY_SET); mState = States::SOLVING_M_B; action.mCode = BNBScheduler::Actions::SOLVE; action.mArgs[0] = mParams.mMBRS; break; case States::SOLVING_M_B: BNB_ASSERT(event.mCode == Events::DONE); mState = States::CHECKING; continue; default: BNB_ERROR_REPORT("Illegal state\n"); } break; } }
/** * Evaluates the function gradients (one per criteria) in a given point * * @param x point the parameter array * @param y pointe to hold gradient matrix */ virtual void grad(double* x, double* g) { BNB_ERROR_REPORT("Not implemented"); }
std::string* getMem(std::string* var) { if(mMemory.find(*var) == mMemory.end()) BNB_ERROR_REPORT("Variable does not exist"); return &(mMemory[*var]); }
main(int argc, char* argv[]) { typedef GOFactory < double > Fact; typedef WTraverse < Fact > Traverse; typedef BNBSeqSolver < Traverse > Solver; typedef std::priority_queue <Fact::Set> TQ; int n; double eps = .001; bool rv = true; GOInitialData<double> id; n = 2; Sqsum obj(n); id.mObj = &obj; id.mA = (double*) malloc(n * sizeof(double)); id.mB = (double*) malloc(n * sizeof(double)); id.mA[0] = -10.; id.mA[1] = -10.; id.mB[0] = 50.; id.mB[1] = 10.; LipzGradDiscarder<double> dscg; Fact fact; SegVecDecomp<Fact> decomp; dscg.setEps(eps); dscg.setObjective(&obj); dscg.setInitialData(&id); dscg.getOptions() |= LipzGradDiscarder<double>::Options::CHECK_GRAD; dscg.getOptions() |= LipzGradDiscarder<double>::Options::CHECK_GRAD_COMP; dscg.getOptions() |= LipzGradDiscarder<double>::Options::DO_GRAD_BALL_CUT; dscg.getOptions() |= LipzGradDiscarder<double>::Options::DO_PRIMARY_BALL_CUT; dscg.getOptions() |= LipzGradDiscarder<double>::Options::DO_UNCONS_BALL_CUT; fact.setInitialData(&id); fact.addDiscarder(&dscg); fact.addDiscarder(&decomp); Solver solvertry(&fact); solvertry.setMST(1); solvertry.solve(); TQ tq = solvertry.getCandidateProblemsList(); if(tq.size() != 2) { BNB_ERROR_REPORT("wrong number of boxes (should be two)\n"); } Fact::Set s = tq.top(); double er = BNBABS(s.mA[0] - (-10.)); er += BNBABS(s.mA[1] - (-10.0)); er += BNBABS(s.mB[0] - 2.679550); er += BNBABS(s.mB[1] - 0.0); tq.pop(); s = tq.top(); er += BNBABS(s.mA[0] - (-10.)); er += BNBABS(s.mA[1] - (.0)); er += BNBABS(s.mB[0] - 2.679550); er += BNBABS(s.mB[1] - 10.0); tq.pop(); if(er > 0.001) { BNB_ERROR_REPORT("wrong box\n"); } Solver solver(&fact); // solver.setDebugOptions(Solver::Options::PRINT_RESULTING_STAT); solver.solve(); Fact::Solution sol = solver.getSolutionContainer()->top(); // printf("Sol val: %lf\n", sol.getValue()); if(sol.getValue() > eps) { BNB_ERROR_REPORT("wrong solution value\n"); } return 0; }