Loading...
Searching...
No Matches
core_example1.py
Go to the documentation of this file.
1import argparse
2import sys
3from gams.core import gdx
4
5if __name__ == "__main__":
6 parser = argparse.ArgumentParser()
7 parser.add_argument("sysDir")
8 parser.add_argument("gdxFile", nargs="?", default=None)
9 args = parser.parse_args()
10
11 print(f"Using GAMS system directory: {args.sysDir}")
12
13 gdx_h = gdx.new_gdxHandle_tp()
14 rc = gdx.gdxCreateD(gdx_h, args.sysDir, gdx.GMS_SSSIZE)
15 if not rc[0]:
16 raise Exception(rc[1])
17
18 print(f"Using GDX DLL version: {gdx.gdxGetDLLVersion(gdx_h)[1]}")
19
20 if args.gdxFile is None:
21 if not gdx.gdxOpenWrite(gdx_h, "demanddata.gdx", "xp_example1")[0]:
22 raise Exception("Error gdxOpenWrite")
23 if not gdx.gdxDataWriteStrStart(
24 gdx_h, "Demand", "Demand data", 1, gdx.GMS_DT_PAR, 0
25 ):
26 raise Exception("Error gdxDataWriteStrStart")
27
28 values = gdx.doubleArray(gdx.GMS_VAL_MAX)
29 values[gdx.GMS_VAL_LEVEL] = 324.0
30 gdx.gdxDataWriteStr(gdx_h, ["New-York"], values)
31 values[gdx.GMS_VAL_LEVEL] = 299.0
32 gdx.gdxDataWriteStr(gdx_h, ["Chicago"], values)
33 values[gdx.GMS_VAL_LEVEL] = 274.0
34 gdx.gdxDataWriteStr(gdx_h, ["Topeka"], values)
35
36 if not gdx.gdxDataWriteDone(gdx_h):
37 raise Exception("Error gdxDataWriteDone")
38 print("Demand data written")
39 else:
40 if not gdx.gdxOpenRead(gdx_h, sys.argv[2])[0]:
41 raise Exception("Error gdxOpenRead")
42
43 file_version, producer = gdx.gdxFileVersion(gdx_h)[1:]
44 print(f"GDX file written using version: {file_version}")
45 print(f"GDX file written by: {producer}")
46
47 rc, sym_nr = gdx.gdxFindSymbol(gdx_h, "x")
48 if not rc:
49 raise Exception("Symbol x not found")
50
51 dim, sym_type = gdx.gdxSymbolInfo(gdx_h, sym_nr)[2:]
52 if dim != 2 or sym_type != gdx.GMS_DT_VAR:
53 raise Exception(
54 f"x is not a two dimensional variable:\ndim = {dim}\ntype = {sym_type}"
55 )
56
57 rc, nr_recs = gdx.gdxDataReadStrStart(gdx_h, sym_nr)
58 if not rc:
59 raise Exception(
60 f"Error in gdxDataReadStrStart: {gdx.gdxErrorStr(gdx_h, gdx.gdxGetLastError(gdx_h))[1]}"
61 )
62
63 print(f"Variable x has {nr_recs} records")
64 for i in range(nr_recs):
65 rc, elements, values, afdim = gdx.gdxDataReadStr(gdx_h)
66 if not rc:
67 raise Exception(
68 f"Error in gdxDataReadStr: {gdx.gdxErrorStr(gdx_h, gdx.gdxGetLastError(gdx_h))[1]}"
69 )
70 level = values[gdx.GMS_VAL_LEVEL]
71 if level != 0:
72 elements = [elements[d] for d in range(dim)]
73 print(f"{'.'.join(elements)} = {level}")
74 print("All solution values shown")
75 gdx.gdxDataReadDone(gdx_h)
76
77 if gdx.gdxClose(gdx_h):
78 raise Exception("Error in gdxClose")
79 if not gdx.gdxFree(gdx_h):
80 raise Exception("Error in gdxFree")
81 print("All done")