def __init__(self, parent, h, x=-0.75, y=0, m=1.5, iterations=None, imgWidth=None, imgHeight=None, save=False, multi=True): Frame.__init__(self, parent) self.parent = parent self.parent.title("Mandelbrot") self.pack(fill=BOTH, expand=1) self.canvas = Canvas(self) if None in {imgWidth, imgHeight}: imgWidth, imgHeight = h, h if imgWidth > imgHeight: ratio = imgHeight/imgWidth self.canvasW, self.canvasH = h, round(h*ratio) else: ratio = imgWidth/imgHeight self.canvasW, self.canvasH = round(h*ratio), h self.fractal = Mandelbrot(self.canvasW, self.canvasH, x=x, y=y, m=m, iterations=iterations, w=imgWidth, h=imgHeight, multi=multi) self.setPalette() self.pixelColors = [] self.img = None self.save = save self.draw() parent.bind("<Button-1>", self.zoomIn) parent.bind("<Button-3>", self.zoomOut) parent.bind("<Control-1>", self.shiftView) parent.bind("<Control-3>", self.changePalette) parent.bind("<Button-2>", self.saveImage)
def __init__(self): self.turtle = turtle.Turtle() self.screen = self.turtle.getscreen() self.widhalf = 400 self.heihalf = 400 self.bound = [-2, -2, 2, 2] self.center = [0,0] self.turtle.hideturtle() self.screen.tracer(2000,0) self.turtle.pensize(1) self.screen.screensize(400, 400) for i in range(-self.widhalf,self.widhalf): self.turtle.pu() self.turtle.goto(i,-self.heihalf) self.turtle.pd() for j in range(-self.heihalf,self.heihalf): c = Complex(i*2/self.widhalf, j*2/self.heihalf) M = Mandelbrot(c,50) color = M.get_color() self.turtle.pencolor(color) self.turtle.goto(i,j) self.screen.onclick(self.click) self.screen.listen() self.screen.mainloop() print("here");
def get_mandelbrot_details(**viewport_kwargs): # show the post with the given id, the id is an integer global lock with lock: m = Mandelbrot(interactive=False) img = m.to_png(**viewport_kwargs) return img
def run(self): xmin = -2.025 xmax = 0.6 ymin = -1.125 ymax = 1.125 width = 400 height = 400 maxiter = 255 mandel = Mandelbrot(xmin, xmax, ymin, ymax, width, height, maxiter) mandel.plot_mandelbrot()
def __init__(self, w=512, h=512, real_bounds=(-2.0, 1.0), imag_bounds=(-1.5, 1.5), iterations=512, min_path=0): Mandelbrot.__init__(self, w, h, real_bounds, imag_bounds, iterations) self.min_path = min_path self.max = 0 self.samples = 0
def draw(self): self.execute = False for i in range(-150, 150): for j in range(-150, 150): complexnum = Complex(self.cx + self.maxcp / self.maxtp * i, self.cy + self.maxcp / self.maxtp * j) mandelbrot = Mandelbrot(complexnum) self.t.penup() self.t.goto(i, j) self.t.pendown() self.t.pencolor(mandelbrot.get_color()) self.t.forward(1) self.execute = True
class TestMandelbrot(unittest.TestCase): def setUp(self): self.mandelbrot = Mandelbrot(complex(5, 5), complex(10, 10)) def test_map_plane(self): self.mandelbrot.map_plane((500, 800), (200, 100), (400, 600)) self.assertEqual(self.mandelbrot.plane_low.real, 7) self.assertEqual(self.mandelbrot.plane_high.real, 9) self.assertEqual(self.mandelbrot.plane_low.imag, 5.625) self.assertEqual(self.mandelbrot.plane_high.imag, 8.75) def test_set_resolution(self): self.assertEqual(self.mandelbrot.resolution, (1, 1)) self.mandelbrot.set_resolution((400, 500)) self.assertEqual(self.mandelbrot.resolution, (0.0125, 0.01)) def test_tends_inf(self): self.assertEqual(self.mandelbrot.tends_inf(complex(0, 1)), False) self.assertEqual(self.mandelbrot.tends_inf(complex(0, 2)), True) def test_equ(self): z = complex(0, 0) c = complex(-1, 1) new_z = self.mandelbrot.equ(z, c) self.assertEqual(new_z, self.mandelbrot.equ(z, c)) def test__mandel_elem(self): self.assertEqual(self.mandelbrot._mandel_elem(complex(0, -1)), 0) self.assertEqual(self.mandelbrot._mandel_elem(complex(2, -1)), 255)
def draw(self): self.turtle.clear() for i in range(-self.widhalf,self.widhalf): self.turtle.pu() self.turtle.goto(i,-self.heihalf) self.turtle.pd() for j in range(-self.heihalf,self.heihalf): mwidhalf = (self.bound[2] - self.bound[0])/2 mheihalf = (self.bound[3] - self.bound[1])/2 a = i*mwidhalf/self.widhalf + self.center[0] b = j*mheihalf/self.heihalf + self.center[1] c = Complex(a, b) M = Mandelbrot(c,50) color = M.get_color() self.turtle.pencolor(color) self.turtle.goto(i,j)
def __draw__(self): self.t.clear() self.t.penup() for i in range(int(self.curcanvwidthneg), int(self.curcanvwidthpos)): for j in range(int(self.curcanvlengthneg), int(self.curcanvlengthpos)): self.isdrawing = True coni = i / 100 / self.xzoom conj = j / 100 / self.yzoom complexnum = Complex(coni, conj) mandelseq = Mandelbrot(complexnum, 50) ColorPoint = str(mandelseq.__get_color__()) self.t.goto(i, j) self.t.pendown() self.t.color(ColorPoint) self.t.forward(1) self.t.penup() self.isdrawing = False
def check_events(): for event in pg.event.get(): if event.type == pg.QUIT: sys.exit() elif event.type == pg.KEYDOWN: if event.key == pg.K_RIGHT: cn.center[0] += 1 / cn.zoom print('Center moved to the right. Current center: ' + str(cn.center)) elif event.key == pg.K_LEFT: cn.center[0] -= 1 / cn.zoom print('Center moved to the left. Current center: ' + str(cn.center)) elif event.key == pg.K_UP: cn.center[1] -= 1 / cn.zoom print('Center moved up. Current center: ' + str(cn.center)) elif event.key == pg.K_DOWN: cn.center[1] += 1 / cn.zoom print('Center moved down. Current center: ' + str(cn.center)) elif event.key == pg.K_SPACE: start_time = time.time() print('Preparing Mandelbrot array...') Mandelbrot(cn.dim, cn.iterations, cn.center, cn.extent, cn.zoom).draw(cn.screen) cn.changed = False end_time = time.time() - start_time print('Array ready. Time: ' + str(end_time)) elif event.key == pg.K_KP_PLUS: cn.iterations *= 2 print('Current iterations increased to: ' + str(cn.iterations)) elif event.key == pg.K_KP_MINUS: cn.iterations /= 2 print('Current iterations decreased to: ' + str(cn.iterations)) elif event.key == pg.K_q: cn.zoom *= 2 print('Zoom increased. Current zoom: ' + str(cn.zoom)) elif event.key == pg.K_e: cn.zoom /= 2 print('Zoom decreased. Current zoom: ' + str(cn.zoom)) elif event.type == pg.MOUSEBUTTONDOWN: if event.button == 1: print('Aligning to new center...') move_vector = np.divide( cn.mandelbrot.get_vector(np.array(pg.mouse.get_pos())), cn.zoom) print(pg.mouse.get_pos()) if not cn.changed: cn.bp_center = cn.center cn.center = np.add(move_vector, cn.center) cn.changed = True else: cn.center = cn.bp_center cn.center = np.add(move_vector, cn.center) cn.changed = True print("New center is: " + str(cn.center) + '. Moved by vector of: ' + str(move_vector))
def api(): # gets json from the post request content = request.get_json() mandel = Mandelbrot( content['RealFrom'], content['RealTo'], content['ImaginaryFrom'], content['ImaginaryTo'], content['Intervall'], content['MaxIteration'], ) # safes the array mandel2Darray = mandel.do_the_loop() # turn 2D array into 1D array mandel1Darray = mandel2Darray.ravel().tolist() return jsonify(mandel1Darray)
def makeFractal(self, gradients, file='spiral0.frac'): frac_data = FractalData().get_one_frac(file) # self.verify_data(frac_data) if frac_data['type'] == 'mandelbrot': return Mandelbrot(frac_data, gradients) elif frac_data['type'] == 'julia': return Julia(frac_data, gradients) elif frac_data['type'] == 'burningship': return Burningship(frac_data, gradients) elif frac_data['type'] == 'phoenix': return Phoenix(frac_data, gradients)
def __init__(self, parent, h, x=-0.75, y=0, m=1, iterations=None, img_width=6000, img_height=4000, save=True, color_palette=False, spec_set='M'): Frame.__init__(self, parent) self.zoom_num = 0 self.parent = parent self.parent.title("Mandelbrot && Julia") self.pack(fill=BOTH, expand=1) self.canvas = Canvas(self) self.palette = None self.color_palette = color_palette self.background = None if None in {img_width, img_height}: img_width, img_height = int(h*1.6), h if img_width > img_height: ratio = img_height/img_width self.canvasW, self.canvasH = h, round(h*ratio) else: ratio = img_width/img_height self.canvasW, self.canvasH = round(h*ratio), h print(img_width, img_height) self.fractal = Mandelbrot(self.canvasW, self.canvasH, x=x, y=y, m=m, iterations=iterations, w=img_width, h=img_height, color_palette=color_palette, spec_set=spec_set) self.set_palette() self.img = None self.save = save self.draw(color_palette) # fix the issue: clicking on window's title bar will generate event self.canvas.bind("<Control-1>", self.zoom_in) self.canvas.bind("<Control-2>", self.zoom_out) self.canvas.bind("<B1-Motion>", self.shift_view) self.canvas.bind("<Button-1>", self.change_palette) self.canvas.bind("<Button-2>", self.save_image) self.canvas.bind("<Motion>", self.mouse_pos)
def makenew(x1, y1, x2, y2): global ttx, tty, m, image if x1 != x2 and y1 != y2: # ttx/tty == abs(x1-x2)/abs(y1-y2) # or tty/ttx == abs(y1-y2)/abs(x1-x2) if abs(x1 - x2) > abs(y1 - y2): ttx = gmx tty = int(gmx * abs(y1 - y2) / abs(x1 - x2)) else: tty = gmx ttx = int(gmx * abs(x1 - x2) / abs(y1 - y2)) z1 = m.values[x1][y1] z2 = m.values[x2][y2] pviter = m.itercount m = Mandelbrot(z1.real, z1.imag, z2.real, z2.imag, ttx, tty) for i in range(pviter): m.iter() image = np.zeros((tty, ttx, 3), np.uint8) cv.imshow("Mandelbrot", image) update() else: s = cv.waitKey(0) if s == 115: save() update()
def draw(self): self.myt.clear() halfwidth = 0.5 * (self.bounds[2] - self.bounds[0]) halfheight = 0.5 * (self.bounds[3] - self.bounds[1]) self.myt.goto(-300, -300) for x in range(-300, 301): realpoint = (x * halfwidth / 300) + (self.bounds[0] + halfwidth) self.myt.goto(x, -300) self.myt.pendown() for y in range(-300, 301): self.myt.goto(x, y) imagpoint = (y * halfheight / 300) + (self.bounds[1] + halfheight) color = Mandelbrot(Complex(realpoint, imagpoint)).get_color() self.myt.color(color) self.myt.penup()
def redraw(): # initializing a new mandelbrot object mandelbrot = Mandelbrot(WIDTH, HEIGHT, iterations_slider.get(), option.get(), x_start, y_start, x_width, y_height, color) # remove all the objects except the select area rectangle and reset the rectangle's points canvas.delete("!select_area") canvas.coords("select_area", 0, 0, 0, 0) # checks if the faster mode is selected (only if pillow is installed) if settings["pil_installed"] and fast_mode: pixel_array = process_iterations_array(mandelbrot, True, canvas) photo_image = get_mandelbrot_image(pixel_array, WIDTH, HEIGHT) canvas.img = photo_image canvas.create_image(WIDTH / 2, HEIGHT / 2, image=photo_image) else: process_iterations_array(mandelbrot, False, canvas)
def show_graphical(self): xmin, xmax, xn = -2.25, +0.75, 3000 / 2 ymin, ymax, yn = -1.25, +1.25, 2500 / 2 maxiter = 200 horizon = 2.0**40 log_horizon = np.log(np.log(horizon)) / np.log(2) Z, N = Mandelbrot.mandelbrot_set(self, xmin, xmax, ymin, ymax, xn, yn, maxiter, horizon) with np.errstate(invalid='ignore'): M = np.nan_to_num(N + 1 - np.log(np.log(abs(Z))) / np.log(2) + log_horizon) dpi = 72 width = 10 height = 10 * yn / xn fig = plt.figure(figsize=(width, height), dpi=dpi) ax = fig.add_axes([0.0, 0.0, 1.0, 1.0], frameon=False, aspect=1) light = colors.LightSource(azdeg=315, altdeg=10) M = light.shade(M, cmap=plt.cm.hot, vert_exag=1.5, norm=colors.PowerNorm(0.3), blend_mode='hsv') plt.imshow(M, extent=[xmin, xmax, ymin, ymax], interpolation="bicubic") ax.set_xticks([]) ax.set_yticks([]) text = "The Mandelbrot fractal" ax.text(xmin + .025, ymin + .025, text, color="white", fontsize=12, alpha=0.5) plt.show()
def test_init(self): cur_obj = Mandelbrot(100, 100, -1, 1, -1, 1) assert (cur_obj.max_iter == 50) assert (cur_obj.x_min == -1)
class Framework(Frame): def __init__(self, parent, h, x=-0.75, y=0, m=1, iterations=None, img_width=6000, img_height=4000, save=True, color_palette=False, spec_set='M'): Frame.__init__(self, parent) self.zoom_num = 0 self.parent = parent self.parent.title("Mandelbrot && Julia") self.pack(fill=BOTH, expand=1) self.canvas = Canvas(self) self.palette = None self.color_palette = color_palette self.background = None if None in {img_width, img_height}: img_width, img_height = int(h*1.6), h if img_width > img_height: ratio = img_height/img_width self.canvasW, self.canvasH = h, round(h*ratio) else: ratio = img_width/img_height self.canvasW, self.canvasH = round(h*ratio), h print(img_width, img_height) self.fractal = Mandelbrot(self.canvasW, self.canvasH, x=x, y=y, m=m, iterations=iterations, w=img_width, h=img_height, color_palette=color_palette, spec_set=spec_set) self.set_palette() self.img = None self.save = save self.draw(color_palette) # fix the issue: clicking on window's title bar will generate event self.canvas.bind("<Control-1>", self.zoom_in) self.canvas.bind("<Control-2>", self.zoom_out) self.canvas.bind("<B1-Motion>", self.shift_view) self.canvas.bind("<Button-1>", self.change_palette) self.canvas.bind("<Button-2>", self.save_image) self.canvas.bind("<Motion>", self.mouse_pos) def mouse_pos(self, event): # print("鼠标状态:", event.type) # print("屏幕坐标:({},{}), 复平面坐标:({})".format(event.x, event.y, self.fractal.center(event))) pass def zoom_in(self, event): self.zoom_num += 1 print('放大次数:', self.zoom_num) self.fractal.zoom_in(event) self.draw(self.color_palette) def zoom_out(self, event): print('Tip: zoom_out') self.fractal.zoom_out(event) self.draw(self.color_palette) def shift_view(self, event): print('Tip: shift_view') self.fractal.shift_view(event) self.draw() def change_palette(self, event): if self.color_palette: print('change_palette') self.set_palette() self.draw_pixels() self.canvas.create_image(0, 0, image=self.background, anchor=NW) self.canvas.pack(fill=BOTH, expand=1) def save_image(self, event): print('Tip: save_image') self.img.save("pictures/{}.png".format(time.strftime("%Y-%m-%d-%H:%M:%S")), "PNG", optimize=True) def draw(self, color_flag=False): """ 绘制图片主功能 :return: """ print('-' * 60) start = time.time() if color_flag is True: self.fractal.get_fractal(color_flag) print("get_fractal {} 秒".format(round(time.time() - start, 2))) start = time.time() self.draw_pixels() print("draw_pixels执行时间 {} 秒".format(round(time.time() - start, 2))) start = time.time() self.canvas.create_image(0, 0, image=self.background, anchor=NW) self.canvas.pack(fill=BOTH, expand=1) else: self.img = self.fractal.get_fractal(color_flag) self.background = ImageTk.PhotoImage(self.img.resize((self.canvasW, self.canvasH))) self.canvas.create_image(0, 0, image=self.background, anchor=NW) self.canvas.pack(fill=BOTH, expand=1) print("create_image执行时间 {} 秒".format(round(time.time()-start, 2))) def set_palette(self): """ 返回256个颜色值的数组列表 :return: """ if self.color_palette: print('Color palette used!') self.palette = [(0, 0, 0)] red_b = 2 * math.pi / (random.randint(0, 128) + 128) red_c = 256 * random.random() green_b = 2 * math.pi / (random.randint(0, 128) + 128) green_c = 256 * random.random() blue_b = 2 * math.pi / (random.randint(0, 128) + 128) blue_c = 256 * random.random() for i in range(256): r = clamp(int(256 * (0.5 * math.sin(red_b * i + red_c) + 0.5))) g = clamp(int(256 * (0.5 * math.sin(green_b * i + green_c) + 0.5))) b = clamp(int(256 * (0.5 * math.sin(blue_b * i + blue_c) + 0.5))) self.palette.append((r, g, b)) else: print('Color palette not used!') def draw_pixels(self): """ 生成图片 :return: """ self.img = Image.new('RGB', (self.fractal.w, self.fractal.h), "black") pixels = self.img.load() # create the pixel map opt.get_colors(pixels, self.fractal.pixels, self.palette) if self.save: self.save_image(None) photo_img = ImageTk.PhotoImage(self.img.resize((self.canvasW, self.canvasH))) self.background = photo_img
def set_point(self, x, y, value): Mandelbrot.set_point(self, x, y, value) if value > self.max: self.max = value
def print_parameters(self): Mandelbrot.print_parameters(self) print "\tsamples:\t", self.samples print "\tmin path:\t", self.min_path
from mandelbrot import Mandelbrot # Set the default values max_iter = 250 height = 1920 width = 1080 # Create a new Mandelbrot object mandelbrot = Mandelbrot(max_iter, height, width) # Generate the image mandelbrot.generateImage()
from PIL import Image from mandelbrot import Mandelbrot resolution = 512 gif = [] for i in range(120): print('Rendering frame ', i) p = 1 + 0.05 * i m = Mandelbrot(resolution, quality=20, x=0, y=0, radius=2, power=p) m.set_palette(1 + 0.02 * i, 1.5, 2 - 0.01 * i) gif.append(m.render(None, False)) # Save the gif gif[0].save('powers.gif', format='GIF', append_images=gif[1:], save_all=True, duration=20, loop=0)
import cv2 as cv import math import os from mandelbrot import Mandelbrot gmx = 700 ttx = gmx tty = int(gmx * 2 / 3) image = np.zeros((tty, ttx, 3), np.uint8) cv.namedWindow("Mandelbrot") ccolour = 255 x1, y1 = 0, 0 cnumber = 1 started = False os.makedirs("captures", exist_ok=True) m = Mandelbrot(-2, 1, 1, -1, ttx, tty) def save(): global cnumber while "img" + str(cnumber) + ".png" in os.listdir("captures"): cnumber = cnumber + 1 cv.imwrite("captures\\img" + str(cnumber) + ".png", image) def makenew(x1, y1, x2, y2): global ttx, tty, m, image if x1 != x2 and y1 != y2: # ttx/tty == abs(x1-x2)/abs(y1-y2) # or tty/ttx == abs(y1-y2)/abs(x1-x2) if abs(x1 - x2) > abs(y1 - y2):
offset = (event.x - self.draw_shape[0] / 2, event.y - self.draw_shape[1] / 2) self.mandelbrot.move(offset) self.redraw_image() self.update_position_label() def on_button_snapshot_clicked(self, *args): SHAPE = (1920, 1080) filename = self.mandelbrot.snapshot(SHAPE) self.add_log_entry( f"Created snapshot: {filename}, size = {SHAPE[0]} x {SHAPE[1]}, time = {self.mandelbrot.get_last_computation_time():.2f}s" ) def on_button_recolor_clicked(self, *args): self.mandelbrot.randomize_buckets() self.redraw_image() def on_button_zoomed_sequence_clicked(self, *args): self.start_zoomed_sequence() if __name__ == "__main__": INITIAL_DEPTH = 10000 setup_logger() log = logging.getLogger(__name__) mb = Mandelbrot(INITIAL_DEPTH) window = Window(mb) window.run()
from fractal import Fractal from julia import Julia from mandelbrot import Mandelbrot from newton import Newton from pheonix import Pheonix # Static constant fractal instances. MANDELBROT = Mandelbrot("Mandelbrot Set") NEWTON = Newton("Newton Fractal") JULIA = Julia("Julia Set") PHEONIX = Pheonix("Pheonix Fractal") def getFractal(fractal_id): return Fractal.FRACTALS[fractal_id] def getFractals(): return Fractal.FRACTALS
from mandelbrot import Mandelbrot import pyglet # %% scale = 1 window = pyglet.window.Window(200, 200) mandelbrot = Mandelbrot(width=200, height=200) @window.event def on_mouse_press(x, y, button, modifiers): window.clear() print(f"Click at {x}, {y}") x_center = mandelbrot.x_center+mandelbrot.scale * \ 4*(x-window.width/2)/window.width y_center = mandelbrot.y_center+mandelbrot.scale * \ 4*(y-window.width/2)/window.width mandelbrot.scale = mandelbrot.scale * 0.5 print(x_center, y_center) mandelbrot.x_center = x_center mandelbrot.y_center = y_center mandelbrot.calc_pixel_array() mandelbrot.save_mandelbrot() mandelbrot.draw_pixel_array(window) mandelbrot.draw_pixel_array(window) pyglet.app.run()
def plot_mandelbrot() -> None: """Plot the Mandelbrot set.""" print('Please wait, the Mandelbrot set is being loaded.') mandelbrot = Mandelbrot(iteration_limit=255, accuracy=300, real_domain=(-2.025, 0.6), imaginary_domain=(-1.125, 1.125)) mandelbrot.plot()
from mandelbrot import Mandelbrot, Scalar, Complex px = 10 py = 10 dp = 32 cx = Scalar(10,0) # -1.0 cy = Scalar(10,0) # 0.3 w = Scalar(4,0) # 0.1 h = w.clone() fn = "mandelbrot-{0}x{1}x{2}.png".format(px,py,dp) pos = Complex(cx,cy) man = Mandelbrot() man.setPosition(pos) man.setWindowSize(w,h) man.setPixels(px,py) man.render(dp) man.write(fn)
def test_get_file_name(self): cur_obj = Mandelbrot(100, 100, -1, 1, -1, 1) fn = cur_obj.get_file_name() fn2 = cur_obj.get_file_name() assert (fn != fn2)
from mandelbrot import Coordinates, Mandelbrot from guiconfig import AppConfig import time, subprocess, os, platform import numpy as np fields = ('X offset', 'Y offset', 'Zoom level', 'Image Height', 'Image Width') x_s = 'X offset' y_s = 'Y offset' z_s = 'Zoom level' h_s = 'Image Height' w_s = 'Image Width' it_s = 'Iterations' gmm_s = 'Gamma' col_s = 'Color map' program = Mandelbrot() config = AppConfig() scale = None gamma_scale = None color_option = None currentcolor_var = None postrenderselect_var = None def makeform(root, f): entries = {} for field in f: row = Frame(root) lbl = Label(row, width=20, text=field + ': ', anchor='w')
from mandelbrot import Mandelbrot, Scalar, Complex px = 100 py = 100 dp = 32 cx = Scalar(-1,0) # -1.0 cy = Scalar(3,-1) # 0.3 w = Scalar(1,-1) # 0.1 h = w.clone() fn = "spiralarm-{0}x{1}x{2}.png".format(px,py,dp) pos = Complex(cx,cy) man = Mandelbrot() man.setPosition(pos) man.setWindowSize(w,h) man.setPixels(px,py) man.render(dp) man.write(fn)