Skip to content

metazoo.bio.darwin

Contains implementations of animal-inspired algorithms.

Submodules

  • pso: Particle Swarm Optimization

Example

from metazoo.bio.darwin.pso import ParticleSwarmOptimizer
from metazoo.gym.evolutionary import crossover, mutation, selection

Reference

ParticleSwarmOptimizer

A simple Particle Swarm Optimization (PSO) implementation.

Source code in metazoo/src/metazoo/bio/darwin/pso.py
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
class ParticleSwarmOptimizer:
    """A simple Particle Swarm Optimization (PSO) implementation."""

    def __init__(
        self,
        fitness_function,
        encoder: Encoding,
        population_size=30,
        inertia=0.7,
        cognitive=1.5,
        social=1.5,
        minimize=True,
    ):
        """
        Initialize the PSO optimizer.
        """
        self.fitness_function = fitness_function
        self.inertia = inertia
        self.cognitive = cognitive
        self.social = social
        self.minimize = minimize

        self.swarm = Swarm(population_size, encoder, minimize=minimize)
        self.global_best_position = None
        self.global_best_fitness = np.inf if minimize else -np.inf
        self.fitness_history = []
        self.best_history = []

    def summary(self):
        """
        Summarize the PSO configuration.
        """
        from rich.console import Console
        from rich.table import Table

        table = Table(title="Particle Swarm Optimizer Summary")
        table.add_column("Parameter", style="bold cyan")
        table.add_column("Value", style="bold magenta")
        table.add_row("Particles", str(self.swarm.size))
        table.add_row("Dimensions", str(self.swarm.encoding.genome_length))
        table.add_row("Inertia", str(self.inertia))
        table.add_row("Cognitive", str(self.cognitive))
        table.add_row("Social", str(self.social))
        table.add_row("Bounds", str(getattr(self.swarm.encoding, "bounds", "None")))
        table.add_row("Fitness Function", self.fitness_function.__name__)
        table.add_row("Minimize", str(self.minimize))
        console = Console()
        console.print(table)

    def eval(self):
        """
        Evaluate the fitness of all particles and update the global best.
        """

        raw_fitness = np.array(
            [
                self.fitness_function(self.swarm.encoding.decode(particle.position))
                for particle in self.swarm
            ]
        )

        if self.minimize:
            fitness = np.nan_to_num(raw_fitness, nan=1e10, posinf=1e10, neginf=1e10)
            self.best_fitness = float(fitness.min())
            best_idx = int(fitness.argmin())
            fitness_transformed = np.max(fitness) - fitness
        else:
            fitness = np.nan_to_num(raw_fitness, nan=-1e10, posinf=-1e10, neginf=-1e10)
            self.best_fitness = float(fitness.max())
            best_idx = int(fitness.argmax())
            fitness_transformed = fitness

        self.best_individual = self.swarm[best_idx]

        return fitness, fitness_transformed

    def step(self):
        """
        Perform one PSO iteration: update velocities and positions.
        """

        fitness, fitness_transformed = self.eval()
        self.fitness_history.append(fitness.mean())
        self.best_history.append(self.best_fitness)

        # Update swarm for Real encoding
        if isinstance(self.swarm.encoding, Real):
            for i, particle in enumerate(self.swarm):
                r1, r2 = np.random.rand(), np.random.rand()
                cognitive_velocity = (
                    self.cognitive * r1 * (particle.best_position - particle.position)
                )
                social_velocity = (
                    self.social
                    * r2
                    * (self.best_individual.position - particle.position)
                )
                particle.velocity = (
                    self.inertia * particle.velocity
                    + cognitive_velocity
                    + social_velocity
                )
                particle.position += particle.velocity

                # Clip position to bounds if defined
                if (
                    hasattr(self.swarm.encoding, "bounds")
                    and self.swarm.encoding.bounds is not None
                ):
                    lower, upper = np.array(self.swarm.encoding.bounds).T
                    particle.position = np.clip(particle.position, lower, upper)

                fitness_value = fitness[i]
                if (self.minimize and fitness_value < particle.best_value) or (
                    not self.minimize and fitness_value > particle.best_value
                ):
                    particle.best_position = particle.position.copy()
                    particle.best_value = fitness_value

        if isinstance(self.swarm.encoding, Permutation):
            for i, particle in enumerate(self.swarm):
                # Update velocity as list of swaps
                new_velocity = []

                # Cognitive component
                cognitive_swaps = get_permutation_swaps(
                    particle.position, particle.best_position
                )
                num_cognitive_swaps = int(
                    self.cognitive * np.random.rand() * len(cognitive_swaps)
                )
                new_velocity.extend(cognitive_swaps[:num_cognitive_swaps])

                # Social component
                social_swaps = get_permutation_swaps(
                    particle.position, self.best_individual.position
                )
                num_social_swaps = int(
                    self.social * np.random.rand() * len(social_swaps)
                )
                new_velocity.extend(social_swaps[:num_social_swaps])

                # Update particle velocity and position
                particle.velocity = new_velocity
                particle.position = apply_permutation_swaps(
                    particle.position, particle.velocity
                )

            # Update personal best
            if (self.minimize and fitness[i] < particle.best_value) or (
                not self.minimize and fitness[i] > particle.best_value
            ):
                particle.best_position = particle.position.copy()
                particle.best_value = fitness[i]

        # Update global best
        if (self.minimize and self.best_fitness < self.global_best_fitness) or (
            not self.minimize and self.best_fitness > self.global_best_fitness
        ):
            self.global_best_fitness = self.best_fitness
            self.global_best_position = self.best_individual.position.copy()

    def run(self, iterations=100, history=False, verbose=True):
        """
        Run the main PSO loop.
        """
        pop_history = []
        best_history = []
        if verbose:
            with Progress() as progress:
                task = progress.add_task("Optimizing...", total=iterations)
                for _ in range(iterations):
                    self.step()
                    pop_history.append([p.position.copy() for p in self.swarm])
                    best_history.append(self.global_best_position.copy())
                    progress.advance(task)
        else:
            for _ in range(iterations):
                self.step()
                pop_history.append([p.position.copy() for p in self.swarm])
                best_history.append(self.global_best_position.copy())
        if history:
            return best_history, pop_history

    def fitness_plot(self, best=False):
        """
        Plot the fitness history using plotly.
        """

        if self.fitness_history:
            if not best:
                fig = px.line(
                    y=np.array(self.fitness_history),
                    labels={"x": "Iteration", "y": "Fitness"},
                    title="Fitness History",
                )
                return fig
            else:
                fig = px.line(
                    y=np.array(self.best_history),
                    labels={"x": "Iteration", "y": "Best Fitness"},
                    title="Best Fitness History",
                )
                return fig
        else:
            raise ValueError("No fitness history to plot. Run the algorithm first.")

