Skip to content

Instantly share code, notes, and snippets.

@nariaki3551
Last active October 17, 2022 03:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nariaki3551/b70d9c7eb7fef7d4b380a77315fffb0d to your computer and use it in GitHub Desktop.
Save nariaki3551/b70d9c7eb7fef7d4b380a77315fffb0d to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "c255afa5",
"metadata": {},
"outputs": [],
"source": [
"\"\"\"\n",
"Codable Opt Search plugin for flopt with version 0.5.5\n",
"\"\"\"\n",
"\n",
"import codableopt\n",
"\n",
"from flopt.solvers.base import BaseSearch\n",
"from flopt.solution import Solution\n",
"from flopt.constants import VariableType, ExpressionType, ConstraintType, SolverTerminateState\n",
"from flopt.utils import Value\n",
"\n",
"from flopt.env import setup_logger\n",
"\n",
"logger = setup_logger(__name__)\n",
"\n",
"\n",
"class SelfReturn:\n",
" def __init__(self, obj):\n",
" self.obj = obj\n",
" self.name = obj.name\n",
"\n",
" def value(self):\n",
" \"\"\"for creating the objective and constraints of pulp\"\"\"\n",
" return self.obj\n",
"\n",
" \n",
"class CodableOptSearch(BaseSearch):\n",
" \"\"\"Codable Model Optimizer Solver API\n",
"\n",
" Attributes\n",
" -------------\n",
" solver : codableopt.solver.opt_solver.OptSolver\n",
" method : codableopt.solver.optimizer.method\n",
" \"\"\"\n",
"\n",
" name = \"CodableOptSearch\"\n",
" can_solve_problems = {\n",
" \"Variable\": VariableType.Number,\n",
" \"Objective\": ExpressionType.Any,\n",
" \"Constraint\": ExpressionType.Linear,\n",
" }\n",
" # conver VarElement -> SystemVariable\n",
" co_variable_class = {\n",
" VariableType.Continuous: codableopt.DoubleVariable,\n",
" VariableType.Integer: codableopt.IntVariable,\n",
" VariableType.Binary: codableopt.IntVariable,\n",
" }\n",
"\n",
" def __init__(self):\n",
" super().__init__()\n",
" self.solver = None\n",
" self.method = None\n",
"\n",
"\n",
" def search(self, solution, objective, constraints):\n",
"\n",
" # create problem\n",
" co_prob = self.createCodableOptProblem(solution, objective, constraints)\n",
"\n",
" # set solver and method\n",
" if self.solver is None:\n",
" self.solver = codableopt.OptSolver() \n",
" if self.method is None:\n",
" self.method = codableopt.PenaltyAdjustmentMethod(steps=40000) # set default value\n",
" \n",
" # solve\n",
" answer, is_feasible = self.solver.solve(co_prob, self.method)\n",
"\n",
" # return status\n",
" if is_feasible:\n",
" return SolverTerminateState.Normal\n",
" else:\n",
" return SolverTerminateState.Infeasible\n",
"\n",
"\n",
" def createCodableOptProblem(self, solution, objective, constraints):\n",
" \"\"\"Convert Problem into codableopt.Problem\n",
"\n",
" Parameters\n",
" ----------\n",
" solution : Solution\n",
" objective : Expression\n",
" objective object\n",
" constraints : list of Constraint\n",
" list of constriants objects\n",
"\n",
" Returns\n",
" -------\n",
" codableopt.Problem\n",
" \"\"\"\n",
" co_variables = []\n",
" for var in solution:\n",
" if var.type() in self.co_variable_class:\n",
" cls = self.co_variable_class[var.type()]\n",
" else:\n",
" raise ValueError(var.type())\n",
" co_variables.append(cls(var.name, var.lowBound, var.upBound))\n",
"\n",
" # conver Problem -> codableopt.Problem\n",
" is_max_problem = ( prob.sense in {\"maximize\", \"Maximize\"} )\n",
" co_prob = codableopt.Problem(is_max_problem=is_max_problem)\n",
" \n",
" # set objective\n",
" def obj(variables):\n",
" solution.setValuesFromArray(variables)\n",
" \n",
" # calculate objective value\n",
" obj_value = objective.value(solution)\n",
" \n",
" # update best solution\n",
" self.registerSolution(solution, obj_value)\n",
"\n",
" # execute callbacks\n",
" self.callback([solution])\n",
"\n",
" # check time limit\n",
" self.raiseTimeoutIfNeeded()\n",
" \n",
" return obj_value\n",
" \n",
" co_prob += codableopt.Objective(objective=obj, args_map={\"variables\": co_variables})\n",
"\n",
" # add constraints\n",
" co_solution = Solution(\"co_solution\", [SelfReturn(var) for var in co_variables])\n",
" for const in constraints:\n",
" const_exp = const.expression\n",
" if const.type == ConstraintType.Eq:\n",
" co_prob += const_exp.value(co_solution) == 0\n",
" else: # const.type == ConstraintType.Le\n",
" co_prob += const_exp.value(co_solution) <= 0\n",
"\n",
" return co_prob"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5a937200",
"metadata": {},
"outputs": [],
"source": [
"from flopt import Variable, Problem, Solver\n",
"\n",
"# Variables\n",
"a = Variable('a', lowBound=0, upBound=1, cat='Continuous')\n",
"b = Variable('b', lowBound=1, upBound=2, cat='Continuous')\n",
"c = Variable('c', upBound=3, cat='Continuous')\n",
"\n",
"# Problem\n",
"prob = Problem()\n",
"prob += 2 * (3 * a+b) - c + 3 # set the objective function\n",
"prob += a + b + c <= 3 # set the constraint\n",
"\n",
"# Solver\n",
"solver = CodableOptSearch()\n",
"solver.setParams() # setting of the hyper parameters\n",
"prob.solve(solver, msg=True) # run solver to solve the problem\n",
"\n",
"# display the result, incumbent solution\n",
"print('obj value', prob.getObjectiveValue())\n",
"print('a', a.value())\n",
"print('b', b.value())\n",
"print('c', c.value())"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1d0bcb74",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.5"
},
"toc": {
"base_numbering": 1,
"nav_menu": {},
"number_sections": true,
"sideBar": true,
"skip_h1_title": false,
"title_cell": "Table of Contents",
"title_sidebar": "Contents",
"toc_cell": false,
"toc_position": {},
"toc_section_display": true,
"toc_window_display": false
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment