MCPcopy Index your code
hub / github.com/algorithmicsuperintelligence/openevolve / evolve_function

Function evolve_function

openevolve/api.py:314–433  ·  view source on GitHub ↗

Evolve a Python function based on test cases Args: func: Initial function to evolve test_cases: List of (input, expected_output) tuples iterations: Number of evolution iterations **kwargs: Additional arguments for run_evolution Returns: Evolutio

(
    func: Callable, test_cases: List[Tuple[Any, Any]], iterations: int = 100, **kwargs
)

Source from the content-addressed store, hash-verified

312
313
314def evolve_function(
315 func: Callable, test_cases: List[Tuple[Any, Any]], iterations: int = 100, **kwargs
316) -> EvolutionResult:
317 """
318 Evolve a Python function based on test cases
319
320 Args:
321 func: Initial function to evolve
322 test_cases: List of (input, expected_output) tuples
323 iterations: Number of evolution iterations
324 **kwargs: Additional arguments for run_evolution
325
326 Returns:
327 EvolutionResult with optimized function
328
329 Example:
330 def initial_sort(arr):
331 # Slow bubble sort
332 for i in range(len(arr)):
333 for j in range(len(arr)-1):
334 if arr[j] > arr[j+1]:
335 arr[j], arr[j+1] = arr[j+1], arr[j]
336 return arr
337
338 result = evolve_function(
339 initial_sort,
340 test_cases=[
341 ([3, 1, 2], [1, 2, 3]),
342 ([5, 2, 8, 1], [1, 2, 5, 8]),
343 ],
344 iterations=50
345 )
346 print(f"Optimized function score: {result.best_score}")
347 """
348
349 # Get function source code
350 func_source = inspect.getsource(func)
351 func_name = func.__name__
352
353 # Ensure the function source has evolution markers
354 if "EVOLVE-BLOCK-START" not in func_source:
355 # Try to add markers around the function body
356 lines = func_source.split("\n")
357 func_def_line = next(i for i, line in enumerate(lines) if line.strip().startswith("def "))
358
359 # Find the end of the function (simplified approach)
360 indent = len(lines[func_def_line]) - len(lines[func_def_line].lstrip())
361 func_end = len(lines)
362 for i in range(func_def_line + 1, len(lines)):
363 if lines[i].strip() and (len(lines[i]) - len(lines[i].lstrip())) <= indent:
364 func_end = i
365 break
366
367 # Insert evolution markers
368 lines.insert(func_def_line + 1, " " * (indent + 4) + "# EVOLVE-BLOCK-START")
369 lines.insert(func_end + 1, " " * (indent + 4) + "# EVOLVE-BLOCK-END")
370 func_source = "\n".join(lines)
371

Calls 1

run_evolutionFunction · 0.70