Skip to content

Commit eba341e

Browse files
committed
Update Shortest Path Problem example
1 parent da0ffb0 commit eba341e

File tree

2 files changed

+126
-0
lines changed

2 files changed

+126
-0
lines changed

README.md

+65
Original file line numberDiff line numberDiff line change
@@ -492,6 +492,71 @@ print(f"Best real scheduling: {model.problem.decode_solution(model.g_best.soluti
492492
```
493493

494494

495+
496+
**Shortest Path Problem**
497+
498+
In this example, the graph is represented as a NumPy array where each element represents the cost or distance between two nodes.
499+
500+
Note that this implementation assumes that the graph is represented by a symmetric matrix, where graph[i,j]
501+
represents the distance between nodes i and j. If your graph representation is different, you may need to modify
502+
the code accordingly.
503+
504+
Please keep in mind that this implementation is a basic example and may not be optimized for large-scale problems.
505+
Further modifications and optimizations may be required depending on your specific use case.
506+
507+
508+
```python
509+
import numpy as np
510+
from mealpy import PermutationVar, WOA, Problem
511+
512+
# Define the graph representation
513+
graph = np.array([
514+
[0, 2, 4, 0, 7, 9],
515+
[2, 0, 1, 4, 2, 8],
516+
[4, 1, 0, 1, 3, 0],
517+
[6, 4, 5, 0, 3, 2],
518+
[0, 2, 3, 3, 0, 2],
519+
[9, 0, 4, 2, 2, 0]
520+
])
521+
522+
523+
class ShortestPathProblem(Problem):
524+
def __init__(self, bounds=None, minmax="min", data=None, **kwargs):
525+
self.data = data
526+
self.eps = 1e10 # Penalty function for vertex with 0 connection
527+
super().__init__(bounds, minmax, **kwargs)
528+
529+
# Calculate the fitness of an individual
530+
def obj_func(self, x):
531+
x_decoded = self.decode_solution(x)
532+
individual = x_decoded["path"]
533+
534+
total_distance = 0
535+
for idx in range(len(individual) - 1):
536+
start_node = individual[idx]
537+
end_node = individual[idx + 1]
538+
weight = self.data[start_node, end_node]
539+
if weight == 0:
540+
return self.eps
541+
total_distance += weight
542+
return total_distance
543+
544+
545+
num_nodes = len(graph)
546+
bounds = PermutationVar(valid_set=list(range(0, num_nodes)), name="path")
547+
problem = ShortestPathProblem(bounds=bounds, minmax="min", data=graph)
548+
549+
model = WOA.OriginalWOA(epoch=100, pop_size=20)
550+
model.solve(problem)
551+
552+
print(f"Best agent: {model.g_best}") # Encoded solution
553+
print(f"Best solution: {model.g_best.solution}") # Encoded solution
554+
print(f"Best fitness: {model.g_best.target.fitness}")
555+
print(f"Best real scheduling: {model.problem.decode_solution(model.g_best.solution)}") # Decoded (Real) solution
556+
```
557+
558+
559+
495560
**Employee Rostering Problem Using Woa Optimizer**
496561

497562
The goal is to create an optimal schedule that assigns employees to shifts while satisfying various
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
#!/usr/bin/env python
2+
# Created by "Thieu" at 15:29, 07/11/2023 ----------%
3+
# Email: [email protected] %
4+
# Github: https://github.com/thieu1995 %
5+
# --------------------------------------------------%
6+
7+
# In this example, the graph is represented as a NumPy array where each element represents the cost or distance between two nodes.
8+
#
9+
# Note that this implementation assumes that the graph is represented by a symmetric matrix, where graph[i,j] represents
10+
# the distance between nodes i and j. If your graph representation is different, you may need to modify the code accordingly.
11+
#
12+
# Please keep in mind that this implementation is a basic example and may not be optimized for large-scale problems.
13+
# Further modifications and optimizations may be required depending on your specific use case.
14+
15+
import numpy as np
16+
from mealpy import PermutationVar, WOA, Problem
17+
18+
# Define the graph representation
19+
graph = np.array([
20+
[0, 2, 4, 0, 7, 9],
21+
[2, 0, 1, 4, 2, 8],
22+
[4, 1, 0, 1, 3, 0],
23+
[6, 4, 5, 0, 3, 2],
24+
[0, 2, 3, 3, 0, 2],
25+
[9, 0, 4, 2, 2, 0]
26+
])
27+
28+
29+
class ShortestPathProblem(Problem):
30+
def __init__(self, bounds=None, minmax="min", data=None, **kwargs):
31+
self.data = data
32+
self.eps = 1e10 # Penalty function for vertex with 0 connection
33+
super().__init__(bounds, minmax, **kwargs)
34+
35+
# Calculate the fitness of an individual
36+
def obj_func(self, x):
37+
x_decoded = self.decode_solution(x)
38+
individual = x_decoded["path"]
39+
40+
total_distance = 0
41+
for idx in range(len(individual) - 1):
42+
start_node = individual[idx]
43+
end_node = individual[idx + 1]
44+
weight = self.data[start_node, end_node]
45+
if weight == 0:
46+
return self.eps
47+
total_distance += weight
48+
return total_distance
49+
50+
51+
num_nodes = len(graph)
52+
bounds = PermutationVar(valid_set=list(range(0, num_nodes)), name="path")
53+
problem = ShortestPathProblem(bounds=bounds, minmax="min", data=graph)
54+
55+
model = WOA.OriginalWOA(epoch=100, pop_size=20)
56+
model.solve(problem)
57+
58+
print(f"Best agent: {model.g_best}") # Encoded solution
59+
print(f"Best solution: {model.g_best.solution}") # Encoded solution
60+
print(f"Best fitness: {model.g_best.target.fitness}")
61+
print(f"Best real scheduling: {model.problem.decode_solution(model.g_best.solution)}") # Decoded (Real) solution

0 commit comments

Comments
 (0)