@@ -492,6 +492,71 @@ print(f"Best real scheduling: {model.problem.decode_solution(model.g_best.soluti
492
492
```
493
493
494
494
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
+
495
560
** Employee Rostering Problem Using Woa Optimizer**
496
561
497
562
The goal is to create an optimal schedule that assigns employees to shifts while satisfying various
0 commit comments