|
| 1 | +import argparse |
| 2 | +import numpy as np |
| 3 | +from fireflyalgorithm.problems import PROBLEMS, get_problem |
| 4 | +from fireflyalgorithm.fireflyalgorithm import FireflyAlgorithm |
| 5 | + |
| 6 | + |
| 7 | +def get_parser(): |
| 8 | + parser = argparse.ArgumentParser( |
| 9 | + prog="firefly-algorithm", |
| 10 | + description="Evaluate the Firefly Algorithm on one or more test functions", |
| 11 | + ) |
| 12 | + |
| 13 | + problem_functions = list(PROBLEMS.keys()) |
| 14 | + parser.add_argument( |
| 15 | + "--problem", |
| 16 | + type=str, |
| 17 | + required=True, |
| 18 | + choices=problem_functions, |
| 19 | + metavar="PROBLEM", |
| 20 | + help="Test problem to evaluate", |
| 21 | + ) |
| 22 | + parser.add_argument( |
| 23 | + "-d", "--dimension", type=int, required=True, help="Dimension of the problem" |
| 24 | + ) |
| 25 | + parser.add_argument( |
| 26 | + "-l", "--lower", type=float, required=True, help="Lower bounds of the problem" |
| 27 | + ) |
| 28 | + parser.add_argument( |
| 29 | + "-u", "--upper", type=float, required=True, help="Upper bounds of the problem" |
| 30 | + ) |
| 31 | + parser.add_argument( |
| 32 | + "-nfes", |
| 33 | + "--max-evals", |
| 34 | + type=int, |
| 35 | + required=True, |
| 36 | + help="Max number of fitness function evaluations", |
| 37 | + ) |
| 38 | + parser.add_argument( |
| 39 | + "-r", "--runs", type=int, default=1, help="Number of runs of the algorithm" |
| 40 | + ) |
| 41 | + parser.add_argument("--pop-size", type=int, default=20, help="Population size") |
| 42 | + parser.add_argument("--alpha", type=float, default=1.0, help="Randomness strength") |
| 43 | + parser.add_argument( |
| 44 | + "--beta-min", type=float, default=1.0, help="Attractiveness constant" |
| 45 | + ) |
| 46 | + parser.add_argument( |
| 47 | + "--gamma", type=float, default=0.01, help="Absorption coefficient" |
| 48 | + ) |
| 49 | + parser.add_argument("--seed", type=int, help="Seed for the random number generator") |
| 50 | + return parser |
| 51 | + |
| 52 | + |
| 53 | +def main(): |
| 54 | + parser = get_parser() |
| 55 | + args = parser.parse_args() |
| 56 | + |
| 57 | + algorithm = FireflyAlgorithm( |
| 58 | + args.pop_size, args.alpha, args.beta_min, args.gamma, args.seed |
| 59 | + ) |
| 60 | + problem = get_problem(args.problem) |
| 61 | + dim = args.dimension |
| 62 | + lb = args.lower |
| 63 | + ub = args.upper |
| 64 | + max_evals = args.max_evals |
| 65 | + runs = args.runs |
| 66 | + |
| 67 | + fitness = np.empty(runs) |
| 68 | + for i in range(runs): |
| 69 | + fitness[i] = algorithm.run(problem, dim, lb, ub, max_evals) |
| 70 | + |
| 71 | + if runs == 1: |
| 72 | + print(f"Best fitness: {fitness[0]}") |
| 73 | + else: |
| 74 | + print(f"Best: {fitness.min()}") |
| 75 | + print(f"Worst: {fitness.max()}") |
| 76 | + print(f"Mean: {fitness.mean()}") |
| 77 | + print(f"Std: {fitness.std()}") |
| 78 | + |
| 79 | + return 0 |
0 commit comments