__init__(fitness_function, encoder, population_size=30, inertia=0.7, cognitive=1.5, social=1.5, minimize=True)

Initialize the PSO optimizer.

Source code in metazoo/src/metazoo/bio/darwin/pso.py
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
def __init__(
    self,
    fitness_function,
    encoder: Encoding,
    population_size=30,
    inertia=0.7,
    cognitive=1.5,
    social=1.5,
    minimize=True,
):
    """
    Initialize the PSO optimizer.
    """
    self.fitness_function = fitness_function
    self.inertia = inertia
    self.cognitive = cognitive
    self.social = social
    self.minimize = minimize

    self.swarm = Swarm(population_size, encoder, minimize=minimize)
    self.global_best_position = None
    self.global_best_fitness = np.inf if minimize else -np.inf
    self.fitness_history = []
    self.best_history = []

eval()

Evaluate the fitness of all particles and update the global best.

Source code in metazoo/src/metazoo/bio/darwin/pso.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
def eval(self):
    """
    Evaluate the fitness of all particles and update the global best.
    """

    raw_fitness = np.array(
        [
            self.fitness_function(self.swarm.encoding.decode(particle.position))
            for particle in self.swarm
        ]
    )

    if self.minimize:
        fitness = np.nan_to_num(raw_fitness, nan=1e10, posinf=1e10, neginf=1e10)
        self.best_fitness = float(fitness.min())
        best_idx = int(fitness.argmin())
        fitness_transformed = np.max(fitness) - fitness
    else:
        fitness = np.nan_to_num(raw_fitness, nan=-1e10, posinf=-1e10, neginf=-1e10)
        self.best_fitness = float(fitness.max())
        best_idx = int(fitness.argmax())
        fitness_transformed = fitness

    self.best_individual = self.swarm[best_idx]

    return fitness, fitness_transformed

fitness_plot(best=False)

Plot the fitness history using plotly.

Source code in metazoo/src/metazoo/bio/darwin/pso.py
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
def fitness_plot(self, best=False):
    """
    Plot the fitness history using plotly.
    """

    if self.fitness_history:
        if not best:
            fig = px.line(
                y=np.array(self.fitness_history),
                labels={"x": "Iteration", "y": "Fitness"},
                title="Fitness History",
            )
            return fig
        else:
            fig = px.line(
                y=np.array(self.best_history),
                labels={"x": "Iteration", "y": "Best Fitness"},
                title="Best Fitness History",
            )
            return fig
    else:
        raise ValueError("No fitness history to plot. Run the algorithm first.")

