Skip to content

Commit

Permalink
Sync python notebook
Browse files Browse the repository at this point in the history
cmd: ./tools/generate_all_notebooks.sh
  • Loading branch information
Mizux committed Mar 10, 2023
1 parent de1b3cb commit 5425ded
Show file tree
Hide file tree
Showing 43 changed files with 2,168 additions and 1,649 deletions.
21 changes: 10 additions & 11 deletions examples/notebook/examples/appointments.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -162,14 +162,13 @@
" Each collection may be selected more than one time.\n",
"\n",
" Args:\n",
" item_collections: a list of item collections. Each item collection is a\n",
" list of integers [#item0, ..., #itemN-1], where #itemK is the number\n",
" of times item #K appears in the collection, and N is the number of\n",
" distinct items.\n",
" max_num_collections: an integer, the maximum number of item collections\n",
" that may be selected (counting repetitions of the same collection).\n",
" item_collections: a list of item collections. Each item collection is a list\n",
" of integers [#item0, ..., #itemN-1], where #itemK is the number of times\n",
" item #K appears in the collection, and N is the number of distinct items.\n",
" max_num_collections: an integer, the maximum number of item collections that\n",
" may be selected (counting repetitions of the same collection).\n",
" ideal_item_ratios: A list of N float which sums to 1.0: the K-th element is\n",
" the ideal ratio of item #K in the whole aggregated selection.\n",
" the ideal ratio of item #K in the whole aggregated selection.\n",
"\n",
" Returns:\n",
" A pair (objective value, list of pairs (item collection, num_selections)),\n",
Expand Down Expand Up @@ -246,10 +245,10 @@
" \"\"\"Computes the optimal schedule for the installation input.\n",
"\n",
" Args:\n",
" demand: a list of \"appointment types\". Each \"appointment type\" is\n",
" a triple (ideal_ratio_pct, name, duration_minutes), where\n",
" ideal_ratio_pct is the ideal percentage (in [0..100.0]) of that\n",
" type of appointment among all appointments scheduled.\n",
" demand: a list of \"appointment types\". Each \"appointment type\" is a triple\n",
" (ideal_ratio_pct, name, duration_minutes), where ideal_ratio_pct is the\n",
" ideal percentage (in [0..100.0]) of that type of appointment among all\n",
" appointments scheduled.\n",
"\n",
" Returns:\n",
" The same output type as EnumerateAllKnapsacksWithRepetition.\n",
Expand Down
79 changes: 41 additions & 38 deletions examples/notebook/examples/arc_flow_cutting_stock_sat.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -83,21 +83,25 @@
"metadata": {},
"outputs": [],
"source": [
"import argparse\n",
"import collections\n",
"import time\n",
"import numpy as np\n",
"\n",
"from ortools.linear_solver import pywraplp\n",
"from google.protobuf import text_format\n",
"from ortools.linear_solver.python import model_builder as mb\n",
"from ortools.sat.python import cp_model\n",
"\n",
"PARSER = argparse.ArgumentParser()\n",
"class FLAGS: pass\n",
"\n",
"_OUTPUT_PROTO = flags.DEFINE_string(\n",
" 'output_proto', '', 'Output file to write the cp_model proto to.')\n",
"_PARAMS = flags.DEFINE_string(\n",
" 'params',\n",
" 'num_search_workers:8,log_search_progress:true,max_time_in_seconds:10',\n",
" 'Sat solver parameters.')\n",
"_SOLVER = flags.DEFINE_string(\n",
" 'solver', 'sat', 'Method used to solve: sat, mip.')\n",
"\n",
"PARSER.add_argument(\n",
" '--solver', default='sat', help='Method used to solve: sat, mip.')\n",
"PARSER.add_argument(\n",
" '--output_proto_file',\n",
" default='',\n",
" help='Output file to write the cp_model proto to.')\n",
"\n",
"DESIRED_LENGTHS = [\n",
" 2490, 3980, 2490, 3980, 2391, 2391, 2391, 596, 596, 596, 2456, 2456, 3018,\n",
Expand Down Expand Up @@ -175,7 +179,7 @@
" return states, transitions\n",
"\n",
"\n",
"def solve_cutting_stock_with_arc_flow_and_sat(output_proto_file):\n",
"def solve_cutting_stock_with_arc_flow_and_sat(output_proto_file: str, params: str):\n",
" \"\"\"Solve the cutting stock with arc-flow and the CP-SAT solver.\"\"\"\n",
" items = regroup_and_count(DESIRED_LENGTHS)\n",
" print('Items:', items)\n",
Expand Down Expand Up @@ -243,16 +247,14 @@
"\n",
" # Output model proto to file.\n",
" if output_proto_file:\n",
" output_file = open(output_proto_file, 'w')\n",
" output_file.write(str(model.Proto()))\n",
" output_file.close()\n",
" model.ExportToFile(output_proto_file)\n",
"\n",
" # Solve model.\n",
" solver = cp_model.CpSolver()\n",
" if params:\n",
" text_format.Parse(params, solver.parameters)\n",
" solver.parameters.log_search_progress = True\n",
" solver.parameters.num_search_workers = 8\n",
" status = solver.Solve(model)\n",
" print(solver.ResponseStats())\n",
" solver.Solve(model)\n",
"\n",
"\n",
"def solve_cutting_stock_with_arc_flow_and_mip():\n",
Expand All @@ -273,17 +275,15 @@
" item_coeffs = collections.defaultdict(list)\n",
"\n",
" start_time = time.time()\n",
" solver = pywraplp.Solver.CreateSolver('cbc')\n",
" if not solver:\n",
" return\n",
" model = mb.ModelBuilder()\n",
"\n",
" objective_vars = []\n",
" objective_coeffs = []\n",
"\n",
" var_index = 0\n",
" for outgoing, incoming, item_index, card in transitions:\n",
" count = items[item_index][1]\n",
" count_var = solver.IntVar(\n",
" count_var = model.new_int_var(\n",
" 0, count, 'a%i_i%i_f%i_t%i_c%i' % (var_index, item_index, incoming,\n",
" outgoing, card))\n",
" var_index += 1\n",
Expand All @@ -295,7 +295,7 @@
" for state_index, state in enumerate(states):\n",
" if state_index == 0:\n",
" continue\n",
" exit_var = solver.IntVar(0, num_items, 'e%i' % state_index)\n",
" exit_var = model.new_int_var(0, num_items, 'e%i' % state_index)\n",
" outgoing_vars[state_index].append(exit_var)\n",
" incoming_sink_vars.append(exit_var)\n",
" price = price_usage(state, POSSIBLE_CAPACITIES)\n",
Expand All @@ -304,44 +304,47 @@
"\n",
" # Flow conservation\n",
" for state_index in range(1, len(states)):\n",
" solver.Add(\n",
" sum(incoming_vars[state_index]) == sum(outgoing_vars[state_index]))\n",
" model.add(\n",
" mb.LinearExpr.sum(incoming_vars[state_index]) == mb.LinearExpr.sum(\n",
" outgoing_vars[state_index]))\n",
"\n",
" # Flow going out of the source must go in the sink\n",
" solver.Add(sum(outgoing_vars[0]) == sum(incoming_sink_vars))\n",
" model.add(\n",
" mb.LinearExpr.sum(outgoing_vars[0]) == mb.LinearExpr.sum(\n",
" incoming_sink_vars))\n",
"\n",
" # Items must be placed\n",
" for item_index, size_and_count in enumerate(items):\n",
" num_arcs = len(item_vars[item_index])\n",
" solver.Add(\n",
" sum(item_vars[item_index][i] * item_coeffs[item_index][i]\n",
" for i in range(num_arcs)) == size_and_count[1])\n",
" model.add(\n",
" mb.LinearExpr.sum([item_vars[item_index][i] * item_coeffs[item_index][i]\n",
" for i in range(num_arcs)]) == size_and_count[1])\n",
"\n",
" # Objective is the sum of waste\n",
" solver.Minimize(\n",
" sum(objective_vars[i] * objective_coeffs[i]\n",
" for i in range(len(objective_vars))))\n",
" solver.EnableOutput()\n",
" model.minimize(np.dot(objective_vars, objective_coeffs))\n",
"\n",
" status = solver.Solve()\n",
" solver = mb.ModelSolver('scip')\n",
" solver.enable_output(True)\n",
" status = solver.solve(model)\n",
"\n",
" ### Output the solution.\n",
" if status == pywraplp.Solver.OPTIMAL:\n",
" if status == mb.SolveStatus.OPTIMAL or status == mb.SolveStatus.FEASIBLE:\n",
" print('Objective value = %f found in %.2f s' %\n",
" (solver.Objective().Value(), time.time() - start_time))\n",
" (solver.objective_value, time.time() - start_time))\n",
" else:\n",
" print('No solution')\n",
"\n",
"\n",
"def main(args):\n",
"def main(_):\n",
" \"\"\"Main function\"\"\"\n",
" if args.solver == 'sat':\n",
" solve_cutting_stock_with_arc_flow_and_sat(args.output_proto_file)\n",
" if _SOLVER.value == 'sat':\n",
" solve_cutting_stock_with_arc_flow_and_sat(_OUTPUT_PROTO.value,\n",
" _PARAMS.value)\n",
" else: # 'mip'\n",
" solve_cutting_stock_with_arc_flow_and_mip()\n",
"\n",
"\n",
"main(PARSER.parse_args())\n",
"main()\n",
"\n"
]
}
Expand Down
164 changes: 0 additions & 164 deletions examples/notebook/examples/assignment2_sat.ipynb

This file was deleted.

Loading

0 comments on commit 5425ded

Please sign in to comment.