1#  ___________________________________________________________________________
2#
3#  Pyomo: Python Optimization Modeling Objects
4#  Copyright 2017 National Technology and Engineering Solutions of Sandia, LLC
5#  Under the terms of Contract DE-NA0003525 with National Technology and
6#  Engineering Solutions of Sandia, LLC, the U.S. Government retains certain
7#  rights in this software.
8#  This software is distributed under the 3-clause BSD License.
9#  ___________________________________________________________________________
10
11import glob
12
13# build obj gradient and constraint Jacobian
14# from a gjh file written by the ASL gjh 'solver'
15# gjh solver may be called using pyomo, use keepfiles = True to write the file
16
17# Use symbolic_solver_labels=True option in pyomo allong with keepfiles = True
18# to write the .row file and .col file to get variable mappings
19
20
21def readgjh(fname=None):
22    if fname is None:
23        files = list(glob.glob("*.gjh"))
24        fname = files.pop(0)
25        if len(files) > 1:
26            print("**** WARNING **** More than one gjh file in current directory")
27            print("  Processing: %s\nIgnoring: %s" % (
28                fname, '\n         '.join(files)))
29
30    f = open(fname,"r")
31
32    data = "dummy_str"
33    while data != "param g :=\n":
34        data = f.readline()
35
36    data = f.readline()
37    g = []
38    while data[0] != ';':
39        # gradient entry (sparse)
40        entry = [int(data.split()[0]) - 1, float(data.split()[1])] # subtract 1 to index from 0
41        g.append(entry) # build obj gradient in sparse format
42        data = f.readline()
43
44
45    while data != "param J :=\n":
46        data = f.readline()
47
48    data = f.readline()
49    J = []
50    while data[0] != ';':
51        if data[0] == '[':
52            # Jacobian row index
53            #
54            # The following replaces int(filter(str.isdigit,data)),
55            # which only works in 2.x
56            data_as_int = int(''.join(filter(str.isdigit, data)))
57            row = data_as_int - 1  # subtract 1 to index from 0
58            data = f.readline()
59
60        entry = [row, int(data.split()[0]) - 1, float(data.split()[1])]  # subtract 1 to index from 0
61        J.append(entry) # Jacobian entries, sparse format
62        data = f.readline()
63    f.close()
64
65    #
66    # TODO: Parse the Hessian information
67    #
68
69    f = open(fname[:-3]+'col',"r")
70    data = f.read()
71    varlist = data.split()
72    f.close()
73
74    f = open(fname[:-3]+'row',"r")
75    data = f.read()
76    conlist = data.split()
77    f.close()
78
79    return g,J,varlist,conlist
80
81
82