abc-tsp


Nameabc-tsp JSON
Version 2.0.2 PyPI version JSON
download
home_pagehttps://github.com/AngelS017/ABC-algorithm-for-TSP
SummaryArtificial Bee Colony TSP solver
upload_time2024-10-24 16:18:22
maintainerNone
docs_urlNone
authorAngel Sanz Gutierrez
requires_python>=3.8
licenseMIT
keywords artificial bee colony abc optimizer tsp k-opt metaheuristic
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Artificial Bee Colony (ABC) for Solving the Traveling Salesman Problem (TSP)

![Artificial Bee Colony](https://img.shields.io/badge/Artificial%20Bee%20Colony-ABC%20Algorithm-blue.svg) 
![Python](https://img.shields.io/badge/Python-3.8%2B-brightgreen.svg)
![TSP](https://img.shields.io/badge/Problem-TSP-orange.svg) 
![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)


This project implements an Artificial Bee Colony (ABC) algorithm for solving the Traveling Salesman Problem (TSP), where the goal is to find the shortest possible route that visits a set of cities exactly once and returns to the starting point.

## Table of Contents
- [Author and contact](#author-and-contact)
- [Version History](#version-history)
- [Overview](#overview)
- [Algorithm Workflow](#algorithm-workflow)
- [Folder Structure](#folder-structure)
- [Installation](#installation)
- [Classes and Functions](#classes-and-functions)
- [Usage](#usage)
- [Tuning Parameters](#tuning-parameters)
- [Contributing](#contributing)
- [License](#license)


## Author and contact

Author: Angel Sanz Gutierrez\
Contact: sanzangel017@gmail.com\
GitHub: AngelS017\
License: MIT License

## Version History

### [v 2.0.2] - 2024-10-24
- Changes on how to pass the hyperparameters for the different employed and onlooker bee mutation strategies.
- Eliminated the search for unnecessary hyperparameter combinations from the ABC algorithm thanks to the new hyperparameter step in the mutation strategies. 
- Updated documentation (README and comments on functions)


### [v 2.0.0] - 2024-09-17
- Added new functionality in ArtificialBeeColonyOptimizer: grid_search_abc()
- Updated the minimum required Python version to 3.8

### [v 1.0.3] - 2023-09-14
- Initial release of the Artificial Bee Colony for TSP,

## Overview

The Artificial Bee Colony (ABC) algorithm is a bio-inspired optimization technique modeled after the intelligent foraging behavior of honeybees. This algorithm is highly effective for solving complex optimization problems like the Traveling Salesman Problem (TSP), where the objective is to find the shortest path that visits all cities exactly once and returns to the starting city.

In this implementation, bees are divided into three roles: employed bees, onlooker bees, and scout bees. 
Each role contributes to exploring the search space and improving potential solutions. 

* Employed bees focus on exploitation new food sources (solutions). 

* Onlooker bees focus on selective exploitation, probabilistically select and improve upon the best-found solutions.

* Scout bees introduce exploration by abandoning poor solutions.

This implementation provides a flexible ABC framework, allowing users to:

* Customize the mutation strategies for exploring different paths.

* Customize the porcentage of bees of each role (Employed and Onlooker).

* Adjust the colony size, exploitation limits and the number of epochs to optimize the problem.


## Algorithm Workflow

1. Initialization:

    A population of bees (solutions) is randomly initialized. The population is divided into employed bees and onlooker bees.
    Each employed bee is assigned a random TSP route, and the initial distance for each route is calculated.

2. Employed Bee Phase:

    Employed bees explore new routes by applying mutation strategies.
    If the new route is shorter, the employed bee updates its current route.

3. Onlooker Bee Phase:

    Onlooker bees choose solutions based on the probability proportional to the solution’s quality (distance).
    Onlookers explore new routes and improve upon the best ones found by employed bees.

4. Scout Bee Phase:

    If an employed bee fails to find a better route for a predefined number of trials, it becomes a scout bee and is reinitialized with a new random route.

5. Convergence:

    The algorithm is executed for a defined number of epochs, constantly trying to improve the routes and recording the best solution found.


## Folder Structure

    ArtificialBeeColony_TSP
    ├── abc_tsp
    |   ├── ArtificialBeeColony_TSP.py
    |   └── __init__.py
    ├── README.md
    ├── LICENSE
    └── setup.py

## Prerequisites

The following open source packages are used to develop this algorithm:
* numpy >= 1.22
* tqdm
* joblib

Additionally, the software requires the Python 3.8 or higher version, as this is the minimum version supported by the tqmd packages.

However, it is recommended that the most recent versions of Numpy and Python be installed in order to achieve optimal performance and the fastest results.

## Installation

To install the ABC algorithm for the TSP, you just need to:

    pip install abc-tsp

    
## Classes and Functions
* Bee
  * Attributes:
    * **role:** Defines whether the bee is Employed, Onlooker, or Scout.
    * **path:** The current TSP path the bee is exploring.
    * **path_len:** The len of the path - 2 (used to select the indexes of the   path for the mutation strategy)
    * **path_distance:** The total distance of the current path.
    * **trial:** Number of unsuccessful attempts to improve the current path.
    * **mutation_strategy:** The mutation startegy used by the bees to generate new solutions.

  * Methods:

    * **_select_mutation_strategy():** Selects the appropriate mutation strategy based on the provided strategy name
    * **swap():** The swap strategy
    * **insertion():** The insertion strategy
    * **k_opt():** The k-opt strategy
    * **mutate_path():** Applies a mutation strategy (e.g., swap, insertion, k-opt) to generate new paths.
    * **distance_path():** Calculates the total distance of the given path using the distance matrix.

* ArtificialBeeColonyOptimizer
  * Attributes:
    * **ini_end_city:** The city where the path starts and ends.
    * **population:** Total number of bees in the colony.
    * **employed_percentage:** Percentage of employed bees in the colony.
    * **limit:** Trial limit before a bee becomes a scout.
    * **epochs:** Number of iterations the algorithm will run.
    * **distance_matrix:** Matrix containing the distances between cities.
    * **employed_mutation_strategy:** The mutation strategy used by the employed bees.
    * **onlooker_mutation_strategy:** The mutation strategy used by the onlooker bees.
    * **mutation_params:** All the parametrs needed for the employed_mutation_strategy and the onlooker_mutation_strategy in an dictionary format.
    * **seed:** The seed for the random numbers.
    * **verbose:** If you want to see the information after de training of the algorithm.

  * Methods:
    * **initialize_colony_with_roles():** Initializes the bee colony with random paths and their roles.
    * **employed_bee_behavior():** The logic behind employed bees improving their solutions.
    * **caclulate_probabilities():** Compute the probability of choosing each solution in the colony.
    * **roulette_wheel_selection():** Apply the roulet wheel selction to choose the best solution in the colony for the onlooker bee.
    * **onlooker_bee_behavior():** Onlooker bees probabilistically select solutions and improve them.
    * **scout_bee_behavior():** Resets bees that haven’t improved after several trials.
    * **find_best_path():** Finds and returns the best path in the current colony.
    * **fit():** The main loop for optimizing the TSP solution using the ABC algorithm.
    * **run_single_params():** Runs the ABC algorithm with a single set of parameters, returning parameters, the best path and its distance for that specific configuration.
    * **grid_search_abc():** Performs a grid search over a range of parameters to find the best configuration of the algorithm for solving the TSP, allowing users to optimize performance.
    * **print_colony():** Print information (Bee number, role, path distance and trials) about the colony.


## Usage

To use this implementation of the Artificial Bee Colony (ABC) algorithm for solving TSP, follow the basic structure provided below:

~~~python

from abc_tsp import ArtificialBeeColonyOptimizer

# Define the TSP problem as a distance matrix
distance_matrix = np.array([...]) #Square matrix of distances: cities x cities

# Create an instance of the ABC optimizer
abc_optimizer = ArtificialBeeColonyOptimizer(
    ini_end_city=0,  
    population=15,  
    employed_percentage=0.5,  
    limit=2000,  
    epochs=60000,  
    distance_matrix=distance_matrix, 
    employed_mutation_strategy='k_opt',  
    onlooker_mutation_strategy='k_opt',  
    mutation_params = {'k_employed':5, 'k_onlooker':5},  
    seed=1234, 
    verbose=1  
)

# Fit the model and solve the TSP
execution_time, paths_distances, final_best_path, final_best_path_distance = abc_optimizer.fit()

# Results
print(f"Best Path: {final_best_path}")
print(f"Best Path Distance: {final_best_path_distance}")
print(f"Execution Time: {execution_time} seconds")
~~~


## Tuning Parameters

The ArtificialBeeColonyOptimizer class allows you to customize key parameters for tuning the algorithm:

* population
* employed_percentage
* limit
* epochs
* employed_mutation_strategy and onlooker_mutation_strategy
* mutation_params:
    * k_employed
    * k_onlooker

Depending on the data, you may need to search for the optimal values of these parameters in order to get the best result (probably taking into account the time and the path distance).


## Contributing

If you wish to contribute, please fork the repository and create a pull request with a detailed description of the changes. 

Contributions for adding new features, fixing bugs, or improving performance are welcome!


## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

<div align="center"> <img src="https://img.shields.io/badge/License-MIT-blue.svg"> </div>









            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/AngelS017/ABC-algorithm-for-TSP",
    "name": "abc-tsp",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "Artificial Bee Colony, ABC, Optimizer, TSP, k-opt, metaheuristic",
    "author": "Angel Sanz Gutierrez",
    "author_email": "sanzangel017@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/9d/02/a02c4b2210fb96ee919395de4a335f88e40451206b592cbf4cd50e94c5a4/abc_tsp-2.0.2.tar.gz",
    "platform": null,
    "description": "# Artificial Bee Colony (ABC) for Solving the Traveling Salesman Problem (TSP)\r\n\r\n![Artificial Bee Colony](https://img.shields.io/badge/Artificial%20Bee%20Colony-ABC%20Algorithm-blue.svg) \r\n![Python](https://img.shields.io/badge/Python-3.8%2B-brightgreen.svg)\r\n![TSP](https://img.shields.io/badge/Problem-TSP-orange.svg) \r\n![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)\r\n\r\n\r\nThis project implements an Artificial Bee Colony (ABC) algorithm for solving the Traveling Salesman Problem (TSP), where the goal is to find the shortest possible route that visits a set of cities exactly once and returns to the starting point.\r\n\r\n## Table of Contents\r\n- [Author and contact](#author-and-contact)\r\n- [Version History](#version-history)\r\n- [Overview](#overview)\r\n- [Algorithm Workflow](#algorithm-workflow)\r\n- [Folder Structure](#folder-structure)\r\n- [Installation](#installation)\r\n- [Classes and Functions](#classes-and-functions)\r\n- [Usage](#usage)\r\n- [Tuning Parameters](#tuning-parameters)\r\n- [Contributing](#contributing)\r\n- [License](#license)\r\n\r\n\r\n## Author and contact\r\n\r\nAuthor: Angel Sanz Gutierrez\\\r\nContact: sanzangel017@gmail.com\\\r\nGitHub: AngelS017\\\r\nLicense: MIT License\r\n\r\n## Version History\r\n\r\n### [v 2.0.2] - 2024-10-24\r\n- Changes on how to pass the hyperparameters for the different employed and onlooker bee mutation strategies.\r\n- Eliminated the search for unnecessary hyperparameter combinations from the ABC algorithm thanks to the new hyperparameter step in the mutation strategies. \r\n- Updated documentation (README and comments on functions)\r\n\r\n\r\n### [v 2.0.0] - 2024-09-17\r\n- Added new functionality in ArtificialBeeColonyOptimizer: grid_search_abc()\r\n- Updated the minimum required Python version to 3.8\r\n\r\n### [v 1.0.3] - 2023-09-14\r\n- Initial release of the Artificial Bee Colony for TSP,\r\n\r\n## Overview\r\n\r\nThe Artificial Bee Colony (ABC) algorithm is a bio-inspired optimization technique modeled after the intelligent foraging behavior of honeybees. This algorithm is highly effective for solving complex optimization problems like the Traveling Salesman Problem (TSP), where the objective is to find the shortest path that visits all cities exactly once and returns to the starting city.\r\n\r\nIn this implementation, bees are divided into three roles: employed bees, onlooker bees, and scout bees. \r\nEach role contributes to exploring the search space and improving potential solutions. \r\n\r\n* Employed bees focus on exploitation new food sources (solutions). \r\n\r\n* Onlooker bees focus on selective exploitation, probabilistically select and improve upon the best-found solutions.\r\n\r\n* Scout bees introduce exploration by abandoning poor solutions.\r\n\r\nThis implementation provides a flexible ABC framework, allowing users to:\r\n\r\n* Customize the mutation strategies for exploring different paths.\r\n\r\n* Customize the porcentage of bees of each role (Employed and Onlooker).\r\n\r\n* Adjust the colony size, exploitation limits and the number of epochs to optimize the problem.\r\n\r\n\r\n## Algorithm Workflow\r\n\r\n1. Initialization:\r\n\r\n    A population of bees (solutions) is randomly initialized. The population is divided into employed bees and onlooker bees.\r\n    Each employed bee is assigned a random TSP route, and the initial distance for each route is calculated.\r\n\r\n2. Employed Bee Phase:\r\n\r\n    Employed bees explore new routes by applying mutation strategies.\r\n    If the new route is shorter, the employed bee updates its current route.\r\n\r\n3. Onlooker Bee Phase:\r\n\r\n    Onlooker bees choose solutions based on the probability proportional to the solution\u2019s quality (distance).\r\n    Onlookers explore new routes and improve upon the best ones found by employed bees.\r\n\r\n4. Scout Bee Phase:\r\n\r\n    If an employed bee fails to find a better route for a predefined number of trials, it becomes a scout bee and is reinitialized with a new random route.\r\n\r\n5. Convergence:\r\n\r\n    The algorithm is executed for a defined number of epochs, constantly trying to improve the routes and recording the best solution found.\r\n\r\n\r\n## Folder Structure\r\n\r\n    ArtificialBeeColony_TSP\r\n    \u251c\u2500\u2500 abc_tsp\r\n    |   \u251c\u2500\u2500 ArtificialBeeColony_TSP.py\r\n    |   \u2514\u2500\u2500 __init__.py\r\n    \u251c\u2500\u2500 README.md\r\n    \u251c\u2500\u2500 LICENSE\r\n    \u2514\u2500\u2500 setup.py\r\n\r\n## Prerequisites\r\n\r\nThe following open source packages are used to develop this algorithm:\r\n* numpy >= 1.22\r\n* tqdm\r\n* joblib\r\n\r\nAdditionally, the software requires the Python 3.8 or higher version, as this is the minimum version supported by the tqmd packages.\r\n\r\nHowever, it is recommended that the most recent versions of Numpy and Python be installed in order to achieve optimal performance and the fastest results.\r\n\r\n## Installation\r\n\r\nTo install the ABC algorithm for the TSP, you just need to:\r\n\r\n    pip install abc-tsp\r\n\r\n    \r\n## Classes and Functions\r\n* Bee\r\n  * Attributes:\r\n    * **role:** Defines whether the bee is Employed, Onlooker, or Scout.\r\n    * **path:** The current TSP path the bee is exploring.\r\n    * **path_len:** The len of the path - 2 (used to select the indexes of the   path for the mutation strategy)\r\n    * **path_distance:** The total distance of the current path.\r\n    * **trial:** Number of unsuccessful attempts to improve the current path.\r\n    * **mutation_strategy:** The mutation startegy used by the bees to generate new solutions.\r\n\r\n  * Methods:\r\n\r\n    * **_select_mutation_strategy():** Selects the appropriate mutation strategy based on the provided strategy name\r\n    * **swap():** The swap strategy\r\n    * **insertion():** The insertion strategy\r\n    * **k_opt():** The k-opt strategy\r\n    * **mutate_path():** Applies a mutation strategy (e.g., swap, insertion, k-opt) to generate new paths.\r\n    * **distance_path():** Calculates the total distance of the given path using the distance matrix.\r\n\r\n* ArtificialBeeColonyOptimizer\r\n  * Attributes:\r\n    * **ini_end_city:** The city where the path starts and ends.\r\n    * **population:** Total number of bees in the colony.\r\n    * **employed_percentage:** Percentage of employed bees in the colony.\r\n    * **limit:** Trial limit before a bee becomes a scout.\r\n    * **epochs:** Number of iterations the algorithm will run.\r\n    * **distance_matrix:** Matrix containing the distances between cities.\r\n    * **employed_mutation_strategy:** The mutation strategy used by the employed bees.\r\n    * **onlooker_mutation_strategy:** The mutation strategy used by the onlooker bees.\r\n    * **mutation_params:** All the parametrs needed for the employed_mutation_strategy and the onlooker_mutation_strategy in an dictionary format.\r\n    * **seed:** The seed for the random numbers.\r\n    * **verbose:** If you want to see the information after de training of the algorithm.\r\n\r\n  * Methods:\r\n    * **initialize_colony_with_roles():** Initializes the bee colony with random paths and their roles.\r\n    * **employed_bee_behavior():** The logic behind employed bees improving their solutions.\r\n    * **caclulate_probabilities():** Compute the probability of choosing each solution in the colony.\r\n    * **roulette_wheel_selection():** Apply the roulet wheel selction to choose the best solution in the colony for the onlooker bee.\r\n    * **onlooker_bee_behavior():** Onlooker bees probabilistically select solutions and improve them.\r\n    * **scout_bee_behavior():** Resets bees that haven\u2019t improved after several trials.\r\n    * **find_best_path():** Finds and returns the best path in the current colony.\r\n    * **fit():** The main loop for optimizing the TSP solution using the ABC algorithm.\r\n    * **run_single_params():** Runs the ABC algorithm with a single set of parameters, returning parameters, the best path and its distance for that specific configuration.\r\n    * **grid_search_abc():** Performs a grid search over a range of parameters to find the best configuration of the algorithm for solving the TSP, allowing users to optimize performance.\r\n    * **print_colony():** Print information (Bee number, role, path distance and trials) about the colony.\r\n\r\n\r\n## Usage\r\n\r\nTo use this implementation of the Artificial Bee Colony (ABC) algorithm for solving TSP, follow the basic structure provided below:\r\n\r\n~~~python\r\n\r\nfrom abc_tsp import ArtificialBeeColonyOptimizer\r\n\r\n# Define the TSP problem as a distance matrix\r\ndistance_matrix = np.array([...]) #Square matrix of distances: cities x cities\r\n\r\n# Create an instance of the ABC optimizer\r\nabc_optimizer = ArtificialBeeColonyOptimizer(\r\n    ini_end_city=0,  \r\n    population=15,  \r\n    employed_percentage=0.5,  \r\n    limit=2000,  \r\n    epochs=60000,  \r\n    distance_matrix=distance_matrix, \r\n    employed_mutation_strategy='k_opt',  \r\n    onlooker_mutation_strategy='k_opt',  \r\n    mutation_params = {'k_employed':5, 'k_onlooker':5},  \r\n    seed=1234, \r\n    verbose=1  \r\n)\r\n\r\n# Fit the model and solve the TSP\r\nexecution_time, paths_distances, final_best_path, final_best_path_distance = abc_optimizer.fit()\r\n\r\n# Results\r\nprint(f\"Best Path: {final_best_path}\")\r\nprint(f\"Best Path Distance: {final_best_path_distance}\")\r\nprint(f\"Execution Time: {execution_time} seconds\")\r\n~~~\r\n\r\n\r\n## Tuning Parameters\r\n\r\nThe ArtificialBeeColonyOptimizer class allows you to customize key parameters for tuning the algorithm:\r\n\r\n* population\r\n* employed_percentage\r\n* limit\r\n* epochs\r\n* employed_mutation_strategy and onlooker_mutation_strategy\r\n* mutation_params:\r\n    * k_employed\r\n    * k_onlooker\r\n\r\nDepending on the data, you may need to search for the optimal values of these parameters in order to get the best result (probably taking into account the time and the path distance).\r\n\r\n\r\n## Contributing\r\n\r\nIf you wish to contribute, please fork the repository and create a pull request with a detailed description of the changes. \r\n\r\nContributions for adding new features, fixing bugs, or improving performance are welcome!\r\n\r\n\r\n## License\r\n\r\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\r\n\r\n<div align=\"center\"> <img src=\"https://img.shields.io/badge/License-MIT-blue.svg\"> </div>\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Artificial Bee Colony TSP solver",
    "version": "2.0.2",
    "project_urls": {
        "Homepage": "https://github.com/AngelS017/ABC-algorithm-for-TSP"
    },
    "split_keywords": [
        "artificial bee colony",
        " abc",
        " optimizer",
        " tsp",
        " k-opt",
        " metaheuristic"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "55b0118c3f5b52f5bc066cd97d651d6a348da43919519ef0a7ae1bd3b867d13b",
                "md5": "721b5b6940685c56549c23878ef244e4",
                "sha256": "c17cf0b92998727c9f7b6017aabe3b5fb5de1a2aee92c7ef7977fed7febcaa9e"
            },
            "downloads": -1,
            "filename": "abc_tsp-2.0.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "721b5b6940685c56549c23878ef244e4",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 11925,
            "upload_time": "2024-10-24T16:18:20",
            "upload_time_iso_8601": "2024-10-24T16:18:20.167644Z",
            "url": "https://files.pythonhosted.org/packages/55/b0/118c3f5b52f5bc066cd97d651d6a348da43919519ef0a7ae1bd3b867d13b/abc_tsp-2.0.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "9d02a02c4b2210fb96ee919395de4a335f88e40451206b592cbf4cd50e94c5a4",
                "md5": "7c74d575e3f5a0de42b98e7a0a977340",
                "sha256": "64eac9984d223afb54ce167847fc813067b24fd5ca516dd8fcace7979f7ac051"
            },
            "downloads": -1,
            "filename": "abc_tsp-2.0.2.tar.gz",
            "has_sig": false,
            "md5_digest": "7c74d575e3f5a0de42b98e7a0a977340",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 14731,
            "upload_time": "2024-10-24T16:18:22",
            "upload_time_iso_8601": "2024-10-24T16:18:22.571002Z",
            "url": "https://files.pythonhosted.org/packages/9d/02/a02c4b2210fb96ee919395de4a335f88e40451206b592cbf4cd50e94c5a4/abc_tsp-2.0.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-10-24 16:18:22",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "AngelS017",
    "github_project": "ABC-algorithm-for-TSP",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "abc-tsp"
}
        
Elapsed time: 0.99933s