Loading...
Searching...
No Matches
transport_gdx.py
Go to the documentation of this file.
8
9import os
10import subprocess
11import sys
12from gams import GamsWorkspace
13
14if __name__ == "__main__":
15 sys_dir = sys.argv[1] if len(sys.argv) > 1 else None
16 ws = GamsWorkspace(system_directory=sys_dir)
17
18 # Python lists and dictionaries holding the data
19 plants = ["Seattle", "San-Diego"]
20 markets = ["New-York", "Chicago", "Topeka"]
21 capacity = {"Seattle": 350.0, "San-Diego": 600.0}
22 demand = {"New-York": 325.0, "Chicago": 300.0, "Topeka": 275.0}
23 distance = {
24 ("Seattle", "New-York"): 2.5,
25 ("Seattle", "Chicago"): 1.7,
26 ("Seattle", "Topeka"): 1.8,
27 ("San-Diego", "New-York"): 2.5,
28 ("San-Diego", "Chicago"): 1.8,
29 ("San-Diego", "Topeka"): 1.4,
30 }
31
32 # create new GamsDatabase instance
33 db = ws.add_database()
34
35 # add 1-dimensional set 'i' with explanatory text 'canning plants' to the GamsDatabase
36 i = db.add_set("i", 1, "canning plants")
37 for p in plants:
38 i.add_record(p)
39
40 # add 1-dimensional set 'j' with explanatory text 'markets' to the GamsDatabase
41 j = db.add_set("j", 1, "markets")
42 for m in markets:
43 j.add_record(m)
44
45 # add parameter 'a' with domain 'i'
46 a = db.add_parameter_dc("a", [i], "capacity of plant i in cases")
47 for p in plants:
48 a.add_record(p).value = capacity[p]
49
50 # add parameter 'b' with domain 'j'
51 b = db.add_parameter_dc("b", [j], "demand at market j in cases")
52 for m in markets:
53 b.add_record(m).value = demand[m]
54
55 # add parameter 'd' with domains 'i' and 'j'
56 d = db.add_parameter_dc("d", [i, j], "distance in thousands of miles")
57 for k, v in iter(distance.items()):
58 d.add_record(k).value = v
59
60 # add scalar 'f'
61 f = db.add_parameter("f", 0, "freight in dollars per case per thousand miles")
62 f.add_record().value = 90
63
64 # export the GamsDatabase to a GDX file with name 'data.gdx' located in the 'working_directory' of the GamsWorkspace
65 db.export("data.gdx")
66
67 print("Content of GDX file 'data.gdx':")
68 subprocess.call(["gdxdump", os.path.join(ws.working_directory, "data.gdx")])
69
70 # add a new GamsDatabase and initialize it from the GDX file just created
71 db2 = ws.add_database_from_gdx("data.gdx")
72
73 # read data from symbols into Python data structures
74 i = [rec.keys[0] for rec in db2["i"]]
75 j = [rec.keys[0] for rec in db2["j"]]
76
77 a = {rec.keys[0]: rec.value for rec in db2["a"]}
78 b = {rec.keys[0]: rec.value for rec in db2["b"]}
79 d = {tuple(rec.keys): rec.value for rec in db2["d"]}
80
81 f = db2["f"].first_record().value
82
83 print("i:")
84 for rec in i:
85 print(f" {rec}")
86 print("j:")
87 for rec in j:
88 print(f" {rec}")
89 print("a:")
90 for rec in a:
91 print(f" {rec} : {a[rec]}")
92 print("b:")
93 for rec in b:
94 print(f" {rec} : {b[rec]}")
95 print("d:")
96 for rec in d:
97 print(f" {rec} : {d[rec]}")
98 print(f"f:\n {f}")