write a mandelbrot set visualizer in python it should be able to - zoom in - zoom out -…
- User
write a mandelbrot set visualizer in python it should be able to
- zoom in
- zoom out
- rerender the resolution when zooming
- multithreadding
- Assistant
write a mandelbrot set visualizer in python it should be able to
Creating a Mandelbrot set visualizer in Python with features such as zooming in/out, dynamic resolution adjustment, and multithreading can be efficiently achieved using the tkinter library for the GUI, Pillow for image handling, and the threading module for multithreading.
Below is a comprehensive Python script that fulfills your requirements:
Before running the script, ensure you have the necessary libraries installed. You can install them using pip:
pip install pillow
import tkinter as tk
from PIL import Image, ImageTk
import threading
import math
class MandelbrotVisualizer:
def __init__(self, master, width=800, height=600, max_iter=1000):
self.master = master
self.width = width
self.height = height
self.max_iter = max_iter
# Initial view parameters
self.re_start = -2.0
self.re_end = 1.0
self.im_start = -1.5
self.im_end = 1.5
# Create canvas
self.canvas = tk.Canvas(master, width=self.width, height=self.height, bg='black')
self.canvas.pack()
# Bind mouse and keyboard events
self.canvas.bind("<Button-1>", self.zoom_in)
self.canvas.bind("<Button-3>", self.zoom_out)
self.master.bind("<Key>", self.key_pressed)
# Initialize image
self.image = Image.new("RGB", (self.width, self.height), "black")
self.photo = ImageTk.PhotoImage(self.image)
self.image_on_canvas = self.canvas.create_image(0, 0, anchor=tk.NW, image=self.photo)
# Start rendering
self.render()
def key_pressed(self, event):
"""Handle key press events for zooming."""
if event.char == '+':
self.zoom(0.9) # Zoom in by 10%
elif event.char == '-':
self.zoom(1.1) # Zoom out by 10%
def zoom_in(self, event):
"""Zoom in towards the mouse click position."""
self.zoom(0.9, event.x, event.y)
def zoom_out(self, event):
"""Zoom out from the mouse click position."""
self.zoom(1.1, event.x, event.y)
def zoom(self, scale_factor, x=None, y=None):
"""Adjust the view window based on zoom."""
if x is None or y is None:
# Zoom towards the center
center_re = (self.re_start + self.re_end) / 2
center_im = (self.im_start + self.im_end) / 2
else:
# Zoom towards the mouse position
center_re = self.re_start + (x / self.width) * (self.re_end - self.re_start)
center_im = self.im_start + (y / self.height) * (self.im_end - self.im_start)
width_re = (self.re_end - self.re_start) * scale_factor
height_im = (self.im_end - self.im_start) * scale_factor
self.re_start = center_re - width_re / 2
self.re_end = center_re + width_re / 2
self.im_start = center_im - height_im / 2
self.im_end = center_im + height_im / 2
# Optionally adjust resolution based on zoom level
# For simplicity, we'll keep the resolution constant in this example
self.render()
def render(self):
"""Render the Mandelbrot set using multithreading."""
# Create a new image
self.image = Image.new("RGB", (self.width, self.height), "black")
pixels = self.image.load()
# Number of threads
num_threads = 8
threads = []
rows_per_thread = self.height // num_threads
# Start threads
for i in range(num_threads):
start_row = i * rows_per_thread
# Ensure the last thread handles all remaining rows
end_row = (i + 1) * rows_per_thread if i != num_threads - 1 else self.height
thread = threading.Thread(target=self.compute_set, args=(pixels, start_row, end_row))
threads.append(thread)
thread.start()
# Wait for all threads to finish
for thread in threads:
thread.join()
# Update the image on the canvas
self.photo = ImageTk.PhotoImage(self.image)
self.canvas.itemconfig(self.image_on_canvas, image=self.photo)
def compute_set(self, pixels, start_row, end_row):
"""Compute a portion of the Mandelbrot set and update pixels."""
for y in range(start_row, end_row):
im = self.im_start + (y / self.height) * (self.im_end - self.im_start)
for x in range(self.width):
re = self.re_start + (x / self.width) * (self.re_end - self.re_start)
c = complex(re, im)
z = 0 + 0j
iter_count = 0
while abs(z) <= 2 and iter_count < self.max_iter:
z = z * z + c
iter_count += 1
color = self.get_color(iter_count)
pixels[x, y] = color
def get_color(self, iter_count):
"""Map the iteration count to a color."""
if iter_count == self.max_iter:
return (0, 0, 0) # Black for points inside the Mandelbrot set
# Color mapping: Here we use a simple gradient from blue to red
hue = int(255 * iter_count / self.max_iter)
return (hue, 0, 255 - hue)
def main():
root = tk.Tk()
root.title("Mandelbrot Set Visualizer")
visualizer = MandelbrotVisualizer(root, width=800, height=600, max_iter=1000)
root.mainloop()
if __name__ == "__main__":
main()
Imports:
tkinter for creating the GUI.Pillow (PIL) for image creation and manipulation.threading for parallel computation.MandelbrotVisualizer Class:
Initialization (__init__):
tkinter canvas to display the Mandelbrot set.+ to zoom in and - to zoom out).Event Handlers:
key_pressed: Handles keyboard inputs for zooming.zoom_in and zoom_out: Handle mouse click events to zoom towards or away from the clicked point.zoom Method:
render Method:
compute_set Method:
get_color Method:
main Function:
tkinter root window.Zoom In/Out:
+ to zoom in and - to zoom out centered on the current view.Dynamic Resolution Adjustment:
zoom method to adjust self.width and self.height based on the zoom level and reinitialize the image accordingly.Multithreading:
Save the script to a file, e.g., mandelbrot_visualizer.py.
Ensure you have installed the Pillow library.
Run the script using Python:
python mandelbrot_visualizer.py
A window titled "Mandelbrot Set Visualizer" will open displaying the Mandelbrot set.
Interact with the Visualizer:
+ key.- key.Dynamic Resolution Adjustment: To fully implement dynamic resolution adjustment, modify the zoom method to change self.width and self.height, then recreate the canvas and image accordingly.
Performance Improvements:
get_color method to use more sophisticated color mapping for better visual appeal.multiprocessing module or libraries like numpy for vectorized computations.User Interface Enhancements:
This script provides a solid foundation for a Mandelbrot set visualizer with the requested features. You can further enhance and customize it based on your specific needs and preferences.
Not yet included in a published release.
MandelbrotVisualizer.