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

Last change on this file since 2201 was 2201, checked in by wehart, 11 years ago

Update to Coopr to account for changes in PyUtilib? package names.

  • Property svn:executable set to *
File size: 49.9 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.component.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      self.ReportPotentialCycles = 0 # do I report potential cycles, i.e., those too short to base slamming on?
231
232      # end of parms
233
234      self._last_slam_iter = -1    # dynamic
235
236      # constants for W vector hashing (low cost rand() is all we need)
237      # note: July 09, dlw is planning to eschew pre-computed random vector
238      # another note: the top level reset is OK, but really it should
239      #   done way down at the index level with a serial number (stored)
240      #   to avoid correlated hash errors
241      # the hash seed was deleted in 1.1 and we seed with the
242      self.W_hash_seed = 17  # we will reset for dynamic rand vector generation
243      self.W_hash_rand_val = self.W_hash_seed # current rand
244      self.W_hash_a = 1317       # a,b, and c are for a simple generator
245      self.W_hash_b = 27699
246      self.W_hash_c = 131072  # that period should be usually long enough for us!
247                              # (assuming fewer than c scenarios)
248
249      # set up tree storage for statistics that we care about tracking.
250      for stage in ph._scenario_tree._stages:
251
252         if stage != ph._scenario_tree._stages[-1]:
253
254            # first, gather all unique variables referenced in self stage
255            # self "gather" step is currently required because we're being lazy
256            # in terms of index management in the scenario tree
257##            stage_variables = {}
258##            for (reference_variable, index_template, reference_index) in stage._variables:
259##               if reference_variable.name not in stage_variables.keys():
260##                  stage_variables[reference_variable.name] = reference_variable
261##
262            for tree_node in stage._tree_nodes:
263               tree_node._num_iters_converged = {}
264               tree_node._last_converged_val = {}
265               tree_node._w_hash = {}
266               tree_node._fixed_var_flag = {}
267
268               # next, create parameters for each variable in the corresponding tree node.
269
270               for (variable, index_template, variable_indices) in stage._variables:
271
272                  variable_name = variable.name
273                  variable_type = variable.domain
274                 
275                  for index in variable_indices:
276
277                     # IMPT: it has bitten us before in this plug-in, so I'll state the obvious:
278                     #       variable values in the last stage of a stochastic program will *not*
279                     #       have a defined _stage attribute.
280#                     print "dlw debug create stage association ",variable_name, index, stage._name                     
281                     variable[index]._stage = stage
282
283                     new_stat_index = variable._index
284                     new_stat_parameter_name = "NODESTAT_NUM_ITERS_CONVERGED_"+variable.name
285                     new_stat_parameter = None
286                     # this bit of ugliness is due to Pyomo not correctly handling the Param construction
287                     # case when the supplied index set consists strictly of None, i.e., the source variable
288                     # is a singleton. this case be cleaned up when the source issue in Pyomo is fixed.                     
289                     if (len(new_stat_index) is 1) and (None in new_stat_index):
290                        new_stat_parameter = Param(name=new_stat_parameter_name)
291                     else:
292                        new_stat_parameter = Param(new_stat_index,name=new_stat_parameter_name)
293                     for newindex in new_stat_index:
294                        new_stat_parameter[newindex] = 0
295                     tree_node._num_iters_converged[variable.name] = new_stat_parameter
296                     
297                     # need to know to what we have most recently converged
298                     new_conv_index = variable._index
299                     new_conv_parameter_name = "NODESTAT_LAST_CONVERGED_VAL_"+variable.name
300                     new_conv_parameter = None
301                     if (len(new_conv_index) is 1) and (None in new_conv_index):
302                        new_conv_parameter = Param(name=new_conv_parameter_name)
303                     else:
304                        new_conv_parameter = Param(new_conv_index,name=new_conv_parameter_name)
305                     for newindex in new_conv_index:
306                        new_conv_parameter[newindex] = 0.5 # not an int, so harmless
307                     tree_node._last_converged_val[variable.name] = new_conv_parameter
308                     
309                     # need to know to what has been fixed
310                     new_fix_index = variable._index
311                     new_fix_parameter_name = "NODESTAT_FIXED_FLAG_VAL_"+variable.name
312                     new_fix_parameter = None
313                     if (len(new_fix_index) is 1) and (None in new_fix_index):
314                        new_fix_parameter = Param(name=new_fix_parameter_name)
315                     else:
316                        new_fix_parameter = Param(new_fix_index,name=new_fix_parameter_name)
317                     for newindex in new_fix_index:
318                        new_fix_parameter[newindex] = False
319                     tree_node._fixed_var_flag[variable.name] = new_fix_parameter
320                     
321                     # now make the w hash value storage array
322                     new_hash_index = variable._index
323                     new_hash_parameter_name = "W_HASH_STORAGE_"+variable.name
324                     new_hash_parameter = None
325                     if (len(new_hash_index) is 1) and (None in new_hash_index):
326                        new_hash_parameter = Param(ph._iteration_index_set, name=new_hash_parameter_name)
327                     else:
328                        new_hash_parameter = Param(new_hash_index, ph._iteration_index_set, name=new_hash_parameter_name)
329                     for newindex in new_hash_index:
330                        for i in range(0, ph._max_iterations+1):
331                           # the following if-then block is a complete hack, due to the
332                           # fact that we can't index by None if the Param is unary.
333                           if new_hash_parameter.dim() == 1:
334                              new_hash_parameter[i] = 0
335                           else:
336                              new_hash_parameter[newindex,i] = 0
337                     tree_node._w_hash[variable.name] = new_hash_parameter
338
339      # store the total variable counts for future reporting.
340      (self.total_discrete_vars,self.total_continuous_vars) = ph.compute_variable_counts()
341
342      if self._configuration_filename is not None:
343         if os.path.exists(self._configuration_filename) is True:
344            print "WW PH Extension: Loading user-specified configuration from file=" + self._configuration_filename
345            execfile(self._configuration_filename)
346         else:
347            raise RuntimeError, "***WW PH Extension: Failed to load user-specified configuration from file="+self._configuration_filename
348      else:
349         print "WW PH Extension: No user-specified configuration file supplied - using defaults"
350
351      # process any suffix information, if it exists.
352      self.process_suffix_file(ph)         
353
354      # set up the mip gap for iteration 0.
355      if self.Iteration0MipGap > 0.0:
356         print "Setting mipgap to "+str(self.Iteration0MipGap)
357         ph._mipgap = self.Iteration0MipGap
358         
359#==================================================
360   def post_iteration_0_solves(self, ph):
361
362      for stage in ph._scenario_tree._stages:
363         
364         if stage != ph._scenario_tree._stages[-1]: # no blending over the final stage
365           
366            for tree_node in stage._tree_nodes:
367
368               for (variable, index_template, variable_indices) in stage._variables:
369                 
370                  variable_name = variable.name
371                  variable_type = variable.domain
372
373                  for index in variable_indices:
374
375                     # determine if this index is used - otherwise, don't waste time
376                     # fixing and cycle checking. for one, the code will crash :-) with
377                     # none values during the cycle checking computation!
378
379                     is_used = True # until proven otherwise                     
380                     for scenario in tree_node._scenarios:
381                        instance = ph._instances[scenario._name]
382                        if getattr(instance,variable_name)[index].status == VarStatus.unused:
383                           is_used = False
384
385                     if is_used is True:
386
387                        # unlikely, but variables might be fixed even at this stage, depending on
388                        # what weirdness users do prior to the iteration 0 solves.
389                        instance_fixed_count = 0
390                        for scenario in tree_node._scenarios:
391                           instance = ph._instances[scenario._name]
392                           if getattr(instance,variable_name)[index].fixed is True:
393                              instance_fixed_count += 1
394                        if ((instance_fixed_count > 0) and (instance_fixed_count < len(tree_node._scenarios))):
395                           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
396
397                        if instance_fixed_count == 0:
398
399                           if isinstance(variable_type, IntegerSet) or isinstance(variable_type, BooleanSet):                           
400                              node_min = self.Int_If_Close_Enough(ph, tree_node._minimums[variable_name][index]())
401                              node_max = self.Int_If_Close_Enough(ph, tree_node._maximums[variable_name][index]())
402
403                              # update convergence prior to checking for fixing.
404                              self._int_convergence_tracking(ph, tree_node, variable_name, index, node_min, node_max)
405                              attrvariable = ph._model_instance.active_components(Var)[variable_name][index]
406                              if hasattr(attrvariable, 'Iter0FixIfConvergedAtLB'):
407                                 lb = getattr(attrvariable, 'Iter0FixIfConvergedAtLB')
408                              else:
409                                 lb = self.Iter0FixIfConvergedAtLB
410                              if hasattr(attrvariable, 'Iter0FixIfConvergedatUB'):
411                                 ub = getattr(attrvariable, 'Iter0FixIfConvergedAtUB')
412                              else:
413                                 ub = self.Iter0FixIfConvergedAtUB
414                              if hasattr(attrvariable, 'Iter0FixIfConvergedAtNB'):
415                                 nb = getattr(attrvariable, 'Iter0FixIfConvergedAtNB')
416                              else:
417                                 nb = self.Iter0FixIfConvergedAtNB
418                              if self._should_fix_discrete_due_to_conv(tree_node, variable, index, lb, ub, nb):
419                                 self._fix_var(ph, tree_node, variable, index, node_min)
420                              elif self.W_hash_history_len > 0:   # if not fixed, then hash - no slamming at iteration 0
421                                 self._w_hash_acct(ph, tree_node, variable_name, index) # obviously not checking for cycles at iteration 0!
422
423                           else:
424                             
425                              node_min = tree_node._minimums[variable_name][index]()
426                              node_max = tree_node._maximums[variable_name][index]()
427                             
428                              self._continuous_convergence_tracking(ph, tree_node, variable_name, index, node_min, node_max)
429                             
430# jpw: not sure if we care about cycle detection in continuous variables?
431#                              if self.W_hash_history_len > 0: 
432#                                 self._w_hash_acct(ph, tree_node, variable_name, index)
433                             
434
435#==================================================
436   def post_iteration_0(self, ph):
437 
438      self._met0 = ph._converger.lastMetric()
439
440      if (self.InitialMipGap > 0) and (self.FinalMipGap >= 0) and (self.InitialMipGap > self.FinalMipGap):
441         gap = self.InitialMipGap
442         print "Setting mipgap to "+str(gap)
443         ph._mipgap = gap
444
445#==================================================         
446
447   def pre_iteration_k_solves(self, ph):
448        """ Called immediately before the iteration k solves!"""
449        # we don't muck with the PH objectives
450        pass
451
452#==================================================
453   def post_iteration_k_solves(self, ph):
454
455      for stage in ph._scenario_tree._stages:
456         
457         if stage != ph._scenario_tree._stages[-1]: # no blending over the final stage
458           
459            for tree_node in stage._tree_nodes:
460
461               for (variable, index_template, variable_indices) in stage._variables:
462
463                  variable_name = variable.name
464                  variable_type = variable.domain
465
466                  for index in variable_indices:
467
468                     # determine if this index is used - otherwise, don't waste time
469                     # fixing and cycle checking. for one, the code will crash :-) with
470                     # None values during the cycle checking computation!
471
472                     is_used = True # until proven otherwise                     
473                     for scenario in tree_node._scenarios:
474                        instance = ph._instances[scenario._name]
475                        if getattr(instance,variable_name)[index].status == VarStatus.unused:
476                           is_used = False
477
478                     if is_used is True:                       
479
480                        # determine if the variable is already fixed.
481                        instance_fixed_count = 0
482                        for scenario in tree_node._scenarios:
483                           instance = ph._instances[scenario._name]
484                           if getattr(instance,variable_name)[index].fixed is True:
485                              instance_fixed_count += 1
486                        if ((instance_fixed_count > 0) and (instance_fixed_count < len(tree_node._scenarios))):
487                           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
488
489                        if instance_fixed_count == 0:
490
491                           if isinstance(variable_type, IntegerSet) or isinstance(variable_type, BooleanSet):                           
492                              node_min = self.Int_If_Close_Enough(ph, tree_node._minimums[variable_name][index]())
493                              node_max = self.Int_If_Close_Enough(ph, tree_node._maximums[variable_name][index]())
494
495                              # update convergence prior to checking for fixing.
496                              self._int_convergence_tracking(ph, tree_node, variable_name, index, node_min, node_max)
497
498                              # now check on permissions to converge to various placed (e.g., lb is lb permission)
499                              attrvariable = ph._model_instance.active_components(Var)[variable_name][index]
500                              if hasattr(attrvariable, 'FixWhenItersConvergedAtLB'):
501                                 lb = getattr(attrvariable, 'FixWhenItersConvergedAtLB')
502                              else:
503                                 lb = self.FixWhenItersConvergedAtLB
504                              if hasattr(attrvariable, 'FixWhenItersConvergedAtUB'):
505                                 ub = getattr(attrvariable, 'FixWhenItersConvergedAtUB')
506                              else:
507                                 ub = self.FixWhenItersConvergedAtUB
508                              if hasattr(attrvariable, 'FixWhenItersConvergedAtNB'):
509                                 nb = getattr(attrvariable, 'FixWhenItersConvergedAtNB')
510                              else:
511                                 nb = self.FixWhenItersConvergedAtNB
512                                 
513                              if self._should_fix_discrete_due_to_conv(tree_node, variable, index, lb, ub, nb):
514                                 
515                                 self._fix_var(ph, tree_node, variable, index, node_min)
516                                 
517                              else: # if not fixed, then hash and slam as necessary.
518                                 
519                                 if self.W_hash_history_len > 0:   
520                                    self._w_hash_acct(ph, tree_node, variable_name, index)
521                                    computed_cycle_length,msg = self.hash_hit_len(ph, tree_node, variable_name, index, False)
522                                    if (computed_cycle_length >= self.CycleLengthSlamThreshold) and ((ph._current_iteration - self._last_slam_iter) > self.PH_Iters_Between_Cycle_Slams):
523                                       # 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.
524                                       # note: we are *not* slamming the offending variable, but a selected variable
525                                       if index is None:
526                                          print "Cycle issue detected with variable="+variable_name
527                                       else:
528                                          print "Cycle issue detected with variable="+variable_name+"["+str(index)+"]"
529                                       print msg
530                                       print "Cycle length exceeds iteration slamming threshold="+str(self.CycleLengthSlamThreshold)+"; choosing a variable to slam"
531                                       self._pick_one_and_slam_it(ph)
532                                    elif (computed_cycle_length > 1) and (computed_cycle_length < self.CycleLengthSlamThreshold):
533                                       # there was a (potential) cycle, but the slam threshold wasn't reached.
534                                       if self.ReportPotentialCycles is True:
535                                          if index is None:
536                                             print "Cycle issue detected with variable="+variable_name
537                                          else:                                         
538                                             print "Cycle issue detected with variable="+variable_name+"["+str(index)+"]"                                         
539                                          print msg
540                                          print "Taking no action to break cycle - length="+str(computed_cycle_length)+" does not exceed slam threshold="+str(self.CycleLengthSlamThreshold)
541                                    elif (computed_cycle_length >= self.CycleLengthSlamThreshold) and ((ph._current_iteration - self._last_slam_iter) > self.PH_Iters_Between_Cycle_Slams):
542                                       # we could have slammed, but we recently did and are taking a break to see if things settle down on their own.
543                                       if index is None:
544                                          print "Cycle issue detected with variable="+variable_name
545                                       else:                                         
546                                          print "Cycle issue detected with variable="+variable_name+"["+str(index)+"]"                                         
547                                       print msg
548                                       print "Taking no action to break cycle - length="+str(computed_cycle_length)+" does exceed slam threshold="+str(self.CycleLengthSlamThreshold)+ \
549                                             ", but another variable was slammed within the past "+str(self.PH_Iters_Between_Cycle_Slams)+" iterations" 
550                           else:
551
552                              # obviously don't round in the continuous case.
553                              node_min = tree_node._minimums[variable_name][index]()
554                              node_max = tree_node._maximums[variable_name][index]()
555
556                              # update convergence prior to checking for fixing.
557                              self._continuous_convergence_tracking(ph, tree_node, variable_name, index, node_min, node_max)
558
559                              if self._should_fix_continuous_due_to_conv(tree_node, variable, index):
560                                 # fixing to max value for safety (could only be an issue due to tolerances).
561                                 self._fix_var(ph, tree_node, variable, index, node_max)
562                                 # note: we currently don't clam continuous variables!
563
564      # TBD: the 1 might need to be parameterized - TBD - the 1 should be the PH ITERATIONS BETWEEN CYCLE SLAMS
565      if (ph._current_iteration > self.SlamAfterIter) and \
566         ((ph._current_iteration - self._last_slam_iter) > self.PH_Iters_Between_Cycle_Slams) and \
567         (ph._converger.isImproving(self.PH_Iters_Between_Cycle_Slams)):
568         print "Slamming criteria are satisifed - accelerating convergence"
569         self._pick_one_and_slam_it(ph)
570         self._just_slammed_ = True
571      else:
572         self._just_slammed_ = False
573     
574#==================================================
575   def post_iteration_k(self, ph):
576
577      # note: we are lagging one iteration
578      # linear
579      if (self.InitialMipGap > 0 and self.FinalMipGap >= 0) and self.InitialMipGap > self.FinalMipGap:
580         m0 = self._met0
581         m = ph._converger.lastMetric()
582         mlast = ph._converger._convergence_threshold
583         g0 = self.InitialMipGap
584         glast = self.FinalMipGap
585         gap = ((m-m0)/(m0-mlast) + g0/(g0-glast))* (g0-glast)
586         if gap > g0:
587            print "***WARNING: Setting mipgap to thresholded maximal initial mapgap value="+str(g0)+"; unthresholded value="+str(gap)           
588            gap = g0
589         else:
590            print "Setting mipgap to "+str(gap)
591         ph._mipgap = gap
592
593
594#==================================================
595   def post_ph_execution(self, ph):
596
597      if self.fix_discrete_variables_at_exit is True:
598         print "WW PH extension: Fixing all discrete variables that are converged at termination"
599         self._fix_all_converged_discrete_variables(ph)
600
601#=========================
602   def Int_If_Close_Enough(self, ph, x):
603       # if x is close enough to the nearest integer, return the integer
604       # else return x
605       if abs(round(x)-x) <= ph._integer_tolerance:
606          return int(round(x))
607       else:
608          return x
609
610#=========================   
611   def _int_convergence_tracking(self, ph, tree_node, variable_name, index, node_min, node_max):
612       # keep track of cumulative iters of convergence to the same int
613       if (node_min == node_max) and (type(node_min) is types.IntType): 
614          if node_min == tree_node._last_converged_val[variable_name][index]():
615             tree_node._num_iters_converged[variable_name][index].value = tree_node._num_iters_converged[variable_name][index].value + 1
616          else:
617             tree_node._num_iters_converged[variable_name][index].value = 1
618             tree_node._last_converged_val[variable_name][index] = node_min
619       else:
620          tree_node._num_iters_converged[variable_name][index].value = 0
621          tree_node._last_converged_val[variable_name][index].value = 0.5 
622
623#=========================   
624   def _continuous_convergence_tracking(self, ph, tree_node, variable_name, index, node_min, node_max):
625       # keep track of cumulative iters of convergence to the same value within tolerance.
626       if abs(node_max - node_min) <= ph._integer_tolerance:
627          if abs(node_min - tree_node._last_converged_val[variable_name][index]()) <= ph._integer_tolerance:
628             tree_node._num_iters_converged[variable_name][index].value  = tree_node._num_iters_converged[variable_name][index].value + 1
629          else:
630             tree_node._num_iters_converged[variable_name][index].value = 1
631             tree_node._last_converged_val[variable_name][index] = node_min
632       else:
633          tree_node._num_iters_converged[variable_name][index].value = 0
634          tree_node._last_converged_val[variable_name][index] = 0.2342343243223423 # TBD - avoid the magic constant!
635
636#=========================         
637   def _w_hash_acct(self, ph, tree_node, variable_name, index):
638      # do the w hash accounting work
639      # we hash on the variable ph weights, and not the values; the latter may not shift for some time, while the former should.
640      self.W_hash_rand_val = self.W_hash_seed
641      for scenario in tree_node._scenarios:
642         instance = ph._instances[scenario._name]
643         weight_parameter_name = "PHWEIGHT_"+variable_name
644         if index is None:
645            tree_node._w_hash[variable_name][ph._current_iteration].value += getattr(instance,weight_parameter_name)[index].value * self.W_hash_rand_val
646         else:
647            tree_node._w_hash[variable_name][index,ph._current_iteration].value += getattr(instance,weight_parameter_name)[index].value * self.W_hash_rand_val
648         self.W_hash_rand_val = (self.W_hash_b + self.W_hash_a * self.W_hash_rand_val) % self.W_hash_c
649
650#=========================
651   def dump_w_hash(self, ph, tree_node, stage):
652       # debug code
653      print "Stage=",stage._name," tree node=",tree_node._name
654      print "PH Iteration      Variable                          PH Weight Hash Value"
655      for (variable, index_template, variable_indices) in stage._variables:
656
657          variable_name = variable.name
658          variable_type = variable.domain
659
660          # TBD - should we cycle-detect on continuous vars?
661          if isinstance(variable_type, IntegerSet) or isinstance(variable_type, BooleanSet):
662             for index in variable_index:
663                if index is None:
664                   print "%4d        %50ls %20.5f" % (ph._current_iteration, tree_node._w_hash[variable_name][ph._current_iteration], tree_node._w_hash[variable_name][ph._current_iteration]())
665                else:
666                   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]())
667                                                                                                                           
668#=========================
669   def hash_hit_len(self, ph, tree_node, variable_name, index, report_possible_cycles):
670      # return cycles back to closest hash hit for hashval or 0 if no hash hit
671
672      # if the values are converged, then don't report a cycle - often, the weights at convergence are 0s, and even
673      # if they aren't, they won't move if the values are uniform.
674      if (tree_node._num_iters_converged[variable_name][index].value == 0) and (tree_node._fixed_var_flag[variable_name][index].value is False):
675         current_hash_value = None
676         if index is None:
677            current_hash_value = tree_node._w_hash[variable_name][ph._current_iteration]()
678         else:
679            current_hash_value = tree_node._w_hash[variable_name][index,ph._current_iteration]()
680         # scan starting from the farthest point back in history to the closest - this is required to
681         # identify the longest possible cycles, which is what we want.
682         for i in range(max(ph._current_iteration - self.W_hash_history_len - 1, 1), ph._current_iteration - 1, 1):
683             this_hash_value = None
684             if index is None:
685                this_hash_value = tree_node._w_hash[variable_name][i]()
686             else:
687                this_hash_value = tree_node._w_hash[variable_name][index,i]()
688             if abs(this_hash_value - current_hash_value) <= ph._integer_tolerance:
689                if report_possible_cycles is True:
690                   if index is None:
691                      print "Possible cycle detected via PH weight hashing - variable="+variable_name+", node="+tree_node._name
692                   else:
693                      print "Possible cycle detected via PH weight hashing - variable="+variable_name+indexToString(index)+" node="+ tree_node._name
694                msg = "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)
695                return ph._current_iteration - i, msg
696      return 0, ""
697
698#=========================
699   def _fix_var(self, ph, tree_node, variable, index, fix_value):
700       # fix the variable, account for it and maybe output some trace information
701       # note: whether you fix at current values or not can severly impact feasibility later
702       # in the game. my original thought was below - but that didn't work out. if you
703       # make integers, well, integers, all appears to be well.
704       # IMPT: we are leaving the values for individual variables alone, at potentially
705       #       smallish and heterogeneous values. if we fix/round, we run the risk of
706       #       infeasibilities due to numerical issues. the computed value below is
707       #       strictly for output purposes. dlw note: as of aug 1 '09,
708       #       node_min and node_max should be
709       #       int if they should be (so to speak)
710
711       fixing_reported = False # to track whether you have already output the fix message for one scenario.
712
713       for scenario in tree_node._scenarios:
714
715          instance = ph._instances[scenario._name]
716                       
717          getattr(instance,variable.name)[index].fixed = True
718          getattr(instance,variable.name)[index].value = fix_value
719          tree_node._fixed_var_flag[variable.name][index].value = True
720
721          variable_type = variable.domain         
722
723          if fixing_reported is False:
724             # pretty-print the index, string the trailing spaces from the strings.
725             if index is None:
726                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"
727             else:
728                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"               
729             fixing_reported = True
730             if isinstance(variable_type, IntegerSet) or isinstance(variable_type, BooleanSet):
731                self.cumulative_discrete_fixed_count = self.cumulative_discrete_fixed_count + 1
732             else:
733                self.cumulative_continuous_fixed_count = self.cumulative_continuous_fixed_count + 1                                                           
734
735#=========================
736   # the last 3 input arguments are the number of iterations the variable is required to
737   # be at the respective bound (or lack thereof) before fixing can be initiated.
738   def _should_fix_discrete_due_to_conv(self, tree_node, variable, index, lb_iters, ub_iters, nb_iters):
739      # return True if this should be fixed due to convergence
740      variable_name = variable.name
741
742      # 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!
743      # dlw reply: i meant it to mean "without regard to bound" so i have updated the document
744      if nb_iters > 0 and tree_node._num_iters_converged[variable_name][index]() >= nb_iters:
745            return True
746      else:
747         # there is a possibility that the variable doesn't have a bound specified, in which
748         # case we should obviously ignore the corresponding lb_iters/ub_iters/nb_iters - which
749         # should be none as well!
750         lb = None
751         ub = None
752         if variable[index].lb is not None:
753            lb = variable[index].lb()
754         if variable[index].ub is not None:
755            ub = variable[index].ub()
756         conval = tree_node._last_converged_val[variable_name][index]()
757         # note: if they are converged node_max == node_min
758         if (lb is not None) and (lb_iters > 0) and (tree_node._num_iters_converged[variable_name][index]() >= lb_iters) and (conval == lb):
759            return True
760         elif (ub is not None) and (ub_iters > 0) and (tree_node._num_iters_converged[variable_name][index]() >= ub_iters) and (conval == ub):
761            return True
762      # if we are still here, nothing triggered fixing
763      return False
764
765#=========================
766   def _should_fix_continuous_due_to_conv(self, tree_node, variable, index):
767
768      if self.fix_continuous_variables is True:
769         if self.FixWhenItersConvergedContinuous > 0 and tree_node._num_iters_converged[variable.name][index]() >= self.FixWhenItersConvergedContinuous:
770               return True
771
772      # if we are still here, nothing triggered fixing
773      return False   
774
775#=========================
776   def _slam(self, ph, tree_node, variable, index):
777      # this function returns a boolean indicating if it slammed
778      # TBD in the distant future: also: slam it to somewhere it sort of wants to go
779      # e.g., the anywhere case could be to the mode
780      #   or if more than one dest is True, pick the one closest to the average
781      #   as of sept 09, it is written with the implicit assumption that only one
782      #   destination is True or that if not, then min/max trumps lb/ub and anywhere trumps all
783     
784      fix_value = False  # assume the worst
785      variable_type = variable.domain
786      variable_name = variable.name
787      if isinstance(variable_type, IntegerSet) or isinstance(variable_type, BooleanSet):
788         node_min = self.Int_If_Close_Enough(ph, tree_node._minimums[variable_name][index]())
789         node_max = self.Int_If_Close_Enough(ph, tree_node._maximums[variable_name][index]())
790         anywhere = round(tree_node._averages[variable.name][index].value)
791      else:   
792         node_min = tree_node._minimums[variable_name][index]()
793         node_max = tree_node._maximums[variable_name][index]()
794         anywhere = tree_node._averages[variable.name][index].value
795
796      slam_basis_string = ""
797      if self.CanSlamToLB is True:
798         fix_value = variable[index].lb()
799         slam_basis_string = "lower bound"
800      if self.CanSlamToMin is True:
801         fix_value = node_min
802         slam_basis_string = "node minimum"
803      if self.CanSlamToUB is True:
804         fix_value = variable[index].ub()
805         slam_basis_string = "upper bound"
806      if self.CanSlamToMax is True:
807         fix_value = node_max
808         slam_basis_string = "node maximum"
809      if self.CanSlamToAnywhere is True:
810         fix_value = anywhere
811         slam_basis_string = "node average (anywhere)"
812      if fix_value is False:
813         print "Warning: Not allowed to slam variable="+variable.name+str(index)+" at tree node="+tree_node._name
814         return False
815      else:
816         if index is None:
817            print "Slamming variable="+variable.name+" at tree node="+tree_node._name+" to value="+str(fix_value)+"; value="+slam_basis_string
818         else:
819            print "Slamming variable="+variable.name+indexToString(index)+" at tree node="+tree_node._name+" to value="+str(fix_value)+"; value="+slam_basis_string
820         self._fix_var(ph, tree_node, variable, index, fix_value)
821         return True
822
823#=========================
824   def _pick_one_and_slam_it(self, ph):
825
826      reference_instance = ph._model_instance
827
828      for vl in self.slam_list:
829         variable_string = str(vl)
830         full_index = None # JPW is not entirely sure of python scoping rules, so I'm declaring this outside of the if-then block.
831         variable_name = None
832         if isVariableNameIndexed(variable_string) is True:
833            pieces = variable_string.split('[')
834            variable_name = string.strip(pieces[0])
835            full_index = pieces[1].rstrip(']')
836            # the full_index is a string - tuplize it!
837            full_index = tupleizeIndexString(full_index)
838         else:
839            variable_name = variable_string
840            full_index = None
841
842         # verify that the root variable exists and grab it.
843         if variable_name not in reference_instance.active_components(Var).keys():
844            raise RuntimeError, "Unknown variable="+variable_name+" referenced while slamming. "
845         variable = reference_instance.active_components(Var)[variable_name]
846
847         didone = False;   # did we find at least one node to slam in?
848         # it is possible (even likely) that the slam list contains variable values that
849         # reside in the final stage - which, because of the initialization loops in
850         # the post_ph_initialization() method, will not have a _stage attribute defined.
851         # check for the presence of this attribute and skip if not present, as it
852         # doesn't make sense to slam variable values in the final stage anyway.
853         if hasattr(variable[full_index],'_stage') is True:
854            for tree_node in variable[full_index]._stage._tree_nodes:
855               # determine if the variable is already fixed (the trusting version...).
856               if tree_node._fixed_var_flag[variable_name][full_index].value is False:
857                  didone = self._slam(ph, tree_node, variable, full_index)
858            if didone:
859               self._last_slam_iter = ph._current_iteration
860               return
861         
862      print "Warning: Nothing free with a non-zero slam priority - no variable will be slammed"
863
864#==========================
865# a simple utility to fix any discrete variables to their common value, assuming they
866# are at a common value
867#==========================
868
869   def _fix_all_converged_discrete_variables(self, ph):
870
871      num_variables_fixed = 0
872
873      for stage in ph._scenario_tree._stages[:-1]: # no blending over the final stage
874         
875         for tree_node in stage._tree_nodes:
876
877            for (variable, index_template, variable_indices) in stage._variables:
878
879               variable_name = variable.name
880               variable_type = variable.domain
881
882               for index in variable_indices:
883
884                  # determine if this index is used - otherwise, don't waste time
885                  # fixing and cycle checking. for one, the code will crash :-) with
886                  # None values during the cycle checking computation!
887
888                  is_used = True # until proven otherwise                     
889                  for scenario in tree_node._scenarios:
890                     instance = ph._instances[scenario._name]
891                     if getattr(instance,variable_name)[index].status == VarStatus.unused:
892                        is_used = False
893
894                  if is_used is True:                       
895
896                     # determine if the variable is already fixed.
897                     instance_fixed_count = 0
898                     for scenario in tree_node._scenarios:
899                        instance = ph._instances[scenario._name]
900                        if getattr(instance,variable_name)[index].fixed is True:
901                           instance_fixed_count += 1
902                     if ((instance_fixed_count > 0) and (instance_fixed_count < len(tree_node._scenarios))):
903                        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
904
905                     if instance_fixed_count == 0:
906
907                        if isinstance(variable_type, IntegerSet) or isinstance(variable_type, BooleanSet):                           
908                           node_min = self.Int_If_Close_Enough(ph, tree_node._minimums[variable_name][index]())
909                           node_max = self.Int_If_Close_Enough(ph, tree_node._maximums[variable_name][index]())
910
911                           if node_min == node_max:
912                              self._fix_var(ph, tree_node, variable, index, node_min)
913                              num_variables_fixed = num_variables_fixed + 1
914
915      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.