int main (void) { IloEnv env; int retval = -1; try { // Create the model. IloModel model(env); IloCplex cplex(env); IloObjective obj(env); IloNumVarArray vars(env); IloRangeArray rngs(env); IloIntArray cone(env); createmodel(model, obj, vars, rngs, cone); // Extract model. cplex.extract(model); // Solve the problem. If we cannot find an _optimal_ solution then // there is no point in checking the KKT conditions and we throw an // exception. cplex.setParam(IloCplex::Param::Barrier::QCPConvergeTol, CONVTOL); if ( !cplex.solve() || cplex.getStatus() != IloAlgorithm::Optimal ) throw string("Failed to solve problem to optimality"); // Test the KKT conditions on the solution. if ( !checkkkt (cplex, obj, vars, rngs, cone, TESTTOL) ) { env.error() << "Testing of KKT conditions failed." << endl; } else { env.out() << "Solution status: " << cplex.getStatus() << endl; env.out() << "KKT conditions are satisfied." << endl; retval = 0; } env.end(); } catch (IloException &e) { cerr << "IloException: " << e << endl; if (env.getImpl()) env.end(); ::abort(); } catch (string& e) { cerr << e << endl; if (env.getImpl()) env.end(); ::abort(); } return retval; }
int main(int argc, char** argv) { IloEnv env; try { IloModel m(env); IloCplex cplex(env); IloObjective obj; IloNumVarArray vars(env); IloRangeArray rngs(env); const char* datadir = (argc >= 2) ? argv[1] : "../../../examples/data"; char *fname = new char[strlen(datadir) + 1 + strlen("noswot.mps") + 1]; sprintf(fname, "%s/noswot.mps", datadir); env.out() << "reading " << fname << endl; cplex.importModel(m, fname, obj, vars, rngs); delete[] fname; env.out() << "extracting model ..." << endl; cplex.extract(m); IloRangeArray cuts(env); makeCuts(cuts, vars); // Use addUserCuts when the added constraints strengthen the // formulation. Use addLazyConstraints when the added constraints // remove part of the feasible region. Use addCuts when you are // not certain. cplex.addUserCuts(cuts); cuts.endElements(); cuts.end(); cplex.setParam(IloCplex::Param::MIP::Interval, 1000); env.out() << "solving model ...\n"; cplex.solve(); env.out() << "solution status is " << cplex.getStatus() << endl; env.out() << "solution value is " << cplex.getObjValue() << endl; } catch (IloException& ex) { cerr << "Error: " << ex << endl; } env.end(); return 0; }
int main (int argc, char **argv) { IloEnv env; try { IloCplex cplex(env); IloTimer timer(env); const IloNum startTime = cplex.getCplexTime(); parseCommandLine(argc, argv); printCommandLine(argc, argv); // set all default constraint weights as zero consWts["NonOperatorsAtMostOnce"] = 0; consWts["StackDepthUpperBound"] = 0; consWts["ExactlyOneUnknown"] = 0; consWts["NoTwoConsecutiveMultiplications"] = 0; // note: this may be disabled if word "dozen" appears consWts["NoTwoConsecutiveDivisions"] = 0; consWts["NoConsecutiveMultAndDiv"] = 0; consWts["NoNegatives"] = 0; consWts["TypeConsistency"] = 0; consWts["EqualityFirstOrLast"] = 0; consWts["IntConstantsImplyIntUnknown"] = 0; consWts["PreserveOrderingInText"] = 0; consWts["UnknownFirstOrLast"] = 0; consWts["EqualityNextToUnknown"] = 0; consWts["HasAddition"] = 0; consWts["HasSubtraction"] = 0; consWts["HasMultiplication"] = 0; consWts["HasDivision"] = 0; // parse config file defining constraint weights parseConfigFile(param_wts_config_file); cout << "Starting IloTimer" << endl; timer.start(); // parse arithmetic model parameters; note: this may override previously // set constraint weights if (strlen(arith_filename) > 0) parseInputFile(arith_filename); // set cplex paramters setCplexParameters(cplex); // import or build the model IloModel model(env); IloObjective obj(env); IloNumVarArray corevars(env); IloRangeArray rngs(env); if (strlen(mip_filename) > 0) { cout << "------- Importing the model -------" << endl; cplex.importModel(model, mip_filename, obj, corevars, rngs); cout << "Model imported at " << (cplex.getCplexTime() - startTime) << " sec" << endl; } else { cout << "------- Building the model -------" << endl; buildArithmeticModel(model, obj, corevars, rngs); } int nvars = corevars.getSize(); cout << "Number of Core Variables: " << nvars << endl; cplex.extract(model); cout << "Model extracted at " << (cplex.getCplexTime() - startTime) << " sec" << endl; // save the MIP model to a file, if desired if (!param_savemodel.empty()) { cout << endl << "Saving generated MIP model to " << param_savemodel << endl << endl; cplex.exportModel(param_savemodel.c_str()); } // find out whether it is a minimization problem or a maximization one bool isMinimization = true; if (cplex.getObjective().getSense() == IloObjective::Maximize) isMinimization = false; // ask cplex to use MIPInfoCallback cplex.use(MIPInfoCallback(env, isMinimization, cplex, startTime)); cout << "------- Solving the extracted model -------" << endl; //const bool solutionFound = cplex.solve(); const bool solutionFound = (param_nsolutions > 1 ? cplex.populate() : cplex.solve()); const int nSolutionsFound = cplex.getSolnPoolNsolns(); cout << "Stopping IloTimer" << endl; timer.stop(); const IloNum endTime = cplex.getCplexTime(); cout << "-------------------------------------------" << endl; printCommandLine(argc, argv); cout << "-------------------------------------------" << endl; cout << "Number of cplex nodes = " << cplex.getNnodes() << endl; cout << "Number of cplex iterations = " << cplex.getNiterations() << endl; cout << "Aggregated CPU time = " << timer.getTime() << " seconds" << endl; cout << "Elapsed wall clock time = " << endTime - startTime << " seconds" << endl; cout << "Number of threads used = " << param_threads << endl; cout << "Solution status = " << cplex.getStatus() << endl; if (solutionFound) { cout << "Solution value = " << cplex.getObjValue() << endl; cout << "Optimality Gap (in %) = " << fabs((cplex.getBestObjValue() - cplex.getObjValue()) / (1.0 * cplex.getObjValue())) * 100 << endl; //cout << "Maximum bound violation = " << cplex.getQuality(IloCplex::MaxPrimalInfeas) << endl; } cout << endl << "parameters: n=" << n << " l=" << l << " k=" << k << " p=" << p << " q=" << q << " m=" << m << endl; if (solutionFound) { cout << "TOTAL " << nSolutionsFound << " solutions found" << endl; int nAllowedSolutionsFound = 0; if (param_printexpr || param_printanswer || param_printsoln) { IloNumArray objValues(env, nSolutionsFound); vector<pair<IloNum,unsigned> > sortedIndex(nSolutionsFound); // to sort solutions by objective value vector<FormattedExpr> expressions(nSolutionsFound); // extract all solutions as formatted expressions for (int s=0; s<nSolutionsFound; s++) { IloNumArray vals(env); cplex.getValues(vals, corevars, s); // convert solution values to integers; note: simple int cast may lead to errors! IloIntArray intvals(env, vals.getSize()); for (int i=0; i<vals.getSize(); i++) intvals[i] = IloRound(vals[i]); // use IloRound rather than std::round if (param_printsoln) prettyPrintSoln(intvals); objValues[s] = cplex.getObjValue(s); expressions[s] = getFormattedExpr(intvals); sortedIndex[s] = pair<IloNum,unsigned> (objValues[s],s); } // sort solutions by increasing objective value std::stable_sort(sortedIndex.begin(), sortedIndex.end()); // identify which expressions are unique (ignoring type differences); // prefer to keep those that appear earlier in the above sorted order set<int> uniqueExprIndices; set<string> seenExpressions; if (!param_allowdupes) { for (int s=0; s<nSolutionsFound; s++) { const int sId = sortedIndex[s].second; const string & exprPf = expressions[sId].postfix; if (seenExpressions.find(exprPf) == seenExpressions.end()) { uniqueExprIndices.insert(sId); seenExpressions.insert(exprPf); } } } // evaluate all expressions with a single call to Python's SymPy package if (param_printanswer) solveExpressionsWithSymPy(expressions); // print expressions if desired, in sorted order if (param_printexpr) { cout << "SOLN: CORRECT | POS/NEG | INT/FRA | OBJ-SCORE | TRUE-ANS | ANS | INFIX | POSTFIX | TYPED-POSTFIX" << endl; for (int s=0; s<nSolutionsFound; s++) { const int sId = sortedIndex[s].second; if (!param_allowdupes && uniqueExprIndices.find(sId) == uniqueExprIndices.end()) continue; const FormattedExpr & expr = expressions[sId]; const double answerValue = atof(expr.answer.c_str()); const bool isCorrect = (fabs(answerValue - trueAnswer) < epsilon); const bool isAnswerNegative = answerValue < 0; const bool isAnswerInteger = isInt(answerValue); if (!isAnswerNegative && (!allIntConstants || consWts["IntConstantsImplyIntUnknown"] == 0 || isAnswerInteger)) { ++nAllowedSolutionsFound; cout << "EXPR: " << isCorrect << " | " << (isAnswerNegative ? "NEG" : "POS") << " | " << (isAnswerInteger ? "INT" : "FRA") << " | " << objValues[sId] << " | " << trueAnswer << " | " << expr.answer << " | " << expr.infix << " | " << expr.postfix << " | " << expr.typedPostfix << endl; } } } } const string solnProperty = (param_allowdupes ? "" : " unique,") + string(" non-negative") + (allIntConstants && consWts["IntConstantsImplyIntUnknown"] != 0 ? ", integer-valued " : " "); cout << "NET " << nAllowedSolutionsFound << solnProperty << "solutions found out of " << nSolutionsFound << " total solutions" << endl; } cout << "-------------------------------------------" << endl; cout << "RESULT:" << " NODES " << cplex.getNnodes() << " | ITERATIONS " << cplex.getNiterations() << " | CPUTIME " << timer.getTime() << " | WALLTIME " << endTime - startTime << " | THREADS " << param_threads << " | STATUS " << cplex.getStatus(); if (solutionFound) cout << " | SOLUTION " << cplex.getObjValue() << " | OPTGAP " << fabs((cplex.getBestObjValue() - cplex.getObjValue()) / (1.0 * cplex.getObjValue())) * 100; else cout << " | SOLUTION - | OPTGAP -"; cout << endl; //try { // basis may not exist // IloCplex::BasisStatusArray cstat(env); // cplex.getBasisStatuses(cstat, vars); // cout << "Basis statuses = " << cstat << endl; //} //catch (...) { //} } catch (IloException& e) { cerr << "Concert exception caught: " << e << endl; } catch (...) { cerr << "Unknown exception caught" << endl; } env.end(); return 0; } // END main
void iterate(const options_t& options, std::vector<uint32_t>& img) { int world_rank; int world_size; MPI_Comm_rank(MPI_COMM_WORLD, &world_rank); MPI_Comm_size(MPI_COMM_WORLD, &world_size); const int threads = omp_get_max_threads(); const size_t image_size = options.width * options.height; const size_t rs = options.run_size; const Floating rl = options.map_rlow; const Floating rh = options.map_rhigh; const Floating il = options.map_ilow; const Floating ih = options.map_ihigh; const Floating rL = options.rand_rlow; const Floating rH = options.rand_rhigh; const Floating iL = options.rand_ilow; const Floating iH = options.rand_ihigh; if(world_rank == 0) img.resize(image_size); std::vector<uint32_t> tmp(image_size); std::vector<Floating> points(4*threads*rs); std::vector<Integer> escape( threads*rs); std::vector<size_t> idx( threads*rs); std::vector<xorshift1024_t> rngs(threads); for(auto& rng : rngs) seed_xorshift1024_urandom(&rng); uint64_t orbits_written=0, points_written=0, blocks_written=0; double start_time = MPI_Wtime(); if(world_rank == 0) print_info(options, 0.0, 0, 0, 0, std::numeric_limits<double>::infinity()); while(1) { if(world_rank != 0) { orbits_written = 0; points_written = 0; std::memset(tmp.data(), 0, tmp.size()*sizeof(uint32_t)); } #pragma omp parallel for for(size_t i = 0; i < options.block_size; ++i) { int thread_num = omp_get_thread_num(); Floating *cr = points.data() + rs*(thread_num + 0); Floating *ci = points.data() + rs*(thread_num + 4); Floating *tr = points.data() + rs*(thread_num + 8); Floating *ti = points.data() + rs*(thread_num + 12); Integer *im = escape.data() + rs* thread_num; size_t *ix = idx.data() + rs* thread_num; fill_uniform1024(cr, rs, rL, rH, &rngs[thread_num]); fill_uniform1024(ci, rs, iL, iH, &rngs[thread_num]); std::iota(ix, ix+rs, 0); bulb_test(cr, ci, im, rs); const size_t* bulb = std::partition(ix, ix+rs, [im](size_t x) { return im[x] == 0; }); const size_t bulb_size = bulb - ix; const size_t bulb_block = reduce_align<Floating>(bulb_size); for(size_t j = 0; j < bulb_block; ++j) { tr[j] = cr[ix[j]]; ti[j] = ci[ix[j]]; } std::iota(ix, ix+bulb_block, 0); escape_test(tr, ti, im, bulb_block, options.iter_low, options.radius); const size_t* low = std::partition(ix, ix+bulb_block, [im, &options](size_t a) { return im[a] == options.iter_low; }); const size_t low_size = low - ix; const size_t low_block = reduce_align<Floating>(low_size); for(size_t j = 0; j < low_block; ++j) { cr[j] = tr[ix[j]]; ci[j] = ti[ix[j]]; } std::iota(ix, ix+low_block, 0); escape_test(cr, ci, im, low_block, options.iter_high+1, options.radius); size_t* high = std::partition(ix, ix+low_block, [im, &options](size_t a) { return im[a] <= options.iter_high; }); const size_t high_size = high - ix; const size_t high_block = reduce_align<Floating>(high_size); for(size_t j = 0; j < high_block; ++j) { tr[j] = cr[ix[j]]; ti[j] = ci[ix[j]]; } size_t t = write_orbits(tr, ti, high_block, options.iter_high, rl, rh, il, ih, tmp.data(), options.width, options.height); #pragma omp atomic points_written += t; #pragma omp atomic orbits_written += high_block; } double error; MPI_Allreduce(&orbits_written, &orbits_written, 1, MPI_UINT64_T, MPI_SUM, MPI_COMM_WORLD); MPI_Allreduce(&points_written, &points_written, 1, MPI_UINT64_T, MPI_SUM, MPI_COMM_WORLD); if(world_rank == 0) { MPI_Reduce(MPI_IN_PLACE, tmp.data(), image_size, MPI_UINT32_T, MPI_SUM, 0, MPI_COMM_WORLD); double sum = 0; #pragma omp parallel for reduction(+:sum) for(size_t i = 0; i < image_size; ++i) { sum += std::abs(double(tmp[i] - img[i]))/(1+tmp[i]); } std::memcpy(img.data(), tmp.data(), image_size*sizeof(uint32_t)); error = (double)sum/image_size; double current_time = MPI_Wtime(); print_info(options, current_time-start_time, blocks_written+1, orbits_written, points_written, error); } else { MPI_Reduce(tmp.data(), tmp.data(), image_size, MPI_UINT32_T, MPI_SUM, 0, MPI_COMM_WORLD); } ++blocks_written; if(options.use_max && blocks_written >= options.max_blocks) { break; } if(options.use_orb && orbits_written >= options.max_orbits) { break; } if(options.use_err) { MPI_Bcast(&error, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD); if(error < options.error) break; } } }