source: coopr.pysp/trunk/coopr/pysp/wwphextension.py @ 2143

Last change on this file since 2143 was 2143, checked in by jwatson, 10 years ago

Missed indentation fix to PySP ww PH extension plug-in.

  • Property svn:executable set to *
File size: 44.8 KB
Line 
1#  _________________________________________________________________________
2#
3#  Coopr: A COmmon Optimization Python Repository
4#  Copyright (c) 2009 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 types
12from pyutilib.plugin.core import *
13from coopr.pysp import phextension
14from coopr.pysp.phutils import *
15from coopr.pyomo.base import *
16
17from coopr.pyomo.base.set_types import *
18
19from coopr.pyomo.base.var import VarStatus
20
21import string
22import os
23
24#=========================
25def slam_priority_descend_compare(a, b):
26   # used to sort the variable-suffix map for slamming priority
27   value_a = getattr(a, "SlammingPriority")
28   value_b = getattr(b, "SlammingPriority")
29   return cmp(value_b, value_a)
30
31#==================================================
32#==================================================
33class wwphextension(SingletonPlugin):
34
35   implements (phextension.IPHExtension)
36
37   def __init__(self, *args, **kwds):
38
39      # TBD - migrate all of the self attributes defined on-the-fly
40      #       in the post-post-initialization routine here!
41
42      self._configuration_filename = None 
43      self._suffix_filename = None
44
45#=========================
46   def process_suffix_file(self, ph):
47
48      # for each suffix, maintain an inverse map from the suffix name to a list of
49      # objects with that suffix. an object could be a variable (_VarBase) or a
50      # variable value, depending on the resolution of the object for which the
51      # suffix is defined.
52      self._suffix_to_variable_map = {}
53
54      self.slam_list = []
55     
56      if self._suffix_filename is None:
57         return
58
59      if os.path.exists(self._suffix_filename) is False:
60         raise RuntimeError, "Suffix file="+self._suffix_filename+" specified for WW PH extension either does not exist or cannot be read"
61
62      print "WW PH Extension: Loading variable suffixes from file=", self._suffix_filename
63
64      reference_instance = ph._model_instance
65
66      suffix_file = open(self._suffix_filename,'r')
67      for line in suffix_file.readlines():
68         line = line.strip()
69         if len(line) > 0 and line[0] != '#':
70            pieces = line.split()
71            if len(pieces) != 3:
72               raise RuntimeError, "Illegal line=["+line+"] encountered in ww ph extension suffix file="+self._suffix_filename+"; format is variable, suffix, suffix-value."
73
74            variable_string = pieces[0]
75            suffix_name = pieces[1]
76            suffix_value = pieces[2]
77
78            # decide what type of suffix value we're dealing with.
79            is_int = False
80            is_bool = False
81            converted_value = None
82            try:
83               converted_value = bool(suffix_value)
84               is_bool = True
85            except valueerror:
86               pass
87            try:
88               converted_value = int(suffix_value)
89               is_int = True
90            except ValueError:
91               pass
92
93            if (is_int is False) and (is_bool is False):
94               raise RuntimeError, "WW PH Extension unable to deduce type of data referenced in ww ph extension suffix file="+self._suffix_filename+"; value="+suffix_value+" for "+variable_name
95
96            # determine if we're dealing with complete variables or indexed variables.
97            if isVariableNameIndexed(variable_string) is True:
98
99               variable_name, index_template = extractVariableNameAndIndex(variable_string)
100               
101               # verify that the root variable exists and grab it.
102               if variable_name not in reference_instance.active_components(Var).keys():
103                  raise RuntimeError, "Unknown variable="+variable_name+" referenced in ww ph extension suffix file="+self._suffix_filename
104               variable = reference_instance.active_components(Var)[variable_name]
105
106               # extract all "real", i.e., fully specified, indices matching the index template.
107               match_indices = extractVariableIndices(variable, index_template)
108
109               # there is a possibility that no indices match the input template.
110               # if so, let the user know about it.
111               if len(match_indices) == 0:
112                  raise RuntimeError, "No indices match template="+str(index_template)+" for variable="+variable_name               
113
114               # add the suffix to all variable values identified.
115               for index in match_indices:
116
117                  variable_value = variable[index]
118
119                  # if the suffix already exists, we don't care - we're stomping it.
120                  if hasattr(variable_value, suffix_name) is True:
121                     delattr(variable_value, suffix_name)
122 
123                  # set the suffix on the variable value.
124                  setattr(variable_value, suffix_name, converted_value)
125
126                  # place the variable value in the suffix->variable map, for easy searching elsewhere in this plugin.
127                  if suffix_name not in self._suffix_to_variable_map.keys():
128                     self._suffix_to_variable_map[suffix_name] = []
129                  self._suffix_to_variable_map[suffix_name].append(variable_value)                 
130
131            else:
132
133               # verify that the variable exists.
134               if variable_string not in reference_instance.active_components(Var).keys():
135                  raise RuntimeError, "Unknown variable="+variable_string+" referenced in ww ph extension suffix file="+self._suffix_filename
136
137               variable = reference_instance.active_components(Var)[variable_string]
138
139               # 9/14/2009 - now forcing the user to explicit specify the full
140               # match template (e.g., "foo[*,*]") instead of just the variable
141               # name (e.g., "foo") to represent the set of all indices.
142               
143               # if the variable is a singleton - that is, non-indexed - no brackets is fine.
144               # we'll just tag the var[None] variable value with the (suffix,value) pair.
145               if None not in variable._index:
146                  raise RuntimeError, "Illegal match template="+variable_string+" specified in ww ph extension suffix file="+self._suffix_filename                 
147
148               # if the suffix already exists, we don't care - we're stomping it.
149               if hasattr(variable, suffix_name) is True:
150                  delattr(variable, suffix_name)
151 
152               # set the suffix on the variable.
153               setattr(variable, suffix_name, converted_value)
154
155               # place the variable in the suffix->variable map, for easy searching elsewhere in this plugin.
156               if suffix_name not in self._suffix_to_variable_map.keys():
157                  self._suffix_to_variable_map[suffix_name] = []
158               self._suffix_to_variable_map[suffix_name].append(variable)
159
160#      print "pre-sort suffix->variable map:"
161#      for key,value_list in self._suffix_to_variable_map.items():
162#         print "key=",key,":",
163#         for value in value_list:
164#            print value.name,"",
165#         print ""
166
167      if "SlammingPriority" in self._suffix_to_variable_map:
168         self.slam_list = self._suffix_to_variable_map["SlammingPriority"]
169
170      self.slam_list.sort(slam_priority_descend_compare)
171
172#==================================================
173   def post_instance_creation(self, ph):
174       """ Called after PH initialization has created the scenario instances, but before any PH-related weights/variables/parameters/etc are defined!"""
175       # we don't muck with the instances.
176       pass
177
178#==================================================
179   def post_ph_initialization(self, ph):
180
181      # set up "global" record keeping.
182      self.cumulative_discrete_fixed_count = 0
183      self.cumulative_continuous_fixed_count = 0
184
185      # we always track convergence of continuous variables, but we may not want to fix/slam them.                                                           
186      self.fix_continuous_variables = False
187
188      # there are occasions where we might want to fix any values at the end of the
189      # run if the scenarios agree - even if the normal fixing criterion (e.g.,
190      # converged for N iterations) don't apply. one example is when the term-diff
191      # is 0, at which point you really do have a solution. currently only applies
192      # to discrete variables.
193      self.fix_discrete_variables_at_exit = False
194
195      # set up the mipgap parameters (zero means ignore)
196      # note: because we lag one iteration, the final will be less than requested
197      # initial and final refer to PH iteration 1 and PH iteration X, where
198      # X is the iteration at which the convergence metric hits 0.
199      self.Iteration0MipGap = 0.0
200      self.InitialMipGap = 0.10
201      self.FinalMipGap = 0.001
202
203      # "Read" the defaults for parameters that control fixing
204      # (these defaults can be overridden at the variable level)
205      # for all six of these, zero means don't do it.
206      self.Iter0FixIfConvergedAtLB = 0 # 1 or 0
207      self.Iter0FixIfConvergedAtUB = 0  # 1 or 0
208      self.Iter0FixIfConvergedAtNB = 0  # 1 or 0 (converged to a non-bound)
209      # TBD: check for range errors for all six of these
210      self.FixWhenItersConvergedAtLB = 10 
211      self.FixWhenItersConvergedAtUB = 10
212      self.FixWhenItersConvergedAtNB = 12  # converged to a non-bound
213      self.FixWhenItersConvergedContinuous = 0
214     
215      # "default" slamming parms:
216      # TBD: These should get ovverides from suffixes
217      # notice that for a particular var, all could be False
218      # TBD: the user might also want to give slamming priorities
219      self.CanSlamToLB = False
220      self.CanSlamToMin = False
221      self.CanSlamToAnywhere = True
222      self.CanSlamToMax = False
223      self.CanSlamToUB = False
224      self.PH_Iters_Between_Cycle_Slams = 1  # zero means "slam at will"
225      self.SlamAfterIter = len(ph._scenario_tree._stages[-1]._tree_nodes)
226
227      self.CycleLengthSlamThreshold = len(ph._scenario_tree._stages[-1]._tree_nodes) 
228      self.W_hash_history_len = max(100, self.CycleLengthSlamThreshold+1) 
229
230      # end of parms
231
232      self._last_slam_iter = -1    # dynamic
233
234      # constants for W vector hashing (low cost rand() is all we need)
235      # note: July 09, dlw is planning to eschew pre-computed random vector
236      # another note: the top level reset is OK, but really it should
237      #   done way down at the index level with a serial number (stored)
238      #   to avoid correlated hash errors
239      # the hash seed was deleted in 1.1 and we seed with the
240      self.W_hash_seed = 17  # we will reset for dynamic rand vector generation
241      self.W_hash_rand_val = self.W_hash_seed # current rand
242      self.W_hash_a = 1317       # a,b, and c are for a simple generator
243      self.W_hash_b = 27699
244      self.W_hash_c = 131072  # that period should be usually long enough for us!
245                              # (assuming fewer than c scenarios)
246
247      # set up tree storage for statistics that we care about tracking.
248      for stage in ph._scenario_tree._stages:
249
250         if stage != ph._scenario_tree._stages[-1]:
251
252            # first, gather all unique variables referenced in self stage
253            # self "gather" step is currently required because we're being lazy
254            # in terms of index management in the scenario tree
255##            stage_variables = {}
256##            for (reference_variable, index_template, reference_index) in stage._variables:
257##               if reference_variable.name not in stage_variables.keys():
258##                  stage_variables[reference_variable.name] = reference_variable
259##
260            for tree_node in stage._tree_nodes:
261               tree_node._num_iters_converged = {}
262               tree_node._last_converged_val = {}
263               tree_node._w_hash = {}
264               tree_node._fixed_var_flag = {}
265
266               # next, create parameters for each variable in the corresponding tree node.
267
268               for (variable, index_template, variable_indices) in stage._variables:
269
270                  variable_name = variable.name
271                  variable_type = variable.domain
272                 
273                  for index in variable_indices:
274
275                     # IMPT: it has bitten us before in this plug-in, so I'll state the obvious:
276                     #       variable values in the last stage of a stochastic program will *not*
277                     #       have a defined _stage attribute.
278#                     print "dlw debug create stage association ",variable_name, index, stage._name                     
279                     variable[index]._stage = stage
280
281                     new_stat_index = variable._index
282                     new_stat_parameter_name = "NODESTAT_NUM_ITERS_CONVERGED_"+variable.name
283                     new_stat_parameter = Param(new_stat_index,name=new_stat_parameter_name)
284                     for newindex in new_stat_index:
285                        new_stat_parameter[newindex] = 0
286                     tree_node._num_iters_converged[variable.name] = new_stat_parameter
287                     
288                     # need to know to what we have most recently converged
289                     new_conv_index = variable._index
290                     new_conv_parameter_name = "NODESTAT_LAST_CONVERGED_VAL_"+variable.name
291                     new_conv_parameter = Param(new_conv_index,name=new_conv_parameter_name)
292                     for newindex in new_conv_index:
293                        new_conv_parameter[newindex] = 0.5 # not an int, so harmless
294                     tree_node._last_converged_val[variable.name] = new_conv_parameter
295                     
296                     # need to know to what has been fixed
297                     new_fix_index = variable._index
298                     new_fix_parameter_name = "NODESTAT_FIXED_FLAG_VAL_"+variable.name
299                     new_fix_parameter = Param(new_fix_index,name=new_fix_parameter_name)
300                     for newindex in new_fix_index:
301                        new_fix_parameter[newindex] = False
302                     tree_node._fixed_var_flag[variable.name] = new_fix_parameter
303                     
304                     # now make the w hash value storage array
305                     new_hash_index = variable._index
306                     new_hash_parameter_name = "W_HASH_STORAGE_"+variable.name
307                     new_hash_parameter = Param(new_hash_index, ph._iteration_index_set, name=new_hash_parameter_name)
308                     for newindex in new_hash_index:
309                        for i in range(0, ph._max_iterations+1):
310                           new_hash_parameter[newindex,i] = 0
311                     tree_node._w_hash[variable.name] = new_hash_parameter
312
313      # store the total variable counts for future reporting.
314      (self.total_discrete_vars,self.total_continuous_vars) = ph.compute_variable_counts()
315
316      if self._configuration_filename is not None:
317         if os.path.exists(self._configuration_filename) is True:
318            print "WW PH Extension: Loading user-specified configuration from file=" + self._configuration_filename
319            execfile(self._configuration_filename)
320         else:
321            raise RuntimeError, "***WW PH Extension: Failed to load user-specified configuration from file="+self._configuration_filename
322      else:
323         print "WW PH Extension: No user-specified configuration file supplied - using defaults"
324
325      # process any suffix information, if it exists.
326      self.process_suffix_file(ph)         
327
328      # set up the mip gap for iteration 0.
329      if self.Iteration0MipGap > 0.0:
330         print "Setting mipgap to "+str(self.Iteration0MipGap)
331         ph._mipgap = self.Iteration0MipGap
332         
333#==================================================
334   def post_iteration_0_solves(self, ph):
335
336      for stage in ph._scenario_tree._stages:
337         
338         if stage != ph._scenario_tree._stages[-1]: # no blending over the final stage
339           
340            for tree_node in stage._tree_nodes:
341
342               for (variable, index_template, variable_indices) in stage._variables:
343                 
344                  variable_name = variable.name
345                  variable_type = variable.domain
346
347                  for index in variable_indices:
348
349                     # determine if this index is used - otherwise, don't waste time
350                     # fixing and cycle checking. for one, the code will crash :-) with
351                     # none values during the cycle checking computation!
352
353                     is_used = True # until proven otherwise                     
354                     for scenario in tree_node._scenarios:
355                        instance = ph._instances[scenario._name]
356                        if getattr(instance,variable_name)[index].status == VarStatus.unused:
357                           is_used = False
358
359                     if is_used is True:
360
361                        # unlikely, but variables might be fixed even at this stage, depending on
362                        # what weirdness users do prior to the iteration 0 solves.
363                        instance_fixed_count = 0
364                        for scenario in tree_node._scenarios:
365                           instance = ph._instances[scenario._name]
366                           if getattr(instance,variable_name)[index].fixed is True:
367                              instance_fixed_count += 1
368                        if ((instance_fixed_count > 0) and (instance_fixed_count < len(tree_node._scenarios))):
369                           raise RuntimeError, "Variable="+variable_name+str(index)+" is fixed in "+str(instance_fixed_count)+" scenarios, but less than the number of scenarios at tree node="+tree_node._name
370
371                        if instance_fixed_count == 0:
372
373                           if isinstance(variable_type, IntegerSet) or isinstance(variable_type, BooleanSet):                           
374                              node_min = self.Int_If_Close_Enough(ph, tree_node._minimums[variable_name][index]())
375                              node_max = self.Int_If_Close_Enough(ph, tree_node._maximums[variable_name][index]())
376
377                              # update convergence prior to checking for fixing.
378                              self._int_convergence_tracking(ph, tree_node, variable_name, index, node_min, node_max)
379                              attrvariable = ph._model_instance.active_components(Var)[variable_name][index]
380                              if hasattr(attrvariable, 'Iter0FixIfConvergedAtLB'):
381                                 lb = getattr(attrvariable, 'Iter0FixIfConvergedAtLB')
382                              else:
383                                 lb = self.Iter0FixIfConvergedAtLB
384                              if hasattr(attrvariable, 'Iter0FixIfConvergedatUB'):
385                                 ub = getattr(attrvariable, 'Iter0FixIfConvergedAtUB')
386                              else:
387                                 ub = self.Iter0FixIfConvergedAtUB
388                              if hasattr(attrvariable, 'Iter0FixIfConvergedAtNB'):
389                                 nb = getattr(attrvariable, 'Iter0FixIfConvergedAtNB')
390                              else:
391                                 nb = self.Iter0FixIfConvergedAtNB
392                              if self._should_fix_discrete_due_to_conv(tree_node, variable, index, lb, ub, nb):
393                                 self._fix_var(ph, tree_node, variable, index, node_min)
394                              elif self.W_hash_history_len > 0:   # if not fixed, then hash - no slamming at iteration 0
395                                 self._w_hash_acct(ph, tree_node, variable_name, index) # obviously not checking for cycles at iteration 0!
396
397                           else:
398                             
399                              node_min = tree_node._minimums[variable_name][index]()
400                              node_max = tree_node._maximums[variable_name][index]()
401                             
402                              self._continuous_convergence_tracking(ph, tree_node, variable_name, index, node_min, node_max)
403                             
404# jpw: not sure if we care about cycle detection in continuous variables?
405#                              if self.W_hash_history_len > 0: 
406#                                 self._w_hash_acct(ph, tree_node, variable_name, index)
407                             
408
409#==================================================
410   def post_iteration_0(self, ph):
411 
412      self._met0 = ph._converger.lastMetric()
413
414      if (self.InitialMipGap > 0) and (self.FinalMipGap >= 0) and (self.InitialMipGap > self.FinalMipGap):
415         gap = self.InitialMipGap
416         print "Setting mipgap to "+str(gap)
417         ph._mipgap = gap
418
419#==================================================         
420
421   def pre_iteration_k_solves(self, ph):
422        """ Called immediately before the iteration k solves!"""
423        # we don't muck with the PH objectives
424        pass
425
426#==================================================
427   def post_iteration_k_solves(self, ph):
428
429      for stage in ph._scenario_tree._stages:
430         
431         if stage != ph._scenario_tree._stages[-1]: # no blending over the final stage
432           
433            for tree_node in stage._tree_nodes:
434
435               for (variable, index_template, variable_indices) in stage._variables:
436
437                  variable_name = variable.name
438                  variable_type = variable.domain
439
440                  for index in variable_indices:
441
442                     # determine if this index is used - otherwise, don't waste time
443                     # fixing and cycle checking. for one, the code will crash :-) with
444                     # None values during the cycle checking computation!
445
446                     is_used = True # until proven otherwise                     
447                     for scenario in tree_node._scenarios:
448                        instance = ph._instances[scenario._name]
449                        if getattr(instance,variable_name)[index].status == VarStatus.unused:
450                           is_used = False
451
452                     if is_used is True:                       
453
454                        # determine if the variable is already fixed.
455                        instance_fixed_count = 0
456                        for scenario in tree_node._scenarios:
457                           instance = ph._instances[scenario._name]
458                           if getattr(instance,variable_name)[index].fixed is True:
459                              instance_fixed_count += 1
460                        if ((instance_fixed_count > 0) and (instance_fixed_count < len(tree_node._scenarios))):
461                           raise RuntimeError, "Variable="+variable_name+str(index)+" is fixed in "+str(instance_fixed_count)+" scenarios, but less than the number of scenarios at tree node="+tree_node._name
462
463                        if instance_fixed_count == 0:
464
465                           if isinstance(variable_type, IntegerSet) or isinstance(variable_type, BooleanSet):                           
466                              node_min = self.Int_If_Close_Enough(ph, tree_node._minimums[variable_name][index]())
467                              node_max = self.Int_If_Close_Enough(ph, tree_node._maximums[variable_name][index]())
468
469                              # update convergence prior to checking for fixing.
470                              self._int_convergence_tracking(ph, tree_node, variable_name, index, node_min, node_max)
471
472                              # now check on permissions to converge to various placed (e.g., lb is lb permission)
473                              attrvariable = ph._model_instance.active_components(Var)[variable_name][index]
474                              if hasattr(attrvariable, 'FixWhenItersConvergedAtLB'):
475                                 lb = getattr(attrvariable, 'FixWhenItersConvergedAtLB')
476                              else:
477                                 lb = self.FixWhenItersConvergedAtLB
478                              if hasattr(attrvariable, 'FixWhenItersConvergedAtUB'):
479                                 ub = getattr(attrvariable, 'FixWhenItersConvergedAtUB')
480                              else:
481                                 ub = self.FixWhenItersConvergedAtUB
482                              if hasattr(attrvariable, 'FixWhenItersConvergedAtNB'):
483                                 nb = getattr(attrvariable, 'FixWhenItersConvergedAtNB')
484                              else:
485                                 nb = self.FixWhenItersConvergedAtNB
486                                 
487                              if self._should_fix_discrete_due_to_conv(tree_node, variable, index, lb, ub, nb):
488                                 
489                                 self._fix_var(ph, tree_node, variable, index, node_min)
490                                 
491                              else: # if not fixed, then hash and slam as necessary.
492                                 
493                                 if self.W_hash_history_len > 0:   
494                                    self._w_hash_acct(ph, tree_node, variable_name, index)
495                                    computed_cycle_length = self.hash_hit_len(ph, tree_node, variable_name, index)
496                                    if (computed_cycle_length >= self.CycleLengthSlamThreshold) and ((ph._current_iteration - self._last_slam_iter) > self.PH_Iters_Between_Cycle_Slams):
497                                       # TBD: we may not want to slam immediately - it may disappear on it's own after a few iterations, depending on what other variables do.
498                                       # note: i am not slamming the offending variable, but a selected variable
499                                       print "Cycle length exceeds slam threshold="+str(self.CycleLengthSlamThreshold)+"; choosing variable to slam"
500                                       self._pick_one_and_slam_it(ph)
501                                    elif (computed_cycle_length > 1) and (computed_cycle_length < self.CycleLengthSlamThreshold):
502                                       # there was a (potential) cycle, but the slam threshold wasn't reached.
503                                       print "Taking no action to break cycle - length="+str(computed_cycle_length)+" does not exceed slam threshold="+str(self.CycleLengthSlamThreshold)
504                                    elif (computed_cycle_length >= self.CycleLengthSlamThreshold) and ((ph._current_iteration - self._last_slam_iter) > self.PH_Iters_Between_Cycle_Slams):
505                                       # we could have slammed, but we recently did and are taking a break to see if things settle down on their own.
506                                       print "Taking no action to break cycle - length="+str(computed_cycle_length)+" does exceed slam threshold="+str(self.CycleLengthSlamThreshold)+ \
507                                             ", but another variable was slammed within the past "+str(self.PH_Iters_Between_Cycle_Slams)+" iterations" 
508                           else:
509
510                              # obviously don't round in the continuous case.
511                              node_min = tree_node._minimums[variable_name][index]()
512                              node_max = tree_node._maximums[variable_name][index]()
513
514                              # update convergence prior to checking for fixing.
515                              self._continuous_convergence_tracking(ph, tree_node, variable_name, index, node_min, node_max)
516
517                              if self._should_fix_continuous_due_to_conv(tree_node, variable, index):
518                                 # fixing to max value for safety (could only be an issue due to tolerances).
519                                 self._fix_var(ph, tree_node, variable, index, node_max)
520                                 # note: we currently don't clam continuous variables!
521
522      # TBD: the 1 might need to be parameterized
523      if (ph._current_iteration > self.SlamAfterIter) and ((ph._current_iteration - self._last_slam_iter) > 1) and (ph._converger.isImproving(1)):
524         self._pick_one_and_slam_it(ph)
525         self._just_slammed_ = True
526      else:
527         self._just_slammed_ = False
528     
529#==================================================
530   def post_iteration_k(self, ph):
531
532      # note: we are lagging one iteration
533      # linear
534      if (self.InitialMipGap > 0 and self.FinalMipGap >= 0) and self.InitialMipGap > self.FinalMipGap:
535         m0 = self._met0
536         m = ph._converger.lastMetric()
537         mlast = ph._converger._convergence_threshold
538         g0 = self.InitialMipGap
539         glast = self.FinalMipGap
540         gap = ((m-m0)/(m0-mlast) + g0/(g0-glast))* (g0-glast)
541         if gap > g0:
542            print "***WARNING: Setting mipgap to thresholded maximal initial mapgap value="+str(g0)+"; unthresholded value="+str(gap)           
543            gap = g0
544         else:
545            print "Setting mipgap to "+str(gap)
546         ph._mipgap = gap
547
548
549#==================================================
550   def post_ph_execution(self, ph):
551
552      if self.fix_discrete_variables_at_exit is True:
553         print "WW PH extension: Fixing all discrete variables that are converged at termination"
554         self._fix_all_converged_discrete_variables(ph)
555
556#=========================
557   def Int_If_Close_Enough(self, ph, x):
558       # if x is close enough to the nearest integer, return the integer
559       # else return x
560       if abs(round(x)-x) <= ph._integer_tolerance:
561          return int(round(x))
562       else:
563          return x
564
565#=========================   
566   def _int_convergence_tracking(self, ph, tree_node, variable_name, index, node_min, node_max):
567       # keep track of cumulative iters of convergence to the same int
568       if (node_min == node_max) and (type(node_min) is types.IntType): 
569          if node_min == tree_node._last_converged_val[variable_name][index]():
570             tree_node._num_iters_converged[variable_name][index].value = tree_node._num_iters_converged[variable_name][index].value + 1
571          else:
572             tree_node._num_iters_converged[variable_name][index].value = 1
573             tree_node._last_converged_val[variable_name][index] = node_min
574       else:
575          tree_node._num_iters_converged[variable_name][index].value = 0
576          tree_node._last_converged_val[variable_name][index].value = 0.5 
577
578#=========================   
579   def _continuous_convergence_tracking(self, ph, tree_node, variable_name, index, node_min, node_max):
580       # keep track of cumulative iters of convergence to the same value within tolerance.
581       if abs(node_max - node_min) <= ph._integer_tolerance:
582          if abs(node_min - tree_node._last_converged_val[variable_name][index]()) <= ph._integer_tolerance:
583             tree_node._num_iters_converged[variable_name][index].value  = tree_node._num_iters_converged[variable_name][index].value + 1
584          else:
585             tree_node._num_iters_converged[variable_name][index].value = 1
586             tree_node._last_converged_val[variable_name][index] = node_min
587       else:
588          tree_node._num_iters_converged[variable_name][index].value = 0
589          tree_node._last_converged_val[variable_name][index] = 0.2342343243223423 # TBD - avoid the magic constant!
590
591#=========================         
592   def _w_hash_acct(self, ph, tree_node, variable_name, index):
593      # do the w hash accounting work
594      # we hash on the variable ph weights, and not the values; the latter may not shift for some time, while the former should.
595      self.W_hash_rand_val = self.W_hash_seed
596      for scenario in tree_node._scenarios:
597         instance = ph._instances[scenario._name]
598         weight_parameter_name = "PHWEIGHT_"+variable_name
599         tree_node._w_hash[variable_name][index,ph._current_iteration].value += getattr(instance,weight_parameter_name)[index].value * self.W_hash_rand_val
600         self.W_hash_rand_val = (self.W_hash_b + self.W_hash_a * self.W_hash_rand_val) % self.W_hash_c
601
602#=========================
603   def dump_w_hash(self, ph, tree_node, stage):
604       # debug code
605      print "Stage=",stage._name," tree node=",tree_node._name
606      print "PH Iteration      Variable                          PH Weight Hash Value"
607      for (variable, index_template, variable_indices) in stage._variables:
608
609          variable_name = variable.name
610          variable_type = variable.domain
611
612          # TBD - should we cycle-detect on continuous vars?
613          if isinstance(variable_type, IntegerSet) or isinstance(variable_type, BooleanSet):
614             for index in variable_index:
615                print "%4d        %50ls %20.5f" % (ph._current_iteration, tree_node._w_hash[variable_name][index,ph._current_iteration], tree_node._w_hash[variable_name][index,ph._current_iteration]())
616                                                                                                                           
617#=========================
618   def hash_hit_len(self, ph, tree_node, variable_name, index):
619      # return cycles back to closest hash hit for hashval or 0 if no hash hit
620
621      # if the values are converged, then don't report a cycle - often, the weights at convergence are 0s, and even
622      # if they aren't, they won't move if the values are uniform.
623      if (tree_node._num_iters_converged[variable_name][index].value == 0) and (tree_node._fixed_var_flag[variable_name][index].value is False):
624         current_hash_value = tree_node._w_hash[variable_name][index,ph._current_iteration]()
625         # scan starting from the farthest point back in history to the closest - this is required to
626         # identify the longest possible cycles, which is what we want.
627         for i in range(max(ph._current_iteration - self.W_hash_history_len - 1, 1), ph._current_iteration - 1, 1):
628             this_hash_value = tree_node._w_hash[variable_name][index,i]()
629             if abs(this_hash_value - current_hash_value) <= ph._integer_tolerance:
630                if index is None:
631                   print "Possible cycle detected via PH weight hashing - variable="+variable_name+", node="+tree_node._name
632                else:
633                   print "Possible cycle detected via PH weight hashing - variable="+variable_name+indexToString(index)+" node="+ tree_node._name
634                print "Current hash value="+str(current_hash_value)+" matched (within tolerance) hash value="+str(this_hash_value)+" found at PH iteration="+str(i)+"; cycle length="+str(ph._current_iteration - i)
635                return ph._current_iteration - i
636      return 0
637
638#=========================
639   def _fix_var(self, ph, tree_node, variable, index, fix_value):
640       # fix the variable, account for it and maybe output some trace information
641       # note: whether you fix at current values or not can severly impact feasibility later
642       # in the game. my original thought was below - but that didn't work out. if you
643       # make integers, well, integers, all appears to be well.
644       # IMPT: we are leaving the values for individual variables alone, at potentially
645       #       smallish and heterogeneous values. if we fix/round, we run the risk of
646       #       infeasibilities due to numerical issues. the computed value below is
647       #       strictly for output purposes. dlw note: as of aug 1 '09,
648       #       node_min and node_max should be
649       #       int if they should be (so to speak)
650
651       fixing_reported = False # to track whether you have already output the fix message for one scenario.
652
653       for scenario in tree_node._scenarios:
654
655          instance = ph._instances[scenario._name]
656                       
657          getattr(instance,variable.name)[index].fixed = True
658          getattr(instance,variable.name)[index].value = fix_value
659          tree_node._fixed_var_flag[variable.name][index].value = True
660
661          variable_type = variable.domain         
662
663          if fixing_reported is False:
664             # pretty-print the index, string the trailing spaces from the strings.
665             if index is None:
666                print "Fixing variable="+variable.name+" at tree node="+tree_node._name+" to value="+str(fix_value)+"; converged for "+str(tree_node._num_iters_converged[variable.name][index]())+" iterations"
667             else:
668                print "Fixing variable="+variable.name+indexToString(index)+" at tree node="+tree_node._name+" to value="+str(fix_value)+"; converged for "+str(tree_node._num_iters_converged[variable.name][index]())+" iterations"               
669             fixing_reported = True
670             if isinstance(variable_type, IntegerSet) or isinstance(variable_type, BooleanSet):
671                self.cumulative_discrete_fixed_count = self.cumulative_discrete_fixed_count + 1
672             else:
673                self.cumulative_continuous_fixed_count = self.cumulative_continuous_fixed_count + 1                                                           
674
675#=========================
676   def _should_fix_discrete_due_to_conv(self, tree_node, variable, index, lb_iters, ub_iters, nb_iters):
677      # return True if this should be fixed due to convergence
678      variable_name = variable.name
679
680      # jpw: i don't think this logic is correct - shouldn't "non-bound" be moved after the lb/ub checks - this doesn't check a bound!
681      # dlw reply: i meant it to mean "without regard to bound" so i have updated the document
682      if nb_iters > 0 and tree_node._num_iters_converged[variable_name][index]() >= nb_iters:
683            return True
684      else:
685         lb = variable[index].lb()
686         ub = variable[index].ub()
687         conval = tree_node._last_converged_val[variable_name][index]()
688         # note: if they are converged node_max == node_min
689         if lb_iters > 0 and tree_node._num_iters_converged[variable_name][index]() >= lb_iters and conval == lb:
690            return True
691         elif ub_iters > 0 and tree_node._num_iters_converged[variable_name][index]() >= ub_iters and conval == ub:
692            return True
693      # if we are still here, nothing triggered fixing
694      return False
695
696#=========================
697   def _should_fix_continuous_due_to_conv(self, tree_node, variable, index):
698
699      if self.fix_continuous_variables is True:
700         if self.FixWhenItersConvergedContinuous > 0 and tree_node._num_iters_converged[variable.name][index]() >= self.FixWhenItersConvergedContinuous:
701               return True
702
703      # if we are still here, nothing triggered fixing
704      return False   
705
706#=========================
707   def _slam(self, ph, tree_node, variable, index):
708      # this function returns a boolean indicating if it slammed
709      # TBD in the distant future: also: slam it to somewhere it sort of wants to go
710      # e.g., the anywhere case could be to the mode
711      #   or if more than one dest is True, pick the one closest to the average
712      #   as of sept 09, it is written with the implicit assumption that only one
713      #   destination is True or that if not, then min/max trumps lb/ub and anywhere trumps all
714     
715      fix_value = False  # assume the worst
716      variable_type = variable.domain
717      variable_name = variable.name
718      if isinstance(variable_type, IntegerSet) or isinstance(variable_type, BooleanSet):
719         node_min = self.Int_If_Close_Enough(ph, tree_node._minimums[variable_name][index]())
720         node_max = self.Int_If_Close_Enough(ph, tree_node._maximums[variable_name][index]())
721         anywhere = round(tree_node._averages[variable.name][index].value)
722      else:   
723         node_min = tree_node._minimums[variable_name][index]()
724         node_max = tree_node._maximums[variable_name][index]()
725         anywhere = tree_node._averages[variable.name][index].value
726
727      if self.CanSlamToLB is True: fix_value = variable[index].lb()
728      if self.CanSlamToMin is True: fix_value = node_min
729      if self.CanSlamToUB is True: fix_value = variable[index].ub()
730      if self.CanSlamToMax is True: fix_value = node_max
731      if self.CanSlamToAnywhere is True: fix_value = anywhere
732      if fix_value is False:
733         print "Warning: Not allowed to slam variable="+variable.name+str(index)+" at tree node="+tree_node._name
734         return False
735      else:
736         if index is None:
737            print "Slamming variable="+variable.name+" at tree node="+tree_node._name+" to value="+str(fix_value)
738         else:
739            print "Slamming variable="+variable.name+indexToString(index)+" at tree node="+tree_node._name+" to value="+str(fix_value)
740         self._fix_var(ph, tree_node, variable, index, fix_value)
741         return True
742
743#=========================
744   def _pick_one_and_slam_it(self, ph):
745
746      reference_instance = ph._model_instance
747
748      for vl in self.slam_list:
749         variable_string = str(vl)
750         full_index = None # JPW is not entirely sure of python scoping rules, so I'm declaring this outside of the if-then block.
751         variable_name = None
752         if isVariableNameIndexed(variable_string) is True:
753            pieces = variable_string.split('[')
754            variable_name = string.strip(pieces[0])
755            full_index = pieces[1].rstrip(']')
756            # the full_index is a string - tuplize it!
757            full_index = tupleizeIndexString(full_index)
758         else:
759            variable_name = variable_string
760            full_index = None
761
762         # verify that the root variable exists and grab it.
763         if variable_name not in reference_instance.active_components(Var).keys():
764            raise RuntimeError, "Unknown variable="+variable_name+" referenced while slamming. "
765         variable = reference_instance.active_components(Var)[variable_name]
766
767         didone = False;   # did we find at least one node to slam in?
768         # it is possible (even likely) that the slam list contains variable values that
769         # reside in the final stage - which, because of the initialization loops in
770         # the post_ph_initialization() method, will not have a _stage attribute defined.
771         # check for the presence of this attribute and skip if not present, as it
772         # doesn't make sense to slam variable values in the final stage anyway.
773         if hasattr(variable[full_index],'_stage') is True:
774            for tree_node in variable[full_index]._stage._tree_nodes:
775               # determine if the variable is already fixed (the trusting version...).
776               if tree_node._fixed_var_flag[variable_name][full_index].value is False:
777                  didone = self._slam(ph, tree_node, variable, full_index)
778            if didone:
779               self._last_slam_iter = ph._current_iteration
780               return
781         
782      print "Warning: Nothing free with a non-zero slam priority - no variable will be slammed"
783
784#==========================
785# a simple utility to fix any discrete variables to their common value, assuming they
786# are at a common value
787#==========================
788
789   def _fix_all_converged_discrete_variables(self, ph):
790
791      num_variables_fixed = 0
792
793      for stage in ph._scenario_tree._stages[:-1]: # no blending over the final stage
794         
795         for tree_node in stage._tree_nodes:
796
797            for (variable, index_template, variable_indices) in stage._variables:
798
799               variable_name = variable.name
800               variable_type = variable.domain
801
802               for index in variable_indices:
803
804                  # determine if this index is used - otherwise, don't waste time
805                  # fixing and cycle checking. for one, the code will crash :-) with
806                  # None values during the cycle checking computation!
807
808                  is_used = True # until proven otherwise                     
809                  for scenario in tree_node._scenarios:
810                     instance = ph._instances[scenario._name]
811                     if getattr(instance,variable_name)[index].status == VarStatus.unused:
812                        is_used = False
813
814                  if is_used is True:                       
815
816                     # determine if the variable is already fixed.
817                     instance_fixed_count = 0
818                     for scenario in tree_node._scenarios:
819                        instance = ph._instances[scenario._name]
820                        if getattr(instance,variable_name)[index].fixed is True:
821                           instance_fixed_count += 1
822                     if ((instance_fixed_count > 0) and (instance_fixed_count < len(tree_node._scenarios))):
823                        raise RuntimeError, "Variable="+variable_name+str(index)+" is fixed in "+str(instance_fixed_count)+" scenarios, but less than the number of scenarios at tree node="+tree_node._name
824
825                     if instance_fixed_count == 0:
826
827                        if isinstance(variable_type, IntegerSet) or isinstance(variable_type, BooleanSet):                           
828                           node_min = self.Int_If_Close_Enough(ph, tree_node._minimums[variable_name][index]())
829                           node_max = self.Int_If_Close_Enough(ph, tree_node._maximums[variable_name][index]())
830
831                           if node_min == node_max:
832                              self._fix_var(ph, tree_node, variable, index, node_min)
833                              num_variables_fixed = num_variables_fixed + 1
834
835      print "Total number of variables fixed at PH termination due to convergence="+str(num_variables_fixed)
Note: See TracBrowser for help on using the repository browser.