transport12.py
Go to the documentation of this file.
6 
7 from gams import *
8 import sys
9 
11  return '''
12  Sets
13  i canning plants / seattle, san-diego /
14  j markets / new-york, chicago, topeka / ;
15 
16  Parameters
17 
18  a(i) capacity of plant i in cases
19  / seattle 350
20  san-diego 600 /
21 
22  b(j) demand at market j in cases
23  / new-york 325
24  chicago 300
25  topeka 275 / ;
26 
27  Table d(i,j) distance in thousands of miles
28  new-york chicago topeka
29  seattle 2.5 1.7 1.8
30  san-diego 2.5 1.8 1.4 ;
31 
32  Scalar f freight in dollars per case per thousand miles /90/ ;
33  Scalar bmult demand multiplier /1/;
34 
35  Parameter c(i,j) transport cost in thousands of dollars per case ;
36 
37  c(i,j) = f * d(i,j) / 1000 ;
38 
39  Variables
40  x(i,j) shipment quantities in cases
41  z total transportation costs in thousands of dollars ;
42 
43  Positive Variable x ;
44 
45  Equations
46  cost define objective function
47  supply(i) observe supply limit at plant i
48  demand(j) satisfy demand at market j ;
49 
50  cost .. z =e= sum((i,j), c(i,j)*x(i,j)) ;
51 
52  supply(i) .. sum(j, x(i,j)) =l= a(i) ;
53 
54  demand(j) .. sum(i, x(i,j)) =g= bmult*b(j) ;
55 
56  Model transport /all/ ;
57 '''
58 
59 
60 # Needs to be called with an uninstantiated GAMSModelInstance
61 def guss_call(dict, mi, solve_statement, opt = None, mi_opt = None, output=None):
62  modifier_list = []
63 
64  if dict.dimension != 3:
65  raise GamsException("Dict needs to be 3-dimensional")
66 
67  scen_name = dict.first_record((" ", "scenario", " ")).key(0)
68  scen_symbol = dict.database[scen_name]
69 
70  for rec in dict:
71  if rec.key(1).lower() == "scenario":
72  continue
73  if rec.key(1).lower() == "param":
74  modifier_dim = dict.database[rec.key(2)].dimension - scen_symbol.dimension
75  if modifier_dim < 0:
76  raise GamsException("Dimension of " + rec.key(2) + " too small")
77  modifier_list.append((GamsModifier(mi.sync_db.add_parameter(rec.key(0), modifier_dim, "")), dict.database[rec.key(2)]))
78  elif (rec.key(1).lower() == "lower") or (rec.key(1).lower() == "upper") or (rec.key(1).lower() == "fixed"):
79  modifier_dim = dict.database[rec.key(2)].dimension - scen_symbol.dimension
80  if modifier_dim < 0:
81  raise GamsException("Dimension of " + rec.key(2) + " too small")
82  modifier_var = None
83  try:
84  modifier_var = dict.database[rec.key(0)]
85  except:
86  modifier_var = mi.sync_db.add_variable(rec.key(0), modifier_dim, VarType.Free, "")
87  if (rec.key(1).lower() == "lower"):
88  modifier_list.append((GamsModifier(modifier_var, UpdateAction.Lower, mi.sync_db.add_parameter(rec.key(2), modifier_dim, "")), dict.database[rec.key(2)]))
89  elif rec.key(1).lower() == "upper":
90  modifier_list.append((GamsModifier(modifier_var, UpdateAction.Upper, mi.sync_db.add_parameter(rec.key(2), modifier_dim, "")), dict.database[rec.key(2)]))
91  else: #fixed
92  modifier_list.append((GamsModifier(modifier_var, UpdateAction.Fixed, mi.sync_db.add_parameter(rec.key(2), modifier_dim, "")), dict.database[rec.key(2)]))
93  elif (rec.key(1).lower() == "level") or (rec.key(1).lower() == "marginal"):
94  # Check that parameter exists in GAMSDatabase, will throw an exception if not
95  x = dict.database[rec.key(2)]
96  else:
97  raise GamsException("Cannot handle UpdateAction " + rec.key(1))
98 
99  ml = []
100  for tup in modifier_list:
101  ml.append(tup[0])
102  mi.instantiate(solve_statement, ml, opt)
103 
104  out_list = []
105 
106  for s in scen_symbol:
107  for tup in modifier_list:
108  p = None
109  pscen = tup[1]
110 
111  if tup[0].data_symbol == None:
112  p = tup[0].gams_symbol
113  else:
114  p = tup[0].data_symbol
115 
116  # Implemented SymbolUpdateType=BaseCase
117  p.clear()
118 
119  rec = None
120  filter = [""]*pscen.dimension
121  for i in range(scen_symbol.dimension):
122  filter[i] = s.key(i)
123  for i in range (scen_symbol.dimension, pscen.dimension):
124  filter[i] = " "
125  try:
126  rec = pscen.first_record(filter)
127  except:
128  continue
129 
130  while True:
131  my_keys = []
132  for i in range(p.dimension):
133  my_keys.append(rec.key(scen_symbol.dimension+i))
134  p.add_record(my_keys).value = rec.value
135  if not rec.move_next():
136  break
137 
138  mi.solve(SymbolUpdateType.BaseCase, output, mi_opt)
139  if len(out_list) == 0:
140  for rec in dict:
141  if (rec.key(1).lower() == "level") or (rec.key(1).lower() == "marginal"):
142  out_list.append((mi.sync_db[rec.key(0)], dict.database[rec.key(2)], rec.key(1).lower()))
143 
144  for tup in out_list:
145  my_keys = [""]*(scen_symbol.dimension + len(tup[0].first_record().keys))
146  for i in range(scen_symbol.dimension):
147  my_keys[i] = s.key(i)
148 
149  if (tup[2] == "level") and (isinstance(tup[0],GamsVariable)):
150  for rec in tup[0]:
151  for i in range(len(rec.keys)):
152  my_keys[scen_symbol.dimension + i] = s.key(i)
153  tup[1].add_record(my_keys).value = rec.level
154  elif (tup[2] == "level") and (isinstance(tup[0], GamsEquation)):
155  for rec in tup[0]:
156  for i in range(len(rec.keys)):
157  my_keys[scen_symbol.dimension + i] = s.key(i)
158  tup[1].add_record(my_keys).value = rec.level
159  elif (tup[2] == "marginal") and (isinstance(tup[0], GamsVariable)):
160  for rec in tup[0]:
161  for i in range(len(rec.keys)):
162  my_keys[scen_symbol.dimension + i] = s.key(i)
163  tup[1].add_record(my_keys).value = rec.marginal
164  elif (tup[2] == "marginal") and (isinstance(tup[0], GamsEquation)):
165  for rec in tup[0]:
166  for i in range(len(rec.keys)):
167  my_keys[scen_symbol.dimension + i] = s.key(i)
168  tup[1].add_record(my_keys).value = rec.marginal
169 
170 
171 if __name__ == "__main__":
172  if len(sys.argv) > 1:
173  ws = GamsWorkspace(system_directory = sys.argv[1])
174  else:
175  ws = GamsWorkspace()
176 
177  cp = ws.add_checkpoint()
178 
179  # initialize a GAMSCheckpoint by running a GAMSJob
180  t12 = ws.add_job_from_string(get_model_text())
181  t12.run(checkpoint=cp)
182 
183  # create a GAMSModelInstance and solve it multiple times with different scalar bmult
184  mi = cp.add_modelinstance()
185 
186  bmultlist = [ 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3 ]
187 
188  db = ws.add_database()
189 
190  scen = db.add_set("scen", 1, "")
191  bmult = db.add_parameter_dc("bmultlist", [scen])
192  zscen = db.add_parameter_dc("zscen", [scen])
193 
194  i = 0
195  for b in bmultlist:
196  bmult.add_record("s" + str(i)).value = b
197  scen.add_record("s" + str(i))
198  i += 1
199 
200 
201  dict = db.add_set("dict",3,"")
202  dict.add_record((scen.name, "scenario", ""))
203  dict.add_record(("bmult", "param", bmult.name))
204  dict.add_record(("z", "level", zscen.name))
205 
206  guss_call(dict, mi, "transport use lp min z");
207 
208  for rec in db[zscen.name]:
209  print(rec.key(0) + " obj: " + str(rec.value))
210 
211  #*******************
212 
213  mi2 = cp.add_modelinstance()
214  db2 = ws.add_database()
215 
216  scen2 = db2.add_set("scen", 1, "")
217  zscen2 = db2.add_parameter_dc("zscen", [scen2])
218  xup = db2.add_parameter("xup", 3, "")
219 
220  for j in range(4):
221  for irec in t12.out_db["i"]:
222  for jrec in t12.out_db["j"]:
223  xup.add_record(("s" + str(j), irec.key(0), jrec.key(0))).value = j+1
224  scen2.add_record("s" + str(j))
225 
226  dict2 = db2.add_set("dict", 3, "")
227  dict2.add_record((scen2.name, "scenario", ""))
228  dict2.add_record(("x", "lower", xup.name))
229  dict2.add_record(("z", "level", zscen2.name))
230 
231  guss_call(dict2, mi2, "transport use lp min z", output=sys.stdout)
232 
233  for rec in db2[zscen2.name]:
234  print(rec.key(0) + " obj: " + str(rec.value))
235 
236 
def guss_call(dict, mi, solve_statement, opt=None, mi_opt=None, output=None)
Definition: transport12.py:61
def get_model_text()
Definition: transport12.py:10