> 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/backpack-problem.md).

# Backpack Problem

## Imports and Setup

```python
from Finch.generic import Environment, Individual
from Finch.layers.universal_layers import Populate, SortByFitness, CapPopulation
from Finch.selectors import RankBasedSelection, RandomSelection
from Finch.layers.array_layers import ArrayPool, ParentNPoint, SwapMutation, ReplaceMutation, InversionMutation
import numpy as np

# Define the backpack problem parameters
items = [
    {"name": "Laptop", "weight": 3, "value": 10},
    {"name": "Headphones", "weight": 0.5, "value": 3},
    {"name": "Book", "weight": 1, "value": 1},
    {"name": "Water Bottle", "weight": 1, "value": 2},
    {"name": "Snacks", "weight": 0.5, "value": 1},
    {"name": "Camera", "weight": 2, "value": 4},
    {"name": "First Aid Kit", "weight": 1, "value": 9},
    {"name": "Jacket", "weight": 1, "value": 8},
    {"name": "Flashlight", "weight": 0.5, "value": 6},
    {"name": "Portable Charger", "weight": 0.5, "value": 5},
    {"name": "Smartphone", "weight": 0.3, "value": 9},
    {"name": "Tablet", "weight": 1, "value": 7},
    {"name": "Sunglasses", "weight": 0.2, "value": 2},
    {"name": "Umbrella", "weight": 1, "value": 3},
    {"name": "Hiking Boots", "weight": 2, "value": 6},
    {"name": "Tent", "weight": 4, "value": 8},
    {"name": "Sleeping Bag", "weight": 2, "value": 7},
    {"name": "Camping Stove", "weight": 1.5, "value": 5},
    {"name": "Map and Compass", "weight": 0.2, "value": 4},
    {"name": "Binoculars", "weight": 1, "value": 3},
    {"name": "Insect Repellent", "weight": 0.2, "value": 2},
    {"name": "Sunscreen", "weight": 0.3, "value": 2},
    {"name": "Multi-tool", "weight": 0.3, "value": 5},
    {"name": "Rope", "weight": 1, "value": 3},
    {"name": "Water Filter", "weight": 0.5, "value": 6},
    {"name": "Fire Starter", "weight": 0.1, "value": 4},
    {"name": "Emergency Whistle", "weight": 0.1, "value": 2},
    {"name": "Hammock", "weight": 1, "value": 4},
    {"name": "Solar Charger", "weight": 0.5, "value": 5},
    {"name": "Hand Sanitizer", "weight": 0.2, "value": 1}
]

MAX_WEIGHT = 7
```

Here, we import the necessary modules from the Finch library and NumPy. We define our list of items, each with a name, weight, and value. We also set the maximum weight capacity of the backpack.

### Fitness Function

```python
# Define the fitness function
def fitness_function(individual):
    total_weight = sum(items[i]["weight"] for i, gene in enumerate(individual.item) if gene)

    if total_weight > MAX_WEIGHT:
        return -1  # Penalty for exceeding weight limit
    total_value = sum(items[i]["value"] for i, gene in enumerate(individual.item) if gene)
    return total_value
```

The fitness function calculates the total value of items in the backpack. If the total weight exceeds the maximum capacity, it returns a penalty value of -1. This encourages the algorithm to find solutions within the weight limit.

### Gene Pool

```python
# Create the gene pool
pool = ArrayPool(gene_array=np.array([0, 1]), fitness_function=fitness_function, length=len(items))
```

We create an `ArrayPool` that will generate individuals with binary genes (0 or 1) representing whether an item is included in the backpack or not. The length of each individual is equal to the number of items.

### Layers

```python
# Define the layers
layers = [
    Populate(population=100, gene_pool=pool),
    SwapMutation(selection_function=RandomSelection(percent_to_select=0.05).select, overpowered=True),
    ParentNPoint(selection_function=RankBasedSelection(amount_to_select=2, factor=10).select, families=8, children=2,
                 n_points=5),
    SortByFitness(),
    CapPopulation(max_population=90)
]
```

We define the layers of our genetic algorithm:

1. `Populate`: Creates an initial population of 100 individuals.
2. `SwapMutation`: Mutates individuals by swapping genes. The `overpowered=True` parameter ensures that only beneficial mutations are kept.
3. `ParentNPoint`: Performs crossover between parents to create new children using 5 crossover points.
4. `SortByFitness`: Sorts the population based on fitness.
5. `CapPopulation`: Limits the population size to 90, allowing for new random individuals in each generation.

### Environment and Evolution

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

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

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

### Results

```python
# Get and print the best solution
best = env.best_ever
print("Best solution:")
total_weight = 0
total_value = 0
for i, gene in enumerate(best.item):
    if gene:
        print(f"- {items[i]['name']}")
        total_weight += items[i]['weight']
        total_value += items[i]['value']
print(f"Total weight: {total_weight}/{MAX_WEIGHT}")
print(f"Total value: {total_value}")

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

Finally, we print the best solution found, listing the items included in the backpack, their total weight, and total value. 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 the backpack problem using genetic algorithms. You can modify the items list, maximum weight, 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/backpack-problem.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.
