User Tools

Site Tools


python:intvectorrange

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Last revisionBoth sides next revision
python:intvectorrange [2010/10/29 11:52] tkbletscpython:intvectorrange [2012/08/30 17:24] tkbletsc
Line 67: Line 67:
  
  
 +</code>
 +
 +This can be used to build a simple combinatorial optimizer:
 +<code=python>
 +import operator
 +
 +# Optimize the return value of the given function func(), comparing return values with the is_this_better() function (which defaults to greater-than).
 +# All parameters must be named parameters, and come after all other arguments. Options:
 +# - Print out the latest best answer if print_on_better is True
 +# - If return_choices_only is True, then the best_inputs part of the return will only have the choices, not the fixed values
 +# Returns the tuple: (best_inputs,best_value)
 +#
 +# Example:
 +#   def f(x,y,z): return x**2+x+5-y**3+z
 +#   print optimize(f, x=Choice(range(-3,5)), y=Choice(range(-3,5)), z=2)
 +
 +# This finds the best x and y to maximize f(x,y,z) with the given choices, with z fixed at 2.
 +class Choice(list): pass
 +def optimize(func, is_this_better=operator.gt, print_on_better=False, return_choices_only=False, **vargs):
 + choices = dict((k,v) for k,v in vargs.items() if isinstance(v,Choice))
 + fixed_values = dict((k,v) for k,v in vargs.items() if not isinstance(v,Choice))
 + c_keys = choices.keys()
 +
 + choice_max_indices = [len(choices[k])-1 for k in c_keys]
 +
 + best_value = None
 + best_inputs = None
 + for c_indices in IntVectorRange(choice_max_indices):
 + #print c_indices
 + c_values = dict((x,choices[x][c_indices[i]]) for i,x in enumerate(c_keys))
 + all_values = c_values.copy()
 + all_values.update(fixed_values)
 + value = func(**all_values)
 + if best_value is None or is_this_better(value,best_value):
 + best_inputs = c_values if return_choices_only else all_values
 + best_value = value
 + if print_on_better: print best_inputs,best_value
 + #print c_values
 + return (best_inputs,best_value)
 </code> </code>
python/intvectorrange.txt · Last modified: 2012/09/25 13:04 by tkbletsc

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki