Debian Codegraph @

doc/source/guides/how_to_export_models.rst

raw
1 How to import and export models in PuLP
2 ==========================================
3
4 Exporting a model can be useful when the building time takes too long or when the model needs to be passed to another computer to solve. Or any other reason.
5 PuLP offers two ways to export a model: to an mps file or to a dictionary /json file. Each offers advantages over the other.
6
7 **The mps format** is an industry standard. But it is not very flexible so some information cannot be stored. It stores only variables and constraints. It does not store the values of variables.
8
9 **The dictionary/ json format** is made to fit how pulp stores the information and so it does not lose information: this format file saves enough data to be able to restore a complete pulp model on reading it.
10
11 The interface to import and export for both formats is similar as can be seen in the Example 1 below.
12
13 Considerations
14 ------------------
15
16 The following considerations need to be taken into account:
17
18 #. Variable names need to be unique. PuLP permits having variable names because it uses an internal code for each one. But we do not export that code. So we identify variables by their name only.
19 #. Variables are not exported in a grouped way. This means that if you have several `dictionaries of many variables each` you will end up with a very long list of variables. This can be seen in the Example 2.
20 #. Output information is also written to the json format. This means that the status, solution status, the values of variables and shadow prices / reduced costs are exported too. This means that it is possible to export a model that has been solved and then read it again only to see the values of the variables.
21 #. For json, we use the base `json` package. But if `ujson` is available, we use that so the import / export can be really fast.
22
23 Example 1: json
24 ----------------
25
26 A very simple example taken from the internal tests. Imagine the following problem::
27
28 from pulp import *
29
30 prob = LpProblem("test_export_dict_MIP", LpMinimize)
31 x = LpVariable("x", 0, 4)
32 y = LpVariable("y", -1, 1)
33 z = LpVariable("z", 0, None, LpInteger)
34 prob += x + 4 * y + 9 * z, "obj"
35 prob += x + y <= 5, "c1"
36 prob += x + z >= 10, "c2"
37 prob += -y + z == 7.5, "c3"
38
39 We can now export the problem into a dictionary::
40
41 data = prob.to_dict()
42
43 We now have a dictionary with a lot of data::
44
45 {'constraints': [{'coefficients': [{'name': 'x', 'value': 1},
46 {'name': 'y', 'value': 1}],
47 'constant': -5,
48 'name': 'c1',
49 'pi': None,
50 'sense': -1},
51 {'coefficients': [{'name': 'x', 'value': 1},
52 {'name': 'z', 'value': 1}],
53 'constant': -10,
54 'name': 'c2',
55 'pi': None,
56 'sense': 1},
57 {'coefficients': [{'name': 'y', 'value': -1},
58 {'name': 'z', 'value': 1}],
59 'constant': -7.5,
60 'name': 'c3',
61 'pi': None,
62 'sense': 0}],
63 'objective': {'coefficients': [{'name': 'x', 'value': 1},
64 {'name': 'y', 'value': 4},
65 {'name': 'z', 'value': 9}],
66 'name': 'obj'},
67 'parameters': {'name': 'test_export_dict_MIP',
68 'sense': 1,
69 'sol_status': 0,
70 'status': 0},
71 'sos1': {},
72 'sos2': {},
73 'variables': [{'cat': 'Continuous',
74 'dj': None,
75 'lowBound': 0,
76 'name': 'x',
77 'upBound': 4,
78 'varValue': None},
79 {'cat': 'Continuous',
80 'dj': None,
81 'lowBound': -1,
82 'name': 'y',
83 'upBound': 1,
84 'varValue': None},
85 {'cat': 'Integer',
86 'dj': None,
87 'lowBound': 0,
88 'name': 'z',
89 'upBound': None,
90 'varValue': None}]}
91
92 We can now import this dictionary::
93
94 var1, prob1 = LpProblem.from_dict(data)
95 var1
96 # {'x': x, 'y': y, 'z': z}
97 prob1
98 # test_export_dict_MIP:
99 # MINIMIZE
100 # 1*x + 4*y + 9*z + 0
101 # SUBJECT TO
102 # c1: x + y <= 5
103 # c2: x + z >= 10
104 # c3: - y + z = 7.5
105 # VARIABLES
106 # x <= 4 Continuous
107 # -1 <= y <= 1 Continuous
108 # 0 <= z Integer
109
110 As you can see we get a tuple with size 2 with: (1) a variables dictionary and (2) a PuLP model object. We can now solve that problem::
111
112 prob1.solve()
113
114 And the result will be available in our *new* variables::
115
116 var1['x'].value()
117 # 3.0
118
119
120 Example 1: mps
121 ----------------
122
123 The same model::
124
125 from pulp import *
126 prob = LpProblem("test_export_dict_MIP", LpMinimize)
127 x = LpVariable("x", 0, 4)
128 y = LpVariable("y", -1, 1)
129 z = LpVariable("z", 0, None, LpInteger)
130 prob += x + 4 * y + 9 * z, "obj"
131 prob += x + y <= 5, "c1"
132 prob += x + z >= 10, "c2"
133 prob += -y + z == 7.5, "c3"
134
135 We can now export the problem into an mps file::
136
137 prob.writeMPS("test.mps")
138
139 We can now import this file::
140
141 var1, prob1 = LpProblem.fromMPS("test.mps")
142 var1
143 # {'x': x, 'y': y, 'z': z}
144 prob1
145 # test_export_dict_MIP:
146 # MINIMIZE
147 # 1*x + 4*y + 9*z + 0
148 # SUBJECT TO
149 # c1: x + y <= 5
150 # c2: x + z >= 10
151 # c3: - y + z = 7.5
152 # VARIABLES
153 # x <= 4 Continuous
154 # -1 <= y <= 1 Continuous
155 # 0 <= z Integer
156
157 The resulting tuple is exactly the same format as the previous one.
158
159 Example 2: json
160 ------------------
161
162 We will use as example the model in :ref:`set-partitioning-problem`::
163
164 import pulp
165
166 max_tables = 5
167 max_table_size = 4
168 guests = 'A B C D E F G I J K L M N O P Q R'.split()
169
170 def happiness(table):
171 """
172 Find the happiness of the table
173 - by calculating the maximum distance between the letters
174 """
175 return abs(ord(table[0]) - ord(table[-1]))
176
177 #create list of all possible tables
178 possible_tables = [tuple(c) for c in pulp.allcombinations(guests,
179 max_table_size)]
180
181 #create a binary variable to state that a table setting is used
182 x = pulp.LpVariable.dicts('table', possible_tables,
183 lowBound = 0,
184 upBound = 1,
185 cat = pulp.LpInteger)
186
187 seating_model = pulp.LpProblem("Wedding_Seating_Model", pulp.LpMinimize)
188
189 seating_model += pulp.lpSum([happiness(table) * x[table] for table in possible_tables])
190
191 #specify the maximum number of tables
192 seating_model += pulp.lpSum([x[table] for table in possible_tables]) <= max_tables, \
193 "Maximum_number_of_tables"
194
195 #A guest must seated at one and only one table
196 for guest in guests:
197 seating_model += pulp.lpSum([x[table] for table in possible_tables
198 if guest in table]) == 1, "Must_seat_%s"%guest
199
200 We *could* directly solve the model doing::
201
202 seating_model.solve()
203
204 Instead, we are going to export it to a json file::
205
206 seating_model.to_json("seating_model.json")
207
208 And re-import it::
209
210 wedding_vars, wedding_model = LpProblem.from_json("seating_model.json")
211
212 We inspect the variables::
213
214 wedding_vars
215 {"table_('A',)": table_('A',), "table_('A',_'B')": table_('A',_'B'), "table_('A',_'B',_'C')": table_('A',_'B',_'C'), "table_('A',_'B',_'C',_'D')": table_('A',_'B',_'C',_'D'), "table_('A',_'B',_'C',_'E')": table_('A',_'B',_'C',_'E'), ...}
216
217 As can be seen, it is no longer a dictionary indexed by the original tuples. Unfortunately, it has become a flat dictionary with concatenated names.
218
219 We can still solve the model, though::
220
221 wedding_model.solve()
222
223 And inspect some of the values::
224
225 wedding_vars["table_('M',_'N')"].value()
226 # 1.0
227
228
229 Grouping variables
230 ------------------------------------
231
232 As the "Considerations" section mentions, the grouping of variables is not restored automatically. Nevertheless, by using some strict naming convention on variable names and clever parsing, one can reconstruct the original structure of the variables.
233
234 Caveats with json and pandas / numpy data types
235 --------------------------------------------------
236
237 The `json` module in python has some issues transforming numpy data types (e.g., `np.integer`). The easier way to solve this problem is to provide a custom encoding class as shown `here <https://stackoverflow.com/a/57915246/6508131>`_::
238
239 import numpy as np
240 #(...)
241 class NpEncoder(json.JSONEncoder):
242 def default(self, obj):
243 if isinstance(obj, np.integer):
244 return int(obj)
245 elif isinstance(obj, np.floating):
246 return float(obj)
247 elif isinstance(obj, np.ndarray):
248 return obj.tolist()
249 else:
250 return super(NpEncoder, self).default(obj)
251
252 wedding_model.to_json("seating_model.json", cls=NpEncoder)
253
254 Note that this custom encoding class may not work with the `ujson` package. An alternative is to cast all values using `int()` or `float()` before using them in `pulp`.