Loading...
Searching...
No Matches
transport10.py
Go to the documentation of this file.
6
7import os
8import sys
9from gams import GamsWorkspace
10from openpyxl import load_workbook
11
12GAMS_MODEL = """
13Set
14 i 'canning plants'
15 j 'markets';
16
17Parameter
18 a(i) 'capacity of plant i in cases'
19 b(j) 'demand at market j in cases'
20 d(i,j) 'distance in thousands of miles';
21
22Scalar f 'freight in dollars per case per thousand miles' / 90 /;
23
24$if not set gdxincname $abort 'no include file name for data file provided'
25$gdxIn %gdxincname%
26$load i j a b d
27$gdxIn
28
29Parameter c(i,j) 'transport cost in thousands of dollars per case';
30c(i,j) = f*d(i,j)/1000;
31
32Variable
33 x(i,j) 'shipment quantities in cases'
34 z 'total transportation costs in thousands of dollars';
35
36Positive Variable x;
37
38Equations
39 cost 'define objective function'
40 supply(i) 'observe supply limit at plant i'
41 demand(j) 'satisfy demand at market j';
42
43cost.. z =e= sum((i,j), c(i,j)*x(i,j));
44
45supply(i).. sum(j, x(i,j)) =l= a(i);
46
47demand(j).. sum(i, x(i,j)) =g= b(j);
48
49Model transport /all/;
50
51solve transport using lp minimizing z;
52
53display x.l, x.m;
54"""
55
56if __name__ == "__main__":
57 sys_dir = sys.argv[1] if len(sys.argv) > 1 else None
58 ws = GamsWorkspace(system_directory=sys_dir)
59
60 wb = load_workbook(
61 os.path.join(*[os.pardir] * 4, "apifiles", "Data", "transport.xlsx")
62 )
63 capacity = wb["capacity"]
64 demand = wb["demand"]
65 distance = wb["distance"]
66
67 # number of markets/plants have to be the same in all spreadsheets
68 if (
69 distance.max_column - 1 != demand.max_column
70 or distance.max_row - 1 != capacity.max_row
71 ):
72 raise Exception("Size of the spreadsheets doesn't match")
73
74 db = ws.add_database()
75 i = db.add_set("i", 1, "Plants")
76 j = db.add_set("j", 1, "Markets")
77 capacity_param = db.add_parameter_dc("a", [i], "Capacity")
78 demand_param = db.add_parameter_dc("b", [j], "Demand")
79 distance_param = db.add_parameter_dc("d", [i, j], "Distance")
80
81 for c in capacity.iter_cols():
82 key = c[0].value
83 i.add_record(key)
84 capacity_param.add_record(key).value = c[1].value
85
86 for c in demand.iter_cols():
87 key = c[0].value
88 j.add_record(key)
89 demand_param.add_record(key).value = c[1].value
90
91 for c in range(2, distance.max_column + 1):
92 for r in range(2, distance.max_row + 1):
93 keys = (
94 distance.cell(row=r, column=1).value,
95 distance.cell(row=1, column=c).value,
96 )
97 v = distance.cell(row=r, column=c).value
98 distance_param.add_record(keys).value = v
99
100 # create and run the GamsJob
101 job = ws.add_job_from_string(GAMS_MODEL)
102 opt = ws.add_options()
103 opt.defines["gdxincname"] = db.name
104 opt.all_model_types = "xpress"
105 job.run(opt, databases=db)
106 for rec in job.out_db["x"]:
107 print(
108 f"x({rec.key(0)},{rec.key(1)}): level={rec.level} marginal={rec.marginal}"
109 )
load_workbook demand
Definition: transport10.py:64