{"id":26586488,"url":"https://github.com/renatomaynard/tsp-genetic-algorithm","last_synced_at":"2026-05-03T21:32:43.096Z","repository":{"id":283184018,"uuid":"950945986","full_name":"RenatoMaynard/TSP-Genetic-Algorithm","owner":"RenatoMaynard","description":"This repository contains a Genetic Algorithm (GA) implementation for solving the Traveling Salesman Problem (TSP).","archived":false,"fork":false,"pushed_at":"2025-03-23T21:18:46.000Z","size":904,"stargazers_count":16,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2026-03-29T01:26:26.463Z","etag":null,"topics":["animation","deap","evolutionary-algorithm","genetic-algorithm","heuristic","jupyter-notebook","local-search-algorithm","matplotlib","metaheuristic","numpy","operations-research","optimization","plotting","python","traveling-salesman-problem","tsp","tsplib-format","tsplib95","visualization"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/RenatoMaynard.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2025-03-18T23:36:42.000Z","updated_at":"2025-04-27T23:24:30.000Z","dependencies_parsed_at":"2025-03-19T01:25:14.690Z","dependency_job_id":"88c923bf-11c5-4c9f-875f-f80d813c82d0","html_url":"https://github.com/RenatoMaynard/TSP-Genetic-Algorithm","commit_stats":null,"previous_names":["renatomaynard/tsp-genetic-algorithm"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/RenatoMaynard/TSP-Genetic-Algorithm","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RenatoMaynard%2FTSP-Genetic-Algorithm","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RenatoMaynard%2FTSP-Genetic-Algorithm/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RenatoMaynard%2FTSP-Genetic-Algorithm/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RenatoMaynard%2FTSP-Genetic-Algorithm/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/RenatoMaynard","download_url":"https://codeload.github.com/RenatoMaynard/TSP-Genetic-Algorithm/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RenatoMaynard%2FTSP-Genetic-Algorithm/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32586187,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-03T06:36:36.687Z","status":"ssl_error","status_checked_at":"2026-05-03T06:36:09.306Z","response_time":103,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["animation","deap","evolutionary-algorithm","genetic-algorithm","heuristic","jupyter-notebook","local-search-algorithm","matplotlib","metaheuristic","numpy","operations-research","optimization","plotting","python","traveling-salesman-problem","tsp","tsplib-format","tsplib95","visualization"],"created_at":"2025-03-23T11:18:21.173Z","updated_at":"2026-05-03T21:32:42.724Z","avatar_url":"https://github.com/RenatoMaynard.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# TSP Genetic Algorithm in Python\n\nThis repository contains a **Genetic Algorithm (GA)** implementation for solving the **Traveling Salesman Problem (TSP)**. It uses the following Python libraries:\n\n- [**tsplib95**](https://pypi.org/project/tsplib95/) to parse TSPLIB-compatible TSP instances.\n- [**DEAP**](https://deap.readthedocs.io/en/master/) to build and evolve the population.\n- [**matplotlib**](https://matplotlib.org/) (for plotting and optional animation).\n- [**numpy**](https://numpy.org/) (optional, for representing routes).\n- [**IPython**](https://ipython.org/) (needed if you want to see the animations inline in a Jupyter notebook).\n\n## Example \n\nBelow are the plots generated by this project:\n\n\u003ctable\u003e\n  \u003ctr\u003e\n    \u003ctd align=\"center\"\u003e\n      \u003cimg src=\"images/TSP_route.png\" alt=\"TSP Route\" width=\"400px\" height=\"300px\"\u003e\u003cbr\u003e\n      \u003cb\u003eFigure 1:\u003c/b\u003e TSP Route \n    \u003c/td\u003e\n    \u003ctd align=\"center\"\u003e\n      \u003cimg src=\"images/TSP_cost_plot.png\" alt=\"TSP cost plot\" width=\"400px\" height=\"300px\"\u003e\u003cbr\u003e\n      \u003cb\u003eFigure 2:\u003c/b\u003e TSP Cost vs Average plot\n    \u003c/td\u003e\n  \u003c/tr\u003e\n\u003c/table\u003e\n\n\n## Table of Contents\n\n1. [Features](#features)\n2. [Installation](#installation)\n3. [Usage](#usage)\n4. [Code Overview](#code-overview)\n   - [Global Variables](#global-variables)\n   - [AnimationTSP Class](#animationtsp-class)\n   - [TSPInstance Class](#tspinstance-class)\n   - [Genetic Algorithm Functions](#genetic-algorithm-functions)\n   - [Helper Functions](#helper-functions)\n   - [Main Function](#main-function)\n5. [Notes on Plotting and Animations](#notes-on-plotting-and-animations)\n6. [License](#license)\n\n---\n\n## Features\n\n- **Simple GA** and an **Advanced GA** mode:\n  - *Simple GA* uses a basic approach for selection, crossover, and mutation.\n  - *Advanced GA* includes larger population sizes, more generations, and can integrate local search steps (such as 2-Opt).\n- **Multiple mutation/perturbation** methods are provided, including:\n  - Swapping two random cities.\n  - Swapping neighbors.\n  - Reversing sub-routes.\n  - 2-Opt local improvement (commented out but can be activated).\n- **Visualization**:\n  - Plots the best cost and average cost over generations.\n  - Optionally animates the evolving route (in Jupyter/IPython environments).\n- **Interactive menu** instead of command-line arguments, making it more straightforward to use within a Python environment or when running the script directly.\n\n---\n\n## Installation\n\n1. **Clone** or **download** this repository.\n2. Install the required libraries:\n   ```bash\n   pip install tsplib95 deap matplotlib numpy ipython\n\n## Usage \n\n1. Run the script (e.g., python ga_interactive.py), or open it in an environment like Jupyter Notebook and run all cells.\n2. You will see a **menu**:\n```\n=========================================\n  TSP GA Solver - Interactive Menu\n=========================================\nEnable route plotting/animation? (`0=No`, `1=Yes`):\nEnter the file path of the TSP instance (e.g., `kroA100.tsp`):\nEnter random seed (integer), e.g. `42`:\nChoose GA version (`0=Simple`, `1=Advanced`):\nUse numpy arrays for individuals? (`0=No`, `1=Yes`):\n```\n3. Enter the requested inputs:\n - Enable route plotting/animation?\n   - `1` enables a line plot of best/average costs and, if using a Jupyter environment, an animation of the route.\n   - `0` disables plotting and animation.\n\n- File path of the TSP instance: e.g., `kroA100.tsp`\n\n- Random seed: Any integer to make results reproducible (e.g., `73`).\n\n- GA version:\n  - `0` runs the simple GA.\n  - `1` runs the advanced GA (larger population, more generations, etc.).\n\n- Use numpy arrays:\n  - `1` to store individuals (routes) as numpy.ndarray\n  - `0` to store individuals as a standard Python list.\n\n4. The algorithm will begin executing. You will see logs of each generation (especially in the advanced version).\n\n5. After finishing, it will output:\n- Best route cost found.\n- Execution time (in seconds).\n- Plots of cost evolution (if plotting is enabled).\n- An animation of the best route per generation (in Jupyter/IPython) if you chose `1` in the first question and you have the environment to display it.\n\n## Code Overview\n\nThe code is structured as follows:\n\n```python\nga_interactive.py\n└── (entry point) main()\n```\n\n\n### Global Variables\n\n- **INF**: A large constant (`9999999`) used to represent infinite distance in the distance matrix.\n- **dist_matrix**: A global 2D list that holds pairwise distances between cities.\n- **use_numpy**: A global integer set from the user’s input in the menu (`0` or `1`). If `1`, routes are stored as NumPy arrays.\n\n### AnimationTSP Class\n\n```python\nclass AnimationTSP:\n    ...\n```\n- **Purpose:** Creates and manages an animation of the TSP route as it evolves.\n\n- **Methods:**\n  - **init(self, history, x_coords, y_coords, costs):** Receives the full solution history (each solution is a permutation of city indices), corresponding cost list, and the x/y coordinates of each city.\n  - **init_animation(self):** Initializes the plot with city nodes.\n  - **update_animation(self, frame):** Updates the route lines for each frame in the history.\n  - **animate_routes(self):** Puts everything together and shows the animation in Jupyter using FuncAnimation.\n \n### TSPInstance Class\n\n```python\nclass TSPInstance:\n    ...\n```\n- **Purpose**:\n  - Loads a TSP instance from a TSPLIB file.\n  - Extracts node coordinates if they exist (for 2D-based problems: `EUC_2D`, `GEO`, `ATT`).\n  - Generates the global distance matrix (`dist_matrix`) to quickly retrieve distances.\n- **Key methods**:\n  - **init(self, plot_route, instance_file):** Sets up the plotting option and reads the TSP file. Checks if coordinates can be plotted.\n  - **generate_distance_matrix(self):** Builds the matrix `dist_matrix[i][j]` = distance from city `i` to `j`.\n    \n### Genetic Algorithm Functions\n1. **Fitness Evaluation**\n```python\ndef total_cost(route):\n    ...\n```\n  - Computes the total distance of the closed tour represented by `route`.\n2. **Initialization**\n```python\ndef nearest_neighbor(n):\n    ...\n```\n  - Randomly chooses a start city, then with probability 0.4 applies a Nearest Neighbor approach; otherwise fully shuffles the cities.\n  - Returns either a Python list or a NumPy array of the city permutation (depending on `use_numpy`).\n3. **Mutation (and Perturbations)**\n```python\ndef mutate(route):\n    ...\n```\n  - Applies one of several custom perturbation methods (e.g., reversing a sub-route).\n  - You can switch out different mutation methods (e.g., `perturbation_swap_two`, `perturbation_swap_neighbors`, `two_opt`).\n4. **GA Routines**\n    - ga_simple\n        - Population size = 50\n        - Generations = 200\n        - Uses `eaSimple` from DEAP for a straightforward evolution loop.\n    - ga_advanced\n        - Larger population (100)\n        - More generations (1000)\n        - Custom loop (with optional local searches, more detailed logs, etc).\n### Helper Functions\n- `two_opt(route)`: An optional local search to reverse edges in the route if it yields improvement.\n- `perturbation_swap_two`, `perturbation_swap_neighbors`, `perturbation_reverse_subroute`: Different ways to shuffle or reverse parts of the route.\n- `plot_evolution(min_values, avg_values)`: Creates a line chart showing how the best cost and average cost evolve over generations.\n\n### Main Function \n```python\ndef main():\n    ...\n```\n- Presents a **menu** of questions to the user:\n    1. Enable route plotting/animation? (`0` or `1`)\n    2. TSP instance file path (e.g., `kroA100.tsp`)\n    3. Seed (integer)\n    4. Version of GA: `0 = simple`, `1 = advanced`\n    5. use_numpy: `0` or `1`\n- Creates a `TSPInstance` based on these answers, generates the distance matrix, and then calls `ga_simple` or `ga_advanced`.\n\n### Notes on Plotting and Animations \n1. **Ploting:**  The script uses `matplotlib.pyplot` to show the best and average cost across generations.\n  - If `plot_flag == 1`, a figure will pop up at the end of the run.\n2. **Animation:**  The route animation (showing how the best route changes) works best in a **Jupyter/IPython** environment.\n    - If run in a standard terminal, you might **not** see the inline animation (you can still save it to a file, if you modify the code).\n    - The `FuncAnimation` calls `to_jshtml()`, so an inline notebook display is ideal.\n   \n### License\nThis repository is licensed under the MIT License. You are free to modify, share, and use this code for your own projects.\n\n---\n\nEnjoy solving TSP instances with this Genetic Algorithm! If you have any questions, feel free to open an issue or submit a pull request.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frenatomaynard%2Ftsp-genetic-algorithm","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frenatomaynard%2Ftsp-genetic-algorithm","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frenatomaynard%2Ftsp-genetic-algorithm/lists"}