python:intvectorrange
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revision | Last revisionBoth sides next revision | ||
python:intvectorrange [2010/10/29 11:52] – tkbletsc | python:intvectorrange [2012/08/30 17:24] – tkbletsc | ||
---|---|---|---|
Line 67: | Line 67: | ||
+ | </ | ||
+ | |||
+ | This can be used to build a simple combinatorial optimizer: | ||
+ | < | ||
+ | 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, | ||
+ | # | ||
+ | # Example: | ||
+ | # def f(x,y,z): return x**2+x+5-y**3+z | ||
+ | # print optimize(f, x=Choice(range(-3, | ||
+ | # | ||
+ | # 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): | ||
+ | def optimize(func, | ||
+ | choices = dict((k,v) for k,v in vargs.items() if isinstance(v, | ||
+ | fixed_values = dict((k,v) for k,v in vargs.items() if not isinstance(v, | ||
+ | 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, | ||
+ | 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_inputs = c_values if return_choices_only else all_values | ||
+ | best_value = value | ||
+ | if print_on_better: | ||
+ | #print c_values | ||
+ | return (best_inputs, | ||
</ | </ |
python/intvectorrange.txt · Last modified: 2012/09/25 13:04 by tkbletsc