Utils

exception llamea.utils.NoCodeException

Bases: Exception

Could not extract generated code.

llamea.utils.apply_unified_diff(text: str, diff: str) str

Apply a unified diff to the given text using the system patch command.

This delegates all parsing and application logic to the external patch utility, which is far more robust than a hand-rolled parser. It handles context mismatches, fuzz factors, and edge cases like missing EOF newlines.

```text ┌─────────────┐ │ INPUT │ │ text:str │──┐ └─────────────┘ │

┌───────────┐ │ tempfile │ → holds original text └───────────┘

│ ▼

┌──────────────┐ │ patch cmd │ ← receives unified diff on stdin └──────────────┘

│ ▼

┌───────────┐ │ tempfile │ → now contains patched text └───────────┘

│ ▼

patched:str

```

Args:

text: The original text to patch. diff: The unified diff (as produced by git diff, difflib.unified_diff, etc.). strip: Optional -p value to pass to patch (number of path segments to strip).

Useful if the diff contains file paths you want ignored.

Returns:

The patched text as a string.

Raises:

subprocess.CalledProcessError: If patch fails and returns a nonzero exit code. FileNotFoundError: If patch is not installed.

llamea.utils.code_distance(a, b)

Return a rough distance between two solutions based on their ASTs.

The function accepts either Solution objects or raw code strings and computes 1 - similarity of their abstract syntax trees using difflib.SequenceMatcher on the dumped AST representations. 1.0 is returned on parsing errors or when the inputs cannot be processed.

Args:

a: The first solution or Python source code. b: The second solution or Python source code.

Returns:

float: A value in [0, 1] indicating dissimilarity of the code.

llamea.utils.discrete_power_law_distribution(n, beta)

Power law distribution function from: # Benjamin Doerr, Huu Phuoc Le, Régis Makhmara, and Ta Duy Nguyen. 2017. # Fast genetic algorithms. # In Proceedings of the Genetic and Evolutionary Computation Conference (GECCO ‘17). # Association for Computing Machinery, New York, NY, USA, 777–784. # https://doi.org/10.1145/3071178.3071301

llamea.utils.handle_timeout(signum, frame)

Raise a timeout exception