nodes: 0, module; 1, function_definition; 2, function_name:optimize; 3, parameters; 4, block; 5, identifier:self; 6, identifier:problem; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, default_parameter; 11, default_parameter; 12, default_parameter; 13, default_parameter; 14, expression_statement; 15, if_statement; 16, comment:# Prepare pool for multiprocessing; 17, if_statement; 18, comment:# Set first, incase optimizer uses _max_iterations in initialization; 19, expression_statement; 20, comment:# Initialize algorithm; 21, expression_statement; 22, expression_statement; 23, expression_statement; 24, try_statement; 25, return_statement; 26, identifier:max_iterations; 27, integer:100; 28, identifier:max_seconds; 29, call; 30, identifier:cache_encoded; 31, True; 32, identifier:cache_solution; 33, False; 34, identifier:clear_cache; 35, True; 36, identifier:logging_func; 37, identifier:_print_fitnesses; 38, identifier:n_processes; 39, integer:0; 40, comment:"""Find the optimal inputs for a given fitness function.
  
          Args:
              problem: An instance of Problem. The problem to solve.
              max_iterations: The number of iterations to optimize before stopping.
              max_seconds: Maximum number of seconds to optimize for, before stopping.
                  Note that condition is only checked one per iteration,
                  meaning optimization can take more than max_seconds,
                  especially if fitnesses take a long time to calculate.
              cache_encoded: bool; Whether or not to cache fitness of encoded strings.
                  Encoded strings are produced directly by the optimizer.
                  If an encoded string is found in cache, it will not be decoded.
              cache_solution: bool; Whether or not to cache fitness of decoded solutions.
                  Decoded solution is provided by problems decode function.
                  If problem does not provide a hash solution function,
                  Various naive hashing methods will be attempted, including:
                      tuple, tuple(sorted(dict.items)), str.
              clear_cache: bool; Whether or not to reset cache after optimization.
                  Disable if you want to run optimize multiple times on the same problem.
              logging_func: func/None; Function taking:
                  iteration, population, solutions, fitnesses, best_solution, best_fitness
                  Called after every iteration.
                  Use for custom logging, or set to None to disable logging.
                  Note that best_solution and best_fitness are the best of all iterations so far.
              n_processes: int; Number of processes to use for multiprocessing.
                  If <= 0, do not use multiprocessing.
  
          Returns:
              object; The best solution, after decoding.
          """; 41, not_operator; 42, block; 43, comparison_operator:n_processes > 0; 44, block; 45, else_clause; 46, assignment; 47, call; 48, assignment; 49, assignment; 50, comment:# Begin optimization loop; 51, block; 52, finally_clause; 53, attribute; 54, identifier:float; 55, argument_list; 56, call; 57, raise_statement; 58, identifier:n_processes; 59, integer:0; 60, try_statement; 61, block; 62, attribute; 63, identifier:max_iterations; 64, attribute; 65, argument_list; 66, identifier:best_solution; 67, dictionary; 68, identifier:population; 69, call; 70, expression_statement; 71, for_statement; 72, comment:# Store best internally, before returning; 73, expression_statement; 74, expression_statement; 75, comment:# Clear caches; 76, block; 77, identifier:self; 78, identifier:best_solution; 79, string; 80, identifier:isinstance; 81, argument_list; 82, call; 83, block; 84, except_clause; 85, expression_statement; 86, identifier:self; 87, identifier:__max_iterations; 88, identifier:self; 89, identifier:_reset; 90, pair; 91, pair; 92, attribute; 93, argument_list; 94, assignment; 95, attribute; 96, call; 97, comment:# Infinite sequence of iterations; 98, comment:# Evaluate potential solutions; 99, block; 100, assignment; 101, assignment; 102, if_statement; 103, comment:# Clean up multiprocesses; 104, try_statement; 105, string_content:inf; 106, identifier:problem; 107, identifier:Problem; 108, identifier:TypeError; 109, argument_list; 110, expression_statement; 111, identifier:NameError; 112, block; 113, assignment; 114, string; 115, None; 116, string; 117, None; 118, identifier:self; 119, identifier:initial_population; 120, identifier:start; 121, call; 122, identifier:self; 123, identifier:iteration; 124, attribute; 125, argument_list; 126, expression_statement; 127, comment:# If the best fitness from this iteration is better than; 128, comment:# the global best; 129, expression_statement; 130, if_statement; 131, if_statement; 132, comment:# Break if solution found; 133, if_statement; 134, comment:# Break if out of time; 135, if_statement; 136, comment:# Break if out of iterations; 137, if_statement; 138, comment:# Continue optimizing; 139, expression_statement; 140, attribute; 141, subscript; 142, attribute; 143, subscript; 144, identifier:clear_cache; 145, comment:# Clear caches from memory; 146, block; 147, block; 148, except_clause; 149, string; 150, assignment; 151, raise_statement; 152, identifier:pool; 153, None; 154, string_content:solution; 155, string_content:fitness; 156, attribute; 157, argument_list; 158, identifier:itertools; 159, identifier:count; 160, integer:1; 161, assignment; 162, assignment; 163, comparison_operator:best_fitness > best_solution['fitness']; 164, comment:# Store the new best solution; 165, block; 166, identifier:logging_func; 167, block; 168, identifier:finished; 169, block; 170, comparison_operator:time.clock() - start >= max_seconds; 171, block; 172, comparison_operator:self.iteration >= max_iterations; 173, block; 174, assignment; 175, identifier:self; 176, identifier:best_solution; 177, identifier:best_solution; 178, string; 179, identifier:self; 180, identifier:best_fitness; 181, identifier:best_solution; 182, string; 183, expression_statement; 184, expression_statement; 185, comment:# Reset encoded, and decoded key functions; 186, expression_statement; 187, expression_statement; 188, expression_statement; 189, comment:# Kill outstanding work; 190, expression_statement; 191, comment:# Close child processes; 192, identifier:AttributeError; 193, comment:# No pool; 194, block; 195, string_content:problem must be an instance of Problem class; 196, identifier:pool; 197, call; 198, call; 199, identifier:time; 200, identifier:clock; 201, pattern_list; 202, call; 203, pattern_list; 204, call; 205, identifier:best_fitness; 206, subscript; 207, expression_statement; 208, expression_statement; 209, expression_statement; 210, expression_statement; 211, break_statement; 212, binary_operator:time.clock() - start; 213, identifier:max_seconds; 214, break_statement; 215, attribute; 216, identifier:max_iterations; 217, break_statement; 218, identifier:population; 219, call; 220, string_content:solution; 221, string_content:fitness; 222, assignment; 223, assignment; 224, assignment; 225, assignment; 226, call; 227, call; 228, assert_statement; 229, attribute; 230, argument_list; 231, identifier:ImportError; 232, argument_list; 233, identifier:solutions; 234, identifier:fitnesses; 235, identifier:finished; 236, attribute; 237, argument_list; 238, identifier:best_index; 239, identifier:best_fitness; 240, identifier:max; 241, argument_list; 242, identifier:best_solution; 243, string; 244, assignment; 245, assignment; 246, call; 247, assignment; 248, call; 249, identifier:start; 250, identifier:self; 251, identifier:iteration; 252, attribute; 253, argument_list; 254, attribute; 255, dictionary; 256, attribute; 257, dictionary; 258, attribute; 259, attribute; 260, attribute; 261, attribute; 262, attribute; 263, argument_list; 264, attribute; 265, argument_list; 266, comparison_operator:pool is None; 267, identifier:multiprocessing; 268, identifier:Pool; 269, keyword_argument; 270, string; 271, identifier:self; 272, identifier:_get_fitnesses; 273, identifier:problem; 274, identifier:population; 275, keyword_argument; 276, keyword_argument; 277, keyword_argument; 278, call; 279, keyword_argument; 280, string_content:fitness; 281, subscript; 282, identifier:best_fitness; 283, subscript; 284, subscript; 285, identifier:logging_func; 286, argument_list; 287, attribute; 288, True; 289, attribute; 290, argument_list; 291, identifier:self; 292, identifier:next_population; 293, identifier:population; 294, identifier:fitnesses; 295, identifier:self; 296, identifier:__encoded_cache; 297, identifier:self; 298, identifier:__solution_cache; 299, identifier:self; 300, identifier:_get_encoded_key; 301, identifier:self; 302, identifier:_get_encoded_key_type; 303, identifier:self; 304, identifier:_get_solution_key; 305, identifier:self; 306, identifier:_get_solution_key_type; 307, identifier:pool; 308, identifier:terminate; 309, identifier:pool; 310, identifier:close; 311, identifier:pool; 312, None; 313, identifier:processes; 314, identifier:n_processes; 315, string_content:pickle, dill, or multiprocessing library is not available.; 316, identifier:cache_encoded; 317, identifier:cache_encoded; 318, identifier:cache_solution; 319, identifier:cache_solution; 320, identifier:pool; 321, identifier:pool; 322, identifier:enumerate; 323, argument_list; 324, identifier:key; 325, call; 326, identifier:best_solution; 327, string; 328, identifier:best_solution; 329, string; 330, identifier:solutions; 331, identifier:best_index; 332, attribute; 333, identifier:population; 334, identifier:solutions; 335, identifier:fitnesses; 336, subscript; 337, subscript; 338, identifier:self; 339, identifier:solution_found; 340, identifier:time; 341, identifier:clock; 342, identifier:fitnesses; 343, attribute; 344, argument_list; 345, string_content:fitness; 346, string_content:solution; 347, identifier:self; 348, identifier:iteration; 349, identifier:best_solution; 350, string; 351, identifier:best_solution; 352, string; 353, identifier:operator; 354, identifier:itemgetter; 355, integer:1; 356, string_content:solution; 357, string_content:fitness
code: def optimize(self, problem, max_iterations=100, max_seconds=float('inf'),
                   cache_encoded=True, cache_solution=False, clear_cache=True,
                   logging_func=_print_fitnesses,
                   n_processes=0):
          """Find the optimal inputs for a given fitness function.
  
          Args:
              problem: An instance of Problem. The problem to solve.
              max_iterations: The number of iterations to optimize before stopping.
              max_seconds: Maximum number of seconds to optimize for, before stopping.
                  Note that condition is only checked one per iteration,
                  meaning optimization can take more than max_seconds,
                  especially if fitnesses take a long time to calculate.
              cache_encoded: bool; Whether or not to cache fitness of encoded strings.
                  Encoded strings are produced directly by the optimizer.
                  If an encoded string is found in cache, it will not be decoded.
              cache_solution: bool; Whether or not to cache fitness of decoded solutions.
                  Decoded solution is provided by problems decode function.
                  If problem does not provide a hash solution function,
                  Various naive hashing methods will be attempted, including:
                      tuple, tuple(sorted(dict.items)), str.
              clear_cache: bool; Whether or not to reset cache after optimization.
                  Disable if you want to run optimize multiple times on the same problem.
              logging_func: func/None; Function taking:
                  iteration, population, solutions, fitnesses, best_solution, best_fitness
                  Called after every iteration.
                  Use for custom logging, or set to None to disable logging.
                  Note that best_solution and best_fitness are the best of all iterations so far.
              n_processes: int; Number of processes to use for multiprocessing.
                  If <= 0, do not use multiprocessing.
  
          Returns:
              object; The best solution, after decoding.
          """
          if not isinstance(problem, Problem):
              raise TypeError('problem must be an instance of Problem class')
  
          # Prepare pool for multiprocessing
          if n_processes > 0:
              try:
                  pool = multiprocessing.Pool(processes=n_processes)
              except NameError:
                  raise ImportError(
                      'pickle, dill, or multiprocessing library is not available.'
                  )
          else:
              pool = None
  
          # Set first, incase optimizer uses _max_iterations in initialization
          self.__max_iterations = max_iterations
  
          # Initialize algorithm
          self._reset()
  
          best_solution = {'solution': None, 'fitness': None}
          population = self.initial_population()
          try:
              # Begin optimization loop
              start = time.clock()
              for self.iteration in itertools.count(1):  # Infinite sequence of iterations
                  # Evaluate potential solutions
                  solutions, fitnesses, finished = self._get_fitnesses(
                      problem,
                      population,
                      cache_encoded=cache_encoded,
                      cache_solution=cache_solution,
                      pool=pool)
  
                  # If the best fitness from this iteration is better than
                  # the global best
                  best_index, best_fitness = max(
                      enumerate(fitnesses), key=operator.itemgetter(1))
                  if best_fitness > best_solution['fitness']:
                      # Store the new best solution
                      best_solution['fitness'] = best_fitness
                      best_solution['solution'] = solutions[best_index]
  
                  if logging_func:
                      logging_func(self.iteration, population, solutions,
                                   fitnesses, best_solution['solution'],
                                   best_solution['fitness'])
  
                  # Break if solution found
                  if finished:
                      self.solution_found = True
                      break
  
                  # Break if out of time
                  if time.clock() - start >= max_seconds:
                      break
  
                  # Break if out of iterations
                  if self.iteration >= max_iterations:
                      break
  
                  # Continue optimizing
                  population = self.next_population(population, fitnesses)
  
              # Store best internally, before returning
              self.best_solution = best_solution['solution']
              self.best_fitness = best_solution['fitness']
  
          finally:
              # Clear caches
              if clear_cache:
                  # Clear caches from memory
                  self.__encoded_cache = {}
                  self.__solution_cache = {}
  
                  # Reset encoded, and decoded key functions
                  self._get_encoded_key = self._get_encoded_key_type
                  self._get_solution_key = self._get_solution_key_type
  
              # Clean up multiprocesses
              try:
                  pool.terminate()  # Kill outstanding work
                  pool.close()  # Close child processes
              except AttributeError:
                  # No pool
                  assert pool is None
  
          return self.best_solution