|
| 1 | +""" |
| 2 | +Plot the Mandelbrot set using parallel workers. |
| 3 | +
|
| 4 | +Usage: |
| 5 | +$ python parallelization.py |
| 6 | +""" |
| 7 | + |
| 8 | +import functools |
| 9 | +import multiprocessing |
| 10 | +import os |
| 11 | +import time |
| 12 | +from dataclasses import dataclass |
| 13 | +from math import log |
| 14 | +from typing import Callable, Iterable |
| 15 | + |
| 16 | +import numpy as np |
| 17 | +from PIL import Image |
| 18 | + |
| 19 | +from splitting.multidimensional import Bounds, split_multi |
| 20 | + |
| 21 | +IMAGE_WIDTH, IMAGE_HEIGHT = 1280, 720 |
| 22 | +CENTER = -0.7435 + 0.1314j |
| 23 | +SCALE = 0.0000025 |
| 24 | +MAX_ITERATIONS = 256 |
| 25 | +ESCAPE_RADIUS = 1000 |
| 26 | +NUM_CHUNKS = os.cpu_count() or 4 |
| 27 | + |
| 28 | + |
| 29 | +class Chunk: |
| 30 | + """A chunk of the image to be computed and rendered.""" |
| 31 | + |
| 32 | + def __init__(self, bounds: Bounds) -> None: |
| 33 | + self.bounds = bounds |
| 34 | + self.height = bounds.size[0] |
| 35 | + self.width = bounds.size[1] |
| 36 | + self.pixels = np.zeros((self.height, self.width), dtype=np.uint8) |
| 37 | + |
| 38 | + def __getitem__(self, coordinates) -> int: |
| 39 | + """Get the value of a pixel at the given absolute coordinates.""" |
| 40 | + return self.pixels[self.bounds.offset(*coordinates)] |
| 41 | + |
| 42 | + def __setitem__(self, coordinates, value: int) -> None: |
| 43 | + """Set the value of a pixel at the given absolute coordinates.""" |
| 44 | + self.pixels[self.bounds.offset(*coordinates)] = value |
| 45 | + |
| 46 | + |
| 47 | +@dataclass |
| 48 | +class MandelbrotSet: |
| 49 | + max_iterations: int |
| 50 | + escape_radius: float = 2.0 |
| 51 | + |
| 52 | + def __contains__(self, c: complex) -> bool: |
| 53 | + return self.stability(c) == 1 |
| 54 | + |
| 55 | + def stability(self, c: complex, smooth=False, clamp=True) -> float: |
| 56 | + value = self.escape_count(c, smooth) / self.max_iterations |
| 57 | + return max(0.0, min(value, 1.0)) if clamp else value |
| 58 | + |
| 59 | + def escape_count(self, c: complex, smooth=False) -> int | float: |
| 60 | + z = 0 + 0j |
| 61 | + for iteration in range(self.max_iterations): |
| 62 | + z = z**2 + c |
| 63 | + if abs(z) > self.escape_radius: |
| 64 | + if smooth: |
| 65 | + return iteration + 1 - log(log(abs(z))) / log(2) |
| 66 | + return iteration |
| 67 | + return self.max_iterations |
| 68 | + |
| 69 | + |
| 70 | +def timed(function: Callable) -> Callable: |
| 71 | + @functools.wraps(function) |
| 72 | + def wrapper(*args, **kwargs): |
| 73 | + start = time.perf_counter() |
| 74 | + result = function(*args, **kwargs) |
| 75 | + end = time.perf_counter() |
| 76 | + print(f"{function.__name__}() took {end - start:.2f} seconds") |
| 77 | + return result |
| 78 | + |
| 79 | + return wrapper |
| 80 | + |
| 81 | + |
| 82 | +def main() -> None: |
| 83 | + for worker in (process_chunks_parallel, process_chunks_sequential): |
| 84 | + image = compute(worker) |
| 85 | + image.show() |
| 86 | + |
| 87 | + |
| 88 | +@timed |
| 89 | +def process_chunks_sequential(chunked_bounds: Iterable[Bounds]) -> list[Chunk]: |
| 90 | + return list(map(generate_chunk, chunked_bounds)) |
| 91 | + |
| 92 | + |
| 93 | +@timed |
| 94 | +def process_chunks_parallel(chunked_bounds: Iterable[Bounds]) -> list[Chunk]: |
| 95 | + with multiprocessing.Pool() as pool: |
| 96 | + return pool.map(generate_chunk, chunked_bounds) |
| 97 | + |
| 98 | + |
| 99 | +def generate_chunk(bounds: Bounds) -> Chunk: |
| 100 | + """Generate a chunk of pixels for the given bounds.""" |
| 101 | + chunk = Chunk(bounds) |
| 102 | + mandelbrot_set = MandelbrotSet(MAX_ITERATIONS, ESCAPE_RADIUS) |
| 103 | + for y, x in bounds: |
| 104 | + c = transform(y, x) |
| 105 | + instability = 1 - mandelbrot_set.stability(c, smooth=True) |
| 106 | + chunk[y, x] = int(instability * 255) |
| 107 | + return chunk |
| 108 | + |
| 109 | + |
| 110 | +def transform(y: int, x: int) -> complex: |
| 111 | + """Transform the given pixel coordinates to the complex plane.""" |
| 112 | + im = SCALE * (IMAGE_HEIGHT / 2 - y) |
| 113 | + re = SCALE * (x - IMAGE_WIDTH / 2) |
| 114 | + return complex(re, im) + CENTER |
| 115 | + |
| 116 | + |
| 117 | +def compute(worker: Callable) -> Image.Image: |
| 118 | + """Render the image using the given worker function.""" |
| 119 | + chunks = worker(split_multi(NUM_CHUNKS, IMAGE_HEIGHT, IMAGE_WIDTH)) |
| 120 | + return combine(chunks) |
| 121 | + |
| 122 | + |
| 123 | +def combine(chunks: list[Chunk]) -> Image.Image: |
| 124 | + """Combine the chunks into a single image.""" |
| 125 | + pixels = np.zeros((IMAGE_HEIGHT, IMAGE_WIDTH), dtype=np.uint8) |
| 126 | + for chunk in chunks: |
| 127 | + pixels[chunk.bounds.slices()] = chunk.pixels |
| 128 | + return Image.fromarray(pixels, mode="L") |
| 129 | + |
| 130 | + |
| 131 | +if __name__ == "__main__": |
| 132 | + main() |
0 commit comments