> For the complete documentation index, see [llms.txt](https://finch-1.gitbook.io/version0.0.1/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://finch-1.gitbook.io/version0.0.1/examples/evolve-strings.md).

# Evolve Strings

## String Evolution Example

### Imports and Setup

<pre class="language-python"><code class="lang-python">from Finch.generic import Environment, Individual
from Finch.layers.universal_layers import Populate, SortByFitness, CapPopulation
from Finch.selectors import RandomSelection, RankBasedSelection
from Finch.layers.array_layers import ParentNPoint, InsertionDeletionMutation, ArrayPool, SwapMutation
<strong>from difflib import SequenceMatcher
</strong>import string

# Define the target sentence
TARGET = "genetic algos are lit"

# Define the character set (lowercase letters and space)
CHAR_SET = string.ascii_lowercase + " "
</code></pre>

Here, we import the necessary modules from the Finch library and other required libraries. We define our target string and the character set that will be used to generate and evolve our strings.

### Fitness Function

```python
# Define the fitness function
def fitness_function(individual):
    return SequenceMatcher(None, TARGET, ''.join(individual.item)).ratio() * 100
```

The fitness function calculates how similar an individual's string is to the target string. It uses the `SequenceMatcher` from the `difflib` module to compute the similarity ratio and returns a percentage.

### Gene Pool

```python
# Create the gene pool
pool = ArrayPool(gene_array=list(CHAR_SET), fitness_function=fitness_function, length=len(TARGET))
```

We create an `ArrayPool` that will generate individuals with genes (characters) from our `CHAR_SET`. Each individual will have a length equal to the target string.

### Layers

```python
# Define the layers
layers = [
    Populate(population=100, gene_pool=pool),
    ParentNPoint(selection_function=RankBasedSelection(amount_to_select=2, factor=2).select, families=8, children=2, refit=True),
    InsertionDeletionMutation(selection_function=RandomSelection(percent_to_select=0.2).select, overpowered=True, refit=False),
    SwapMutation(selection_function=RandomSelection(percent_to_select=0.2).select, overpowered=True, refit=False),
    SortByFitness(),
    CapPopulation(max_population=99)
]
```

We define the layers of our genetic algorithm:

1. `Populate`: Creates an initial population of 100 individuals.
2. `ParentNPoint`: Performs crossover between parents to create new children.
3. `InsertionDeletionMutation`: Mutates individuals by inserting or deleting characters.
4. `SwapMutation`: Mutates individuals by swapping characters.
5. `SortByFitness`: Sorts the population based on fitness.
6. `CapPopulation`: Limits the population size to 99, allowing for one new random individual in each generation.

### Environment and Evolution

```python
# Create the environment
env = Environment(layers=layers, verbose_every=10)

# Compile the environment
env.compile()

# Evolve the population
env.evolve(generations=2000)
```

We create an `Environment` with our defined layers, compile it, and then evolve the population for 2000 generations.

### Results

```python
# Print the best individual
best = env.best_ever
print(f"Best solution: '{''.join(best.item)}'")
print(f"Fitness: {best.fitness}")

# Plot the fitness history
env.plot()
```

Finally, we print the best solution found and its fitness score. The `env.plot()` function will display a graph showing how the fitness of the population improved over generations.

This example demonstrates how to use Finch to solve a string evolution problem. You can modify the target string, character set, population size, number of generations, and other parameters to experiment with different scenarios.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://finch-1.gitbook.io/version0.0.1/examples/evolve-strings.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
