Skip to content

Commit 886a620

Browse files
committed
Adding GA docs
1 parent d7e64cb commit 886a620

1 file changed

Lines changed: 123 additions & 6 deletions

File tree

docs/single/gen.md

Lines changed: 123 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,128 @@
1-
## Fitness Function
1+
# 🚦TLS Optimization using Genetic Algorithm
22

3+
The optimization minimizes the **average vehicle waiting time** and **queue length**, while maximizing **throughput**.
4+
5+
6+
## What is a Genetic Algorithm (GA)?
7+
8+
A **Genetic Algorithm** is an optimization method inspired by **natural evolution**.
9+
It works by evolving a population of possible solutions over several generations to find the best one.
10+
11+
### GA Core Steps:
12+
1. **Initialization**–Generate a random population of solutions.
13+
2. **Evaluation**–Measure fitness (performance) of each solution.
14+
3. **Selection**–Choose the best-performing individuals.
15+
4. **Crossover**–Combine parts of two solutions to create offspring.
16+
5. **Mutation**–Randomly alter some parts to maintain diversity.
17+
6. **Iteration**–Repeat until reaching a desired number of generations or convergence.
18+
19+
---
20+
21+
## Project Files
22+
23+
| File | Description |
24+
|------|--------------|
25+
| `gen.net.xml` | Road network for the intersection |
26+
| `gen.add.xml` | Additional network elements (e.g., detectors) |
27+
| `gen.rou.xml` | Vehicle route definitions |
28+
| `gen.py` | Main optimization script |
29+
30+
---
31+
32+
## Algorithm Summary
33+
34+
### Parameters
335
```python
4-
avg_wait = total_wait / vehicle_count
5-
queue_penalty = total_queue / SIM_STEPS
6-
throughput_bonus = throughput / SIM_STEPS
36+
POP_SIZE = 8 # Number of solutions per generation
37+
N_GENERATIONS = 10 # Number of generations
38+
MUTATION_RATE = 0.2 # Probability of mutation
39+
CROSSOVER_RATE = 0.7 # Probability of crossover
40+
GREEN_MIN, GREEN_MAX = 10, 60
41+
YELLOW_MIN, YELLOW_MAX = 2, 5
42+
SIM_STEPS = 2000 # Number of simulation steps per run
43+
```
44+
45+
### Fitness Function
46+
The **fitness** evaluates how effective a given signal plan is:
47+
48+
```python
49+
fitness = avg_wait + 0.5 * queue_penalty - 0.2 * throughput_bonus
50+
```
51+
52+
- **avg_wait:** average vehicle waiting time (lower is better)
53+
- **queue_penalty:** total halting vehicles over time
54+
- **throughput_bonus:** number of vehicles that successfully left the network
55+
56+
The **goal** is to **minimize** the fitness value.
57+
58+
---
59+
60+
## Code Structure
761

8-
fitness = avg_wait + 0.5 * queue_penalty - 0.2 * throughput_bonus
62+
### Run SUMO Simulation
63+
```python
64+
def run_simulation(phase_durations):
65+
# Launch SUMO with the specified network and route files
66+
traci.start([...])
67+
# Modify traffic light program phases
68+
# Run the simulation for SIM_STEPS and record stats
69+
...
70+
traci.close()
971
return fitness
1072
```
11-
## Mutation
73+
74+
### Initialize Population
75+
```python
76+
def init_population(num_phases, phase_types):
77+
# Create random green/yellow durations
78+
return [[random.randint(GREEN_MIN, GREEN_MAX) if t == "green"
79+
else random.randint(YELLOW_MIN, YELLOW_MAX) for t in phase_types]
80+
for _ in range(POP_SIZE)]
81+
```
82+
83+
### Crossover & Mutation
84+
```python
85+
def crossover(p1, p2):
86+
if random.random() < CROSSOVER_RATE:
87+
point = random.randint(1, len(p1) - 1)
88+
return p1[:point] + p2[point:], p2[:point] + p1[point:]
89+
return p1[:], p2[:]
90+
91+
def mutate(ind, phase_types):
92+
for i, t in enumerate(phase_types):
93+
if random.random() < MUTATION_RATE:
94+
ind[i] = random.randint(GREEN_MIN, GREEN_MAX) if t == "green" else random.randint(YELLOW_MIN, YELLOW_MAX)
95+
return ind
96+
```
97+
98+
### Main GA Loop
99+
```python
100+
population = init_population(len(phases), phase_types)
101+
best_solution, best_score = None, float("inf")
102+
103+
for gen in range(N_GENERATIONS):
104+
fitness = [run_simulation(ind) for ind in population]
105+
# Select, crossover, and mutate
106+
...
107+
print(f"Generation {gen+1}: Best Fitness = {best_score:.2f}")
108+
```
109+
110+
### Visualization
111+
At the end of optimization, results are visualized using Matplotlib:
112+
```python
113+
plt.plot(range(1, N_GENERATIONS+1), best_scores, marker='o')
114+
plt.xlabel("Generation")
115+
plt.ylabel("Best Fitness")
116+
plt.title("GA Optimization Progress")
117+
plt.grid(True)
118+
plt.show()
119+
```
120+
121+
## Dependencies
122+
Install required modules:
123+
```bash
124+
pip install traci matplotlib
125+
```
126+
Make sure SUMO is installed and available in your system path.
127+
---
128+

0 commit comments

Comments
 (0)