| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
| Name | Name | Last commit date | ||
|---|---|---|---|---|
This project provides a high-performance implementation of the A* ("A-Star") pathfinding algorithm (based on this Lisp implementation by Andrew Kravchuck) along with various maze generation techniques to showcase how this algorithm works, as well as an advanced animated visualization of pathfinding in these mazes. The mazes are generated using many diverse approaches, each providing a different visual look and feel and also potential challenges for a pathfinding algorithm. The A* algorithm is designed to efficiently find the shortest path in these mazes, taking into consideration various heuristic functions and neighbor enumerators.
The A* algorithm implementation focuses on efficiency and scalability. Key aspects include:
Custom Priority Queue: The priority queue is a fundamental component of the A* algorithm, used to manage the open set (frontier) of nodes to be explored. In this implementation, the priority queue is optimized for fast insertion and extraction of elements based on their priority values, which represent the estimated total cost (distance traveled + heuristic) to reach the goal. This allows the algorithm to quickly focus on the most promising nodes.
Coordinate Encoding: The system supports both integer and float coordinates, which are encoded efficiently to optimize memory usage and computation. This encoding process involves converting floating-point coordinates into a unique integer representation, ensuring precise and quick decoding. The encoding scheme supports a wide range of values, accommodating both fine-grained precision and large-scale maps.
Heuristic Functions: A variety of heuristic functions are available, including Manhattan, Octile, and Euclidean distance heuristics. Each heuristic offers a different way to estimate the cost to reach the goal from a given node, balancing accuracy with computational efficiency. The choice of heuristic can significantly affect the performance of the A* algorithm, with more accurate heuristics generally leading to faster pathfinding at the cost of additional computation.
Neighbor Enumeration: The algorithm provides customizable neighbor enumerators that define how neighboring nodes are considered during the pathfinding process. Options include 4-directional, 8-directional, and more complex movement patterns. This flexibility allows the algorithm to handle various types of terrain and movement costs, such as diagonal movement being more expensive than orthogonal movement.
This project includes a rich variety of maze generation algorithms, each creating unique patterns and challenges. Below is a detailed explanation of each method:
Diffusion-Limited Aggregation (DLA):
Game of Life:
One-Dimensional Automata:
Langton's Ant:
Voronoi Diagram:
Fractal Division:
Wave Function Collapse:
Growing Tree:
Terrain-Based:
Musicalized:
Quantum-Inspired:
Artistic:
Cellular Automaton:
Fourier-Based:
Reaction-Diffusion:
Each method in this collection offers a distinct visual and structural style, making it possible to explore a wide range of maze characteristics and challenges. These mazes are suitable for testing various pathfinding algorithms and for generating visually compelling visualizations.
In maze generation, ensuring that the resulting structures are not only visually appealing but also functionally navigable is critical. Various techniques and methods are employed to validate the generated mazes and modify them if they don't meet specific criteria, such as solvability, complexity, or connectivity. This section details the philosophy, theory, and practical implementations behind these techniques, with a focus on ensuring high-quality maze structures.
The approach to maze validation and adjustment involves a multi-step process:
This process ensures that each maze not only provides a challenging and engaging environment but also maintains a balance between complexity and solvability.
smart_hole_puncher
ensure_connectivity
add_walls
remove_walls
add_room_separators
break_up_large_room
break_up_large_areas
create_simple_maze
connect_areas
connect_disconnected_areas
bresenham_line
validate_and_adjust_maze
generate_and_validate_maze
The visualization component in this project is designed to provide a comprehensive and interactive display of both the maze generation process and the pathfinding algorithms at work. This component uses the matplotlib library to create detailed visual representations that highlight the complexities and intricacies of maze structures and pathfinding strategies. Key elements of the visualization include:
Walls and Floors: The visualization distinctly represents walls and floors using a two-color scheme. Walls are typically rendered in a dark color (e.g., deep blue or gray), while floors are displayed in a contrasting light color (e.g., white or light gray). This clear differentiation helps users easily identify passable and impassable areas within the maze.
Color Mapping: The code allows for the customization of wall and floor colors. This is particularly useful for creating visual themes or adjusting the visualization for different viewing conditions (e.g., color blindness). The LinearSegmentedColormap from matplotlib can be used to define custom gradients for different maze elements.
Exploration Order: During the pathfinding process, the visualization dynamically displays the exploration order of the algorithm. This is achieved by coloring explored cells using a gradient that represents the progression of exploration. Lighter shades indicate earlier exploration, while darker shades denote later exploration stages. The use of an exploration colormap helps visualize the pathfinding algorithm's exploration strategy and efficiency.
Path Discovery: As the algorithm discovers the path from the start to the goal, the visualization highlights the path using a distinct color (e.g., blue or green). The path is typically represented as a continuous line, indicating the sequence of cells that constitute the solution. The visualization updates in real-time, allowing viewers to see how the path evolves as the algorithm progresses.
Markers for Start and Goal Points: The start and goal points are clearly marked with distinct symbols (e.g., circles or stars) and colors (e.g., green for the start, red for the goal). These markers remain visible throughout the visualization, providing consistent reference points for the viewer.
Customization Options: The visualization component offers extensive customization options for colors, allowing users to adjust the appearance of walls, floors, paths, exploration stages, and start/goal markers. This customization is facilitated through parameters passed to the visualization functions, enabling users to tailor the display to their preferences or specific use cases.
Colormap Selection: For the exploration and path colors, users can select from predefined colormaps or create custom ones using LinearSegmentedColormap. This flexibility ensures that the visualization can be adapted to various aesthetic preferences or accessibility needs.
Transparency and Layering: The visualization supports transparency and layering effects, particularly for the exploration map. By adjusting the alpha value, users can overlay the exploration progress on top of the maze structure without obscuring the underlying details. This feature is useful for simultaneously visualizing the explored area and the structural layout of the maze.
Frame Generation: The visualization is animated by generating frames that capture the state of the maze and pathfinding process at each time step. The code uses concurrent processing to efficiently generate these frames, leveraging multiple CPU cores for faster rendering. Each frame is created by plotting the maze, exploration progress, and current path status.
Animation Playback: The frames can be compiled into an animation using FuncAnimation from matplotlib.animation. The playback speed can be adjusted by setting the frames per second (FPS), allowing for slower or faster visualization of the pathfinding process. The animation provides a smooth and continuous representation of the algorithm's operation, from initial exploration to final pathfinding.
Output Formats: The frames can be saved individually as images or compiled into a video. Each frame is saved as an individual image in the specified frame_format (e.g., PNG, JPG). This option is useful for creating high-quality image sequences or for detailed post-processing of individual frames. Alternatively, if save_as_frames_only is set to False, the frames are compiled into an animation in formats such as MP4. For MP4 exports, the FFMpegWriter is used, allowing for fine-tuned control over encoding parameters, such as bitrate and codec settings. This ensures high-quality video output suitable for presentations or further analysis.
Resource Management: To manage disk space and avoid clutter, the code includes functionality to delete small or temporary files after the animation or frame sequence is saved. This helps maintain a clean working directory and ensures that only the most relevant files are retained. This feature is particularly useful when saving individual frames, as it can help prevent the accumulation of numerous image files.
If you have saved the frames as individual image files and wish to manually assemble them into an MP4 video, you can use FFmpeg. You can download it from the official FFmpeg website or install it via a package manager. Alternatively, you can download a pre-compiled binary from the most recent version here (recommended; note that if you do this, you'll have to copy the binary to /usr/bin/ and do chmod +x ffmpeg to make it executable. To check which version of FFmpeg you're actually using, try which ffmpeg). Additionally, you may need the bc command for calculations, which can be installed using:
sudo apt install bcAssuming your frames are named sequentially (e.g., frame_0001.png, frame_0002.png, etc.) and stored in the current directory, you can use the following command to generate a 30-second video file using x265:
cd /home/ubuntu/visual_astar_python/maze_animations/animation_20240805_114757/ # Change to the directory containing the frames-- this is just an example
ffmpeg -framerate $(echo "($(find . -maxdepth 1 -type f -name 'frame_*.png' | wc -l) + 30 - 1) / 30" | bc) -i frame_%05d.png -vf "pad=ceil(iw/2)*2:ceil(ih/2)*2,scale=3840:2160" -c:v libx265 -preset slow -crf 28 -pix_fmt yuv420p -x265-params "pools=16:bframes=8:ref=4:no-open-gop=1:me=star:rd=4:aq-mode=3:aq-strength=1.0" -movflags +faststart output.mp4For encoding using x264, use:
ffmpeg -framerate $(echo "($(find . -maxdepth 1 -type f -name 'frame_*.png' | wc -l) + 30 - 1) / 30" | bc) -i frame_%05d.png -vf "pad=ceil(iw/2)*2:ceil(ih/2)*2" -c:v libx264 -crf 18 -pix_fmt yuv420p -threads 16 -movflags +faststart output_x264.mp4These commands and explanations should help you efficiently create high-quality MP4 videos from a sequence of frames using FFmpeg.
Clone the repo and set up a virtual environment with the required packages using (tested on Python 3.12 and Ubuntu 22):
git clone https://github.com/Dicklesworthstone/visual_astar_python.git
cd visual_astar_python
python -m venv venv
source venv/bin/activate
python -m pip install --upgrade pip
python -m pip install wheel
python -m pip install --upgrade setuptools wheel
pip install -r requirements.txtThe code is tested with Python 3.12. If you want to use that version without messing with your system Python version, then on Ubuntu you can install and use PyEnv like so:
if ! command -v pyenv &> /dev/null; then
sudo apt-get update
sudo apt-get install -y build-essential libssl-dev zlib1g-dev libbz2-dev \
libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev \
xz-utils tk-dev libffi-dev liblzma-dev python3-openssl git
git clone https://github.com/pyenv/pyenv.git ~/.pyenv
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.zshrc
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.zshrc
echo 'eval "$(pyenv init --path)"' >> ~/.zshrc
source ~/.zshrc
fi
cd ~/.pyenv && git pull && cd -
pyenv install 3.12
cd ~
git clone https://github.com/Dicklesworthstone/visual_astar_python.git
cd visual_astar_python
pyenv local 3.12
python -m venv venv
source venv/bin/activate
python -m pip install --upgrade pip
python -m pip install wheel
python -m pip install --upgrade setuptools wheel
pip install -r requirements.txt
To generate and visualize a maze, run the main script with the desired parameters:
python main.pyYou can see what it looks like running here:
This project includes several parameters that users can configure to customize the output of maze generation and pathfinding visualization. Key parameters include:
These parameters provide users with extensive control over the behavior and appearance of the generated mazes and visualizations, allowing for fine-tuning according to specific requirements or preferences.
The A* algorithm is a sophisticated method for finding the shortest path in various environments, whether it's navigating a complex maze or plotting a course through a dynamically changing landscape. Unlike simpler algorithms, A* intelligently evaluates paths by considering both the journey already taken and the estimated distance to the goal. This dual approach makes A* not only a pathfinder but a path optimizer, ensuring the selected path is the most efficient.
Imagine you're in a vast maze; A* doesn't just explore paths blindly. It uses a strategic approach akin to a seasoned traveler who checks their progress and considers the remaining distance to the destination at every decision point. This ability to foresee and plan makes A* particularly adept at avoiding dead ends and minimizing travel time.
The Journey So Far (g-cost): This aspect involves calculating the exact cost from the start point to the current position. It's like keeping track of the miles traveled during a road trip. By accumulating these costs, A* can compare different paths to the same point, ensuring it chooses the most efficient one.
The Journey Ahead (h-cost): Known as the heuristic estimate, this component predicts the cost from the current position to the goal. It's a calculated guess based on the nature of the environment. For example, in a grid, this might be the Euclidean distance (straight-line distance), which provides a quick and reasonably accurate estimate of the remaining journey.
The sum of these two values (g-cost + h-cost) forms the f-cost, which A* uses to prioritize paths. This combination ensures that A* not only seeks to minimize the total travel cost but also maintains a focus on progressing towards the goal.
A* stands out for its efficiency and effectiveness, particularly in comparison to simpler algorithms:
Depth-First Search (DFS) explores as deep as possible along one branch before backtracking. While it may find a path, it often does so inefficiently, sometimes missing the shortest path entirely due to its lack of goal-awareness and tendency to get trapped in deep branches.
Breadth-First Search (BFS) methodically explores all nodes at the present depth before moving on to the next. While BFS guarantees finding the shortest path in an unweighted graph, it is computationally expensive and memory-intensive, especially in large graphs, as it explores all nodes without any consideration of the goal's location.
Dijkstra's Algorithm is a precursor to A* that calculates the shortest path by considering the total cost from the start node to each node. However, it does not incorporate a heuristic, treating all paths equally regardless of their direction relative to the goal. This can lead to unnecessary exploration and inefficiencies, particularly in large graphs with varied edge costs.
A* merges the strengths of Dijkstra's thorough cost analysis with an informed heuristic approach, directing its search towards the goal and avoiding unnecessary paths. This combination allows it to find the shortest path efficiently, making it suitable for a wide range of practical applications.
A* is widely used in various domains due to its reliability and efficiency:
Video Games: A* is the backbone of many AI pathfinding systems, guiding characters through complex virtual worlds with precision. Its ability to navigate around obstacles and efficiently reach objectives makes it ideal for real-time strategy games and role-playing games.
Robotics: In robotics, A* helps autonomous robots navigate through environments, such as factory floors or outdoor terrains. The algorithm enables robots to avoid obstacles, plan efficient routes, and respond to dynamic changes in their surroundings.
Navigation Systems: A* is used in GPS navigation systems to find the quickest route between two points, considering factors like road distances and traffic conditions.
AI and Machine Learning: A* is used in AI for problem-solving, such as solving puzzles or planning tasks. Its ability to incorporate different heuristics allows it to be adapted to various types of problems.
This project's implementation of A* goes beyond standard features, incorporating advanced techniques to enhance performance and versatility. Most of the credit for these goes to Andrew Kravchuck, who wrote the Lisp implementation this is based on:
Smart Organization: The algorithm uses a priority queue to manage paths, ensuring that the most promising paths are explored first. This efficient data structure reduces the time spent evaluating less optimal paths.
Precision Handling: The implementation supports both integer and floating-point coordinates, making it adaptable to different scenarios, from simple grid maps to detailed real-world environments.
Adaptive Heuristics: It allows for various heuristic functions, such as Manhattan, Euclidean, or Octile distances, which can be tailored to the specifics of the problem space, optimizing the search process.
Complex Terrain Navigation: The implementation can handle diverse movements, including diagonal and custom paths, enhancing its capability to navigate through varied terrains.
Efficient Path Reconstruction: Upon reaching the goal, the implementation efficiently reconstructs the path, ensuring minimal computational overhead in finalizing the route.
Robust Error Handling: The algorithm gracefully manages exceptional situations, such as encountering impassable regions or unsolvable configurations, providing clear feedback to users.
Optimized Data Structures: The use of bit fields for coordinate encoding enhances memory efficiency and processing speed, crucial for handling large-scale environments or high-resolution grids.
This project is licensed under the MIT License. See the LICENSE file for details.
Thanks for your interest in my open-source project! I hope you find it useful. You might also find my commercial web apps useful, and I would really appreciate it if you checked them out:
YoutubeTranscriptOptimizer.com makes it really quick and easy to paste in a YouTube video URL and have it automatically generate not just a really accurate direct transcription, but also a super polished and beautifully formatted written document that can be used independently of the video.
The document basically sticks to the same material as discussed in the video, but it sounds much more like a real piece of writing and not just a transcript. It also lets you optionally generate quizzes based on the contents of the document, which can be either multiple choice or short-answer quizzes, and the multiple choice quizzes get turned into interactive HTML files that can be hosted and easily shared, where you can actually take the quiz and it will grade your answers and score the quiz for you.
FixMyDocuments.com lets you submit any kind of document— PDFs (including scanned PDFs that require OCR), MS Word and Powerpoint files, images, audio files (mp3, m4a, etc.) —and turn them into highly optimized versions in nice markdown formatting, from which HTML and PDF versions are automatically generated. Once converted, you can also edit them directly in the site using the built-in markdown editor, where it saves a running revision history and regenerates the PDF/HTML versions.
In addition to just getting the optimized version of the document, you can also generate many other kinds of "derived documents" from the original: interactive multiple-choice quizzes that you can actually take and get graded on; slick looking presentation slides as PDF or HTML (using LaTeX and Reveal.js), an in-depth summary, a concept mind map (using Mermaid diagrams) and outline, custom lesson plans where you can select your target audience, a readability analysis and grade-level versions of your original document (good for simplifying concepts for students), Anki Flashcards that you can import directly into the Anki app or use on the site in a nice interface, and more.
| Back | FazBrowse Home | New Git URL |