source: coopr.pysp/trunk/coopr/pysp/phutils.py @ 2322

Last change on this file since 2322 was 2322, checked in by jwatson, 11 years ago

Fixed import issue associated with ModelData? due to recent code restructuring.

File size: 7.2 KB
Line 
1#  _________________________________________________________________________
2#
3#  Coopr: A COmmon Optimization Python Repository
4#  Copyright (c) 2008 Sandia Corporation.
5#  This software is distributed under the BSD License.
6#  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
7#  the U.S. Government retains certain rights in this software.
8#  For more information, see the Coopr README.txt file.
9#  _________________________________________________________________________
10
11import string
12import traceback
13import os
14
15from coopr.pyomo import *
16
17#
18# a simple utility function to pretty-print an index tuple into a [x,y] form string.
19#
20
21def indexToString(index):
22
23   # if the input type is a string or an int, then this isn't a tuple!
24   if isinstance(index, str) or isinstance(index, int):
25      return "["+str(index)+"]"
26
27   result = "["
28   for i in range(0,len(index)):
29      result += str(index[i])
30      if i != len(index) - 1:
31         result += ","
32   result += "]"
33   return result
34
35#
36# a simple utility to determine if a variable name contains an index specification.
37# in other words, is the reference to a complete variable (e.g., "foo") - which may
38# or may not be indexed - or a specific index or set of indices (e.g., "foo[1]" or
39# or "foo[1,*]".
40#
41
42def isVariableNameIndexed(variable_name):
43
44   left_bracket_count = variable_name.count('[')
45   right_bracket_count = variable_name.count(']')
46
47   if (left_bracket_count == 1) and (right_bracket_count == 1):
48      return True
49   elif (left_bracket_count == 1) or (right_bracket_count == 1):
50      raise ValueError, "Illegally formed variable name="+variable_name+"; if indexed, variable names must contain matching left and right brackets"
51   else:
52      return False
53
54#
55# takes a string indexed of the form "('foo', 'bar')" and returns a proper tuple ('foo','bar')
56#
57
58def tupleizeIndexString(index_string):
59
60   index_string=index_string.lstrip('(')
61   index_string=index_string.rstrip(')')
62   pieces = index_string.split(',')
63   return_index = ()
64   for piece in pieces:
65      piece = string.strip(piece)
66      piece = piece.lstrip('\'')
67      piece = piece.rstrip('\'')
68      transformed_component = None
69      try:
70         transformed_component = int(piece)
71      except ValueError:
72         transformed_component = piece
73      return_index = return_index + (transformed_component,)
74
75   # IMPT: if the tuple is a singleton, return the element itself.
76   if len(return_index) == 1:
77      return return_index[0]
78   else:
79      return return_index     
80
81#
82# related to above, extract the index from the variable name.
83# will throw an exception if the variable name isn't indexed.
84# the returned variable name is a string, while the returned
85# index is a tuple. integer values are converted to integers
86# if the conversion works!
87#
88
89def extractVariableNameAndIndex(variable_name):
90
91   if isVariableNameIndexed(variable_name) is False:
92      raise ValueError, "Non-indexed variable name passed to function extractVariableNameAndIndex()"
93
94   pieces = variable_name.split('[')
95   name = string.strip(pieces[0])
96   full_index = pieces[1].rstrip(']')
97
98   # even nested tuples in pyomo are "flattened" into
99   # one-dimensional tuples. to accomplish flattening
100   # replace all parens in the string with commas and
101   # proceed with the split.
102   full_index=string.translate(full_index, None, "()")
103   indices = full_index.split(',')
104
105   return_index = ()
106   
107   for index in indices:
108
109      # unlikely, but strip white-space from the string.
110      index=string.strip(index)
111
112      # if the tuple contains nested tuples, then the nested
113      # tuples have single quotes - "'" characters - around
114      # strings. remove these, as otherwise you have an
115      # illegal index.
116      index=string.translate(index, None, "\'")
117
118      # if the index is an integer, make it one!
119      transformed_index = None
120      try:
121         transformed_index = int(index)
122      except ValueError:
123         transformed_index = index                 
124      return_index = return_index + (transformed_index,)
125
126   # IMPT: if the tuple is a singleton, return the element itself.
127   if len(return_index) == 1:
128      return name, return_index[0]
129   else:
130      return name, return_index
131
132#
133# determine if the input index is an instance of the template,
134# which may or may not contain wildcards.
135#
136
137def indexMatchesTemplate(index, index_template):
138
139   # if the input index is not a tuple, make it one.
140   # ditto with the index template. one-dimensional
141   # indices in pyomo are not tuples, but anything
142   # else is.
143
144   if type(index) != tuple:
145      index = (index,)
146   if type(index_template) != tuple:
147      index_template = (index_template,)
148
149   if len(index) != len(index_template):
150      return False
151
152   for i in range(0,len(index_template)):
153      if index_template[i] == '*':
154         # anything matches
155         pass
156      else:
157         if index_template[i] != index[i]:
158            return False
159
160   return True
161
162#
163# given a variable (the real object, not the name) and an index,
164# "shotgun" the index and see which variable indices match the
165# input index. the cardinality could be > 1 if slices are
166# specified, e.g., [*,1].
167#
168
169def extractVariableIndices(variable, index_template):
170
171   result = []
172
173   for index in variable._index:
174
175      if indexMatchesTemplate(index, index_template) is True:
176         result.append(index)
177
178   return result
179
180#
181# construct a scenario instance!
182#
183def construct_scenario_instance(scenario_tree_instance,
184                                scenario_data_directory_name,
185                                scenario_name,
186                                reference_model,
187                                verbose):
188
189   if verbose is True:
190      if scenario_tree_instance._scenario_based_data == 1:
191         print "Scenario-based instance initialization enabled"
192      else:
193         print "Node-based instance initialization enabled"
194   
195   scenario = scenario_tree_instance.get_scenario(scenario_name)
196   scenario_instance = None
197
198   if verbose is True:
199      print "Creating instance for scenario=" + scenario._name
200
201   try:
202      if scenario_tree_instance._scenario_based_data == 1:
203         scenario_data_filename = scenario_data_directory_name + os.sep + scenario._name + ".dat"
204         if verbose is True:
205            print "Data for scenario=" + scenario._name + " loads from file=" + scenario_data_filename
206         scenario_instance = reference_model.create(scenario_data_filename)
207      else:
208         scenario_instance = reference_model.clone()
209         scenario_data = ModelData()
210         current_node = scenario._leaf_node
211         while current_node is not None:
212            node_data_filename = scenario_data_directory_name + os.sep + current_node._name + ".dat"
213            if verbose is True:
214               print "Node data for scenario=" + scenario._name + " partially loading from file=" + node_data_filename
215            scenario_data.add(node_data_filename)
216            current_node = current_node._parent
217         scenario_data.read(model=scenario_instance)
218         scenario_instance._load_model_data(scenario_data)
219         scenario_instance.presolve()
220   except:
221      print "Encountered exception in model instance creation - traceback:"
222      traceback.print_exc()
223      raise RuntimeError, "Failed to create model instance for scenario=" + scenario._name
224
225   return scenario_instance
Note: See TracBrowser for help on using the repository browser.