run(iterations=100, history=False, verbose=True)

Run the main PSO loop.

Source code in metazoo/src/metazoo/bio/darwin/pso.py
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
def run(self, iterations=100, history=False, verbose=True):
    """
    Run the main PSO loop.
    """
    pop_history = []
    best_history = []
    if verbose:
        with Progress() as progress:
            task = progress.add_task("Optimizing...", total=iterations)
            for _ in range(iterations):
                self.step()
                pop_history.append([p.position.copy() for p in self.swarm])
                best_history.append(self.global_best_position.copy())
                progress.advance(task)
    else:
        for _ in range(iterations):
            self.step()
            pop_history.append([p.position.copy() for p in self.swarm])
            best_history.append(self.global_best_position.copy())
    if history:
        return best_history, pop_history

step()

Perform one PSO iteration: update velocities and positions.

Source code in metazoo/src/metazoo/bio/darwin/pso.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
def step(self):
    """
    Perform one PSO iteration: update velocities and positions.
    """

    fitness, fitness_transformed = self.eval()
    self.fitness_history.append(fitness.mean())
    self.best_history.append(self.best_fitness)

    # Update swarm for Real encoding
    if isinstance(self.swarm.encoding, Real):
        for i, particle in enumerate(self.swarm):
            r1, r2 = np.random.rand(), np.random.rand()
            cognitive_velocity = (
                self.cognitive * r1 * (particle.best_position - particle.position)
            )
            social_velocity = (
                self.social
                * r2
                * (self.best_individual.position - particle.position)
            )
            particle.velocity = (
                self.inertia * particle.velocity
                + cognitive_velocity
                + social_velocity
            )
            particle.position += particle.velocity

            # Clip position to bounds if defined
            if (
                hasattr(self.swarm.encoding, "bounds")
                and self.swarm.encoding.bounds is not None
            ):
                lower, upper = np.array(self.swarm.encoding.bounds).T
                particle.position = np.clip(particle.position, lower, upper)

            fitness_value = fitness[i]
            if (self.minimize and fitness_value < particle.best_value) or (
                not self.minimize and fitness_value > particle.best_value
            ):
                particle.best_position = particle.position.copy()
                particle.best_value = fitness_value

    if isinstance(self.swarm.encoding, Permutation):
        for i, particle in enumerate(self.swarm):
            # Update velocity as list of swaps
            new_velocity = []

            # Cognitive component
            cognitive_swaps = get_permutation_swaps(
                particle.position, particle.best_position
            )
            num_cognitive_swaps = int(
                self.cognitive * np.random.rand() * len(cognitive_swaps)
            )
            new_velocity.extend(cognitive_swaps[:num_cognitive_swaps])

            # Social component
            social_swaps = get_permutation_swaps(
                particle.position, self.best_individual.position
            )
            num_social_swaps = int(
                self.social * np.random.rand() * len(social_swaps)
            )
            new_velocity.extend(social_swaps[:num_social_swaps])

            # Update particle velocity and position
            particle.velocity = new_velocity
            particle.position = apply_permutation_swaps(
                particle.position, particle.velocity
            )

        # Update personal best
        if (self.minimize and fitness[i] < particle.best_value) or (
            not self.minimize and fitness[i] > particle.best_value
        ):
            particle.best_position = particle.position.copy()
            particle.best_value = fitness[i]

    # Update global best
    if (self.minimize and self.best_fitness < self.global_best_fitness) or (
        not self.minimize and self.best_fitness > self.global_best_fitness
    ):
        self.global_best_fitness = self.best_fitness
        self.global_best_position = self.best_individual.position.copy()

summary()

Summarize the PSO configuration.

Source code in metazoo/src/metazoo/bio/darwin/pso.py
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
def summary(self):
    """
    Summarize the PSO configuration.
    """
    from rich.console import Console
    from rich.table import Table

    table = Table(title="Particle Swarm Optimizer Summary")
    table.add_column("Parameter", style="bold cyan")
    table.add_column("Value", style="bold magenta")
    table.add_row("Particles", str(self.swarm.size))
    table.add_row("Dimensions", str(self.swarm.encoding.genome_length))
    table.add_row("Inertia", str(self.inertia))
    table.add_row("Cognitive", str(self.cognitive))
    table.add_row("Social", str(self.social))
    table.add_row("Bounds", str(getattr(self.swarm.encoding, "bounds", "None")))
    table.add_row("Fitness Function", self.fitness_function.__name__)
    table.add_row("Minimize", str(self.minimize))
    console = Console()
    console.print(table)