예제 #1
0
def bytie_handle_mandelbrot(command: str) -> str:
    """
    mandelbrot <x> <y> <zoom> <max_iter> <divergance_radius>

    """
    args = command.split()
    try:
        x = float(args[1])
        y = float(args[2])
        zoom = float(args[3])
        max_iter = int(args[4])
        divergance_radius = float(args[5])
    except:
        return "Please feed a zoom and a center paramter! Also maximum number of iterations and divergance radius!"

    HOST = os.getenv("BYTIE_HOST")
    PATH = os.getenv("BYTIE_PATH")

    filename = f"image_{x}_{y}_{zoom}_{max_iter}_{divergance_radius}.png"
    filepath = f"{PATH}/{filename}"
    url = f"{HOST}/{filename}"

    mandelbrot.mandelbrot(zoom=zoom,
                          center=(x, y),
                          filename=filepath,
                          max_iter=max_iter,
                          div_radius=divergance_radius)

    return url
예제 #2
0
def main():
    try:
        scale = int(argv[1])
    except:
        scale = 3
    filename = "{}/out/mandelbrot.png".format(environ["WD"])
    xs = {
        "width": int(150 * scale),
        "height": int(300 * scale),
        "limit": 255,
        "minX": -2.23,
        "minY": -1.15,
        "maxX": 0.83,
        "maxY": 1.15,
    }
    f = timer(lambda: mandelbrot(), "mandelbrot()")
    y = timer(lambda: f.main(*xs.values()).get(), "f.main(...).get()")
    image = empty((xs["height"], xs["width"], 3), dtype=uint8)
    image[:, :, 0] = (y & 0xFF0000) >> 16
    image[:, :, 1] = (y & 0xFF00) >> 8
    image[:, :, 2] = (y & 0xFF)
    image = timer(
        lambda: reshape(image, (xs["height"], xs["width"] * 3)),
        "reshape(...)",
    )
    timer(lambda: imwrite(filename, image), "imwrite(...)")
예제 #3
0
def showSet(left: float, top: float, step: float, scr: "curses._CursesWindow"):
    """
        Shows set with given left/top bound and "pixel" step
        on screen space
    """
    # Cleans screen
    scr.erase()
    # Get screen size
    height, width = scr.getmaxyx()
    # "Pixel" loop
    for h in range(0, height):
        for w in range(0, width):
            # Ignores last char (not supported by curses)
            if w == width - 1 and h == height - 1:
                break
            # Transforms "pixel" coordenates into complex number
            c = complex(left + w * step,
                        top - h * step)
            # Get max iteration on given "pixel"
            i = mandelbrot(c)
            # Shows correct char in gradient
            s = SYMBS[int(i/MAX_ITER * (len(SYMBS) - 1))]
            scr.addch(s)
    # Refresh screen
    scr.refresh()
def DrawMandelbrot():
    global oled, brotFB, cursorFB, isHiRez
    print("DRAWING:", realStart, realEnd, imStart, imEnd)
    RE_START = realStart
    RE_END = realEnd
    IM_START = imStart
    IM_END = imEnd

    MAX_ITER = 80
    brotFB.fill(0)
    step = 1 if isHiRez else 2
    for x in range(0, WIDTH, step):
        xx = RE_START + (x / WIDTH) * (RE_END - RE_START)
        for y in range(0, HEIGHT, step):
            yy = IM_START + (y / HEIGHT) * (IM_END - IM_START)
            c = complex(xx, yy)  # Convert pixel coordinate to complex number
            m = mandelbrot.mandelbrot(c)  # Compute the number of iterations
            color = 1 - int(m / MAX_ITER)
            if isHiRez:
                brotFB.pixel(x, y, 1 if color > 0 else 0)  # Plot the point
            else:
                brotFB.fill_rect(x, y, 2, 2, 1 if color > 0 else 0)
        if x % 4 == 0:
            oled.blit(brotFB, 0, 0)
            oled.show()
    oled.show()
예제 #5
0
def mandelbrot_plot():
    # input values
    xOff = -2.0
    yOff = -1.0
    xRange = 3.0
    yRange = 2.0
    Res = 1000
    mxStep = 100
    # create matrix
    iMax = int(Res * xRange)
    jMax = int(Res * yRange)
    fMatrix = numpy.empty((jMax, iMax), order='F', dtype=numpy.int32)
    mandelbrot.mandelbrot(xOff, yOff, xRange, yRange, Res, mxStep, fMatrix)
    # plot the image matrix
    plt.imshow(fMatrix.transpose())
    plt.savefig("mandelbrot_fortran.png", dpi=300)
    return
예제 #6
0
 def render_mandelbrot(self, complex_coords=None):
     complex_coords = self.before_render(complex_coords,
                                         MANDELBROT_DEFAULT_COORDS)
     max_iter = settings.mandelbrot.max_iter
     self.complex_plane = mandelbrot.mandelbrot(
         settings.canvas.size_x, settings.canvas.size_y, *complex_coords,
         coloring.colorings[settings.mandelbrot.coloring](max_iter),
         settings.mandelbrot.bailout, max_iter)
     self.after_render(self.render_mandelbrot)
예제 #7
0
def bytie_handle_mandelbrot(command: str) -> str:
    "mandelbrot ${x} ${y} ${zoom} ${iterations} ${divergence_radius} : I generate a mandelbrot image for you."
    args = command.split()
    try:
        x = float(args[0])
        y = float(args[1])
        zoom = float(args[2])
        max_iter = int(args[3])
        divergance_radius = float(args[4])
    except:
        return "Please feed a zoom and a center paramter! Also maximum number of iterations and divergence radius!"

    filename = f"image_{x}_{y}_{zoom}_{max_iter}_{divergance_radius}.png"
    filepath = f"{PATH}/{filename}"
    url = f"{HOST}/{filename}"
    if not(path.exists(filepath)):
        mandelbrot.mandelbrot(zoom=zoom, center=(
            x, y), filename=filepath, max_iter=max_iter, div_radius=divergance_radius)
    return url
예제 #8
0
def create_mandelbrot(screen, screen_width, screen_height, w_values, h_values,
                      resolution):
    next_pixelarray = mandelbrot(screen_width, screen_height, w_values,
                                 h_values, resolution)
    surf = next_pixelarray.surface
    del next_pixelarray
    surf_center = ((screen_width - surf.get_width()) / 2,
                   (screen_height - surf.get_height()) / 2)
    screen.blit(surf, surf_center)
    pygame.display.flip()
    return surf
예제 #9
0
파일: main.py 프로젝트: mrn4344/Mandelbrot
def main():
    me = mand.mandelbrot(2)
    img = Image.new('RGB', (width, height), color='white')
    for y in range(0, height):
        for x in range(0, width):
            c = pixelToCoord((x, y))
            if (me.isInSet(complex(c[0], c[1]), 1024)):
                img.putpixel((x, y), (0, 0, 0))
        if y % 25 == 0:
            print("Row " + str(y))
    img.save("output2.png")
예제 #10
0
파일: mandelbrot.py 프로젝트: gmrigna/abipy
    def __init__(self, parent, **kwargs):
        super(FractalsFrame, self).__init__(parent, **kwargs)

        ndivs = (1000, 1000)
        x, y, m = mandelbrot(ndivs=ndvis)
        #print("x",x[0])
        #print("y",x[0])

        self.display(m)  # x=x[0], y=x[0])

        self.panel.__class__ = MyPanel
예제 #11
0
def do_render(args, writer):
    inside_cutoff = 2**9
    color_map = subharmonics
    for n in progressbar.progressbar(range(args.num_frames)):
        t = n / (args.num_frames - 1)
        x, y = -0.11042608495193805, -1.2321253969758166
        zoom = t * 44 - 2

        image = mandelbrot(args.width, args.height, x, y, zoom, 2.5, 66, color_map=color_map, anti_aliasing=args.anti_aliasing, inside_cutoff=inside_cutoff, clip_outside=True)

        frame = make_video_frame(image, indexing=None)
        writer.append_data(frame)
예제 #12
0
파일: mandelbrot.py 프로젝트: gmrigna/abipy
    def imshow_fractal(self, extent=None):
        xvals, yvals, data = mandelbrot(extent=extent, ndivs=self.ndivs)

        if extent is None:
            extent = (xvals[0], xvals[-1], yvals[0], yvals[-1])

        self.axes.imshow(np.log(data),
                         cmap=plt.cm.hot,
                         origin="lower",
                         extent=extent)

        # Save values
        self.xvals, self.yvals, self.data = xvals, yvals, data
예제 #13
0
def bytie_handle_mandelbrot(command: str) -> str:
    """
    mandelbrot <x> <y> <zoom>

    """
    args = command.split()
    try:
        x = float(args[1])
        y = float(args[2])
        zoom = float(args[3])
    except:
        return "Please feed a zoom and a center paramter!"

    HOST = os.getenv("HOST")
    PATH = os.getenv("PATH")

    filename = f"image_{x}_{y}_{zoom}.png"
    filepath = f"{PATH}/{filename}"
    url = f"{HOST}/{filename}"

    mandelbrot.mandelbrot(zoom=zoom, center=(x, y), filename=filepath)

    return url
예제 #14
0
def DrawMandelbrot():
    global oled, brotFB, cursorFB, isHiRez, nextRefresh
    global tReal, tImaginary, m2, threadState
    print("DRAWING:", realStart, realEnd, imStart, imEnd)
    stopWatch = time.ticks_ms()
    RE_START = realStart
    RE_END = realEnd
    IM_START = imStart
    IM_END = imEnd

    brotFB.fill(0)
    for x in range(0, WIDTH,1):
        xx = RE_START + (x / WIDTH) * (RE_END - RE_START)
        for y in range(0, HEIGHT, 2):
            #-- Second core --
            y2 = y+1
            yy2 = IM_START + (y2 / HEIGHT) * (IM_END - IM_START)
            tReal, tImaginary = xx, yy2 # Convert pixel coordinate to complex number
            print("waiting thread to become idle", threadState)
            while threadState!=0: # Wait until done computing previous input
                pass
            print("Thread was idle!", threadState)
            threadState=1 # Tell thread to start computing
            print("Tell thread to start processing!", threadState)
            
            yy = IM_START + (y / HEIGHT) * (IM_END - IM_START)
            c = complex(xx, yy) # Convert pixel coordinate to complex number
            m = mandelbrot.mandelbrot(c)   # Compute the number of iterations
            color = 1 - int(m/MAX_ITER)
            
            #threadState will be 1 or 2 at this point.
            print("wait for calculation to be completed.", threadState)
            while threadState!=3: # wait for calculation to be completed.
                pass
            print("Thread result ready!", threadState)
            color2 = 1 - int(m2/MAX_ITER) # use calculation result.
            print("Done using thread result, let it compute next one", threadState)
            #brotFB.pixel(x,y+1, 1 if color2>0 else 0) # Plot the point
            #brotFB.pixel(x,y, 1 if color>0 else 0) # Plot the point
            threadState=0 # Done using thread result, let it compute next one
            
        if time.ticks_ms() >= nextRefresh:
#             if ButtonPressed():
#                 return
            oled.blit(brotFB,0,0)
            oled.show()
            nextRefresh = time.ticks_ms() + 500
    oled.show()
    print(time.ticks_diff(time.ticks_ms(), stopWatch))
예제 #15
0
def printChart(x, y, zoom, counter=1):
    points = getPoints(x, y, zoom)
    start = (points[0], points[1])
    end = (points[2], points[3])
    RE_START = start[0]
    IM_START = start[1]
    RE_END = end[0]
    IM_END = end[1]

    histogram = defaultdict(lambda: 0)
    values = {}
    for x in range(0, WIDTH):
        for y in range(0, HEIGHT):
            # Convert pixel coordinate to complex number
            c = complex(RE_START + (x / WIDTH) * (RE_END - RE_START),
                        IM_START + (y / HEIGHT) * (IM_END - IM_START))
            # Compute the number of iterations
            m = mandelbrot(c)

            values[(x, y)] = m
            if m < MAX_ITER:  # Test
                #if m < MAX_ITER - (MAX_ITER * .1): # Test
                histogram[floor(m)] += 1

    total = sum(histogram.values())
    hues = []
    h = 0
    for i in range(MAX_ITER):
        h += histogram[i] / total
        hues.append(h)
    hues.append(h)

    im = Image.new('HSV', (WIDTH, HEIGHT), (0, 0, 0))
    draw = ImageDraw.Draw(im)

    for x in range(0, WIDTH):
        for y in range(0, HEIGHT):
            m = values[(x, y)]
            # The color depends on the number of iterations
            hue = 255 - int(255 * linear_interpolation(hues[floor(m)],
                                                       hues[ceil(m)], m % 1))
            saturation = 255
            value = 255 if m < MAX_ITER else 0
            # Plot the point
            draw.point([x, y], (hue, saturation, value))

    name = 'output-' + str(counter) + '-' + str(zoom) + 'x.png'
    im.convert('RGB').save(name, 'PNG')
    print("\nsaved file: " + name)
예제 #16
0
def mandelbrotArray(plotCenter, numberOfCalculationPoints, maxIterationsCount):
    xValues = np.linspace(plotCenter[0] - plotCenter[2] / 2,
                          plotCenter[0] + plotCenter[2] / 2,
                          numberOfCalculationPoints)
    yValues = np.linspace(plotCenter[1] - plotCenter[2] / 2,
                          plotCenter[1] + plotCenter[2] / 2,
                          numberOfCalculationPoints)
    xLength = len(xValues)
    yLength = len(yValues)
    viewWindow = np.empty((len(xValues), len(yValues)))
    for x in range(xLength):
        for y in range(yLength):
            b = complex(xValues[x], yValues[y])
            viewWindow[x, y] = mandelbrot(b, maxIterationsCount)

    return viewWindow
예제 #17
0
def colorPixel(pixel: [int, int]):
    """
    Color each pixel acording to its max element within bounds on the set
    """

    # Generates according complex number
    c = complex(REAL_START + (pixel[0] / IMG_WIDTH) * (REAL_END - REAL_START),
                IM_START + (pixel[1] / IMG_HEIGHT) * (IM_END - IM_START))
    # Checks max bounded iteration
    i = mandelbrot(c)
    # Apply color
    if BW:
        tone = int(i / MAX_ITER * 255)
        color = (tone, tone, tone)
    else:
        color = palette[int(i / MAX_ITER * (len(palette) - 1))]
    return color
예제 #18
0
def plotMandelbrot(RE_START, RE_END, IM_START, IM_END, WINDOW_WIDTH,
                   WINDOW_HEIGHT, MAX_ITER, RENDER_SCALE):
    WIDTH = int(WINDOW_WIDTH * RENDER_SCALE)
    HEIGHT = int(WINDOW_HEIGHT * RENDER_SCALE)
    im = Image.new("HSV", (WIDTH, HEIGHT), (0, 0, 0))
    draw = ImageDraw.Draw(im)

    for x in range(0, WIDTH):
        for y in range(0, HEIGHT):
            c = complex(RE_START + (x / WIDTH) * (RE_END - RE_START),
                        IM_START + (y / HEIGHT) * (IM_END - IM_START))
            m = mandelbrot(c, MAX_ITER)
            hue = int(255 * m / MAX_ITER)
            saturation = 255
            value = 255 if m < MAX_ITER else 0
            draw.point([x, HEIGHT - y], (hue, saturation, value))

    im = im.resize((WINDOW_WIDTH, WINDOW_HEIGHT), Image.BICUBIC)
    im.convert('RGB').save('output.png', 'PNG')
예제 #19
0
def make_sample_image():
    center = complex(-0.7, 0.0)
    length = 4.0
    resolution = (960, 1280)
    max_itr = 255

    z = mandelbrot.mandelbrot(center, length, resolution, max_itr)

    colormap_table = [['COLORMAP_AUTUMN', cv2.COLORMAP_AUTUMN],
                      ['COLORMAP_BONE', cv2.COLORMAP_BONE],
                      ['COLORMAP_JET', cv2.COLORMAP_JET],
                      ['COLORMAP_WINTER', cv2.COLORMAP_WINTER],
                      ['COLORMAP_RAINBOW', cv2.COLORMAP_RAINBOW],
                      ['COLORMAP_OCEAN', cv2.COLORMAP_OCEAN],
                      ['COLORMAP_SUMMER', cv2.COLORMAP_SUMMER],
                      ['COLORMAP_SPRING', cv2.COLORMAP_SPRING],
                      ['COLORMAP_COOL', cv2.COLORMAP_COOL],
                      ['COLORMAP_HSV', cv2.COLORMAP_HSV],
                      ['COLORMAP_PINK', cv2.COLORMAP_PINK],
                      ['COLORMAP_HOT', cv2.COLORMAP_HOT],
                      ['COLORMAP_PARULA', cv2.COLORMAP_PARULA],
                      ['COLORMAP_MAGMA', cv2.COLORMAP_MAGMA],
                      ['COLORMAP_INFERNO', cv2.COLORMAP_INFERNO],
                      ['COLORMAP_PLASMA', cv2.COLORMAP_PLASMA],
                      ['COLORMAP_VIRIDIS', cv2.COLORMAP_VIRIDIS],
                      ['COLORMAP_CIVIDIS', cv2.COLORMAP_CIVIDIS],
                      ['COLORMAP_TWILIGHT', cv2.COLORMAP_TWILIGHT],
                      [
                          'COLORMAP_TWILIGHT_SHIFTED',
                          cv2.COLORMAP_TWILIGHT_SHIFTED
                      ], ['COLORMAP_TURBO', cv2.COLORMAP_TURBO],
                      ['COLORMAP_DEEPGREEN', cv2.COLORMAP_DEEPGREEN]]

    if not os.path.isdir('colormap'):
        os.mkdir('colormap')

    for colormap in colormap_table:
        a = cv2.applyColorMap(z, colormap[1])
        cv2.imwrite('colormap/' + colormap[0] + '.png', a)
예제 #20
0
def main(filename, width, height, limit, minx, miny, maxx, maxy):
    m = mandelbrot.mandelbrot()

    start=time.time()
    fut_image=m.main(width, height, limit, minx, miny, maxx, maxy)
    end=time.time()
    print('Computed fractal in %.2fs' % (end-start,))

    # Futhark gives us an array of 32-bit integers encoding the color,
    # but the PNG writer expects each colour channel to be separate.
    start=time.time()
    image=numpy.empty((height,width,3))
    image[:,:,0] = (fut_image & 0xFF0000) >> 16
    image[:,:,1] = (fut_image & 0xFF00) >> 8
    image[:,:,2] = (fut_image & 0xFF)
    end=time.time()
    print('Prepared Numpy array in in %.2fs' % (end-start,))

    start=time.time()
    w = png.Writer(width, height, greyscale=False, alpha=False, bitdepth=8)
    with open(filename, 'wb') as f:
        w.write(f, numpy.reshape(image, (height, width*3)))
    end=time.time()
    print('Encoded %s in %.2fs' % (filename, end-start))
예제 #21
0
파일: mandelbrot.py 프로젝트: gmrigna/abipy
    #def onclick(self, event):
    #    print('button=%d, x=%d, y=%d, xdata=%f, ydata=%f'%(
    #          event.button, event.x, event.y, event.xdata, event.ydata))


def wxapp_fractals():
    app = wx.App()
    #frame = FractalsFrame(None)
    frame = CanvasFrame(None)
    app.SetTopWindow(frame)
    frame.Show()
    return app


if __name__ == "__main__":
    import sys
    wxapp_fractals().MainLoop()
    sys.exit(0)

    x, y, m = mandelbrot()

    # we plot log(m)
    import matplotlib.pyplot as plt
    fig = plt.imshow(np.log(m), cmap=plt.cm.hot, extent=extent)

    plt.title('Mandelbrot Set')
    plt.xlabel('Re(z)')
    plt.ylabel('Im(z)')

    plt.show()
예제 #22
0
aspect = dimensions[0] / dimensions[1]
# ylength = xlength / aspect

array = np.zeros(dimensions, int)

# xlength = 4

# p = (-.5, 0)

iterations = 300

# p = (.366363, -.59153375)
p = (-.5, 0)

start = time.time()
i = mandelbrot.mandelbrot(array, 4, p, iterations)
end = time.time()
# print("Elapsed = %s" % (end - start))

start = time.time()
i = mandelbrot.draw_mandelbrot(i, iterations)
end = time.time()
# print("Elapsed (color) = %s" % (end - start))
# print(i)

img = Image.fromarray(i).transpose(Image.ROTATE_90)
# pts = mandelbrot.mandelbrot_path(img.size, (-1.5, 0.1), 4, p, iterations)
# pts = mandelbrot.mandelbrot_path(img.size, (.365, .592), 4, p, iterations)
pts = mandelbrot.mandelbrot_path(img.size, (-1.15, .20), 4, p, iterations)
img = mandelbrot.draw_path(img, pts)
img.save('../output/mainmandelbrot.png')
예제 #23
0
default_local_height = height // size
local_height = default_local_height
if rank == size:
    local_height = height - default_local_height * (size - 1)
local_array_len = local_height * width
local_result = np.zeros(shape=[local_array_len],
                        dtype='i')

dx = a / height
dy = b / width
for row in range(local_height):
    shift = default_local_height * rank
    y = -b / 3 + (row + shift) * dy
    for col in range(width):
        x = -a + col * dx
        local_result[col + row * width] = mandelbrot(x, y, max_iter)
print('{0} process for {1} seconds'.format(rank, time.time() - t0))
local_result.shape = (local_height, width)
pyplot.imshow(local_result, aspect='equal')
pyplot.spectral()
pyplot.show()
result = None
if rank == 0:
    result = np.empty([height * width], dtype='i')
comm.Gather(sendbuf=local_result,
            recvbuf=result,
            root=0)
if rank == 0:
    result.shape = (height, width)
    print('all time for execution {}'.format(time.time() - t0))
    pyplot.imshow(result, aspect='equal')
예제 #24
0
import mandelbrot
import math

iterations = 50
test_set = mandelbrot.mandelbrot(iterations)

# just going to use console output, printing something like '#' for points in
# the set.  Assuming default console size of 80x25 (typical for Windows
# systems). 'Minor' corrections for correct aspect ratio

xmin, xmax = -2.0, 1.0
ymin, ymax = -1.0, 1.0

chars = ('#', ' ', '-', ';', '*')
upper_bound = len(chars) - 1
log_scale = math.log(iterations, upper_bound)

width = 36 * 2  #correction for font not being square, mine happens to be 2:1
height = 24 * 1

for y in range(height):
    row = ""
    for x in range(width):
        real_x, real_y = (xmin + x * (xmax - xmin) / width,
                          ymax - y * (ymax - ymin) / height)
        #print real_x, real_y
        in_set, iter = test_set.calc_point(complex(real_x, real_y))
        if in_set:
            row += chars[0]
        else:
            if iter == 0:
예제 #25
0
# Plot window
RE_START = -2
RE_END = 1
IM_START = -1
IM_END = 1

histogram = defaultdict(lambda: 0)
values = {}
for x in range(0, WIDTH):
    for y in range(0, HEIGHT):
        # Convert pixel coordinate to complex number
        c = complex(RE_START + (x / WIDTH) * (RE_END - RE_START),
                    IM_START + (y / HEIGHT) * (IM_END - IM_START))
        # Compute the number of iterations
        m = mandelbrot(c)

        values[(x, y)] = m
        if m < MAX_ITER:
            histogram[floor(m)] += 1

total = sum(histogram.values())
hues = []
h = 0
for i in range(MAX_ITER):
    h += histogram[i] / total
    hues.append(h)
hues.append(h)

im = Image.new('HSV', (WIDTH, HEIGHT), (0, 0, 0))
draw = ImageDraw.Draw(im)
예제 #26
0
                    help='Ask at startup for the OpenCL device to use')

args = parser.parse_args()

width = args.width
height = args.height
size=(width,height)
sizearr = numpy.array(size, dtype=numpy.int32)
minx=-2.0
miny=-0.75
maxx=0.75
maxy=0.75
limit=255
frame = numpy.zeros((width,height,3), dtype=numpy.byte)

l = mandelbrot.mandelbrot(interactive=args.pick_device)

pygame.init()
pygame.display.set_caption('Mandelbrot APL demo')
screen = pygame.display.set_mode(size)
surface = pygame.Surface(size)
font = pygame.font.Font(None, 36)
pygame.key.set_repeat(1, 1)

def showText(what, where):
    text = font.render(what, 1, (255, 255, 255))
    screen.blit(text, where)

def render():
    fieldarr = numpy.array([miny, maxy, minx, maxx], dtype=numpy.float32)
    limitarr = numpy.array([limit], dtype=numpy.int)
예제 #27
0
from timer import Timer

import matplotlib
matplotlib.use('TKagg')

import pylab as plt
import numpy as np


# create coordinates, along with output count array
def make_coords(center=(-0.575 - 0.575j), width=0.0025, count=4000):

    x = np.linspace(start=(-width / 2), stop=(width / 2), num=count)
    xx = center + (x + 1j * x[:, np.newaxis]).astype(np.complex64)
    return xx, np.zeros_like(xx, dtype=np.uint32)


if __name__ == '__main__':
    in_coords, out_counts = make_coords()

    with Timer() as t:
        mandelbrot.mandelbrot(in_coords, out_counts, 1024)
    seconds = t.interval

    print(
        "{} Million Complex FMAs in {} seconds, {} million Complex FMAs / second"
        .format(out_counts.sum() / 1e6, seconds,
                (out_counts.sum() / seconds) / 1e6))

    plt.imshow(np.log(out_counts))
    plt.show()
예제 #28
0
def wrapper_mandelbrot(args):
    return mandelbrot.mandelbrot(*args)
예제 #29
0
import mandelbrot
import mandelbrot_numpy
import numpy
import pygame
import time
import sys

width = 1200
height = 800
limit = 255
size = (width, height)
frame_every = 1.0 / 30.0
startpos = (-2.23, -1.15, 0.83, 1.15)

futm = mandelbrot.mandelbrot()


def make_mandelbrot_futhark(minx, miny, maxx, maxy):
    return futm.main(width, height, limit, minx, miny, maxx, maxy).get()


def make_mandelbrot_numpy(minx, miny, maxx, maxy):
    return mandelbrot_numpy.mandelbrot(width, height, limit, minx, miny, maxx,
                                       maxy)


backend = 'Futhark'
make_mandelbrot = make_mandelbrot_futhark

예제 #30
0
def mandelbrot_end(min_c_re, min_c_im, max_c_re, max_c_im, x, y, inf_n):

    # There's maybe a better way to do this than
    # type-casting everything manually but this
    # will work for now.

    # Image size (pixels)
    WIDTH = int(x)
    HEIGHT = int(y)

    # Max number of iterations
    max_iter = int(inf_n)

    # Plot window
    RE_START = int(min_c_re)
    RE_END = int(max_c_re)
    IM_START = int(min_c_im)
    IM_END = int(max_c_im)

    histogram = defaultdict(lambda: 0)
    values = {}
    for x in range(0, WIDTH):
        for y in range(0, HEIGHT):
            # Convert pixel coordinate to complex number
            c = complex(RE_START + (x / WIDTH) * (RE_END - RE_START),
                        IM_START + (y / HEIGHT) * (IM_END - IM_START))
            # Compute the number of iterations
            m = mandelbrot(c)

            values[(x, y)] = m
            if m < max_iter:
                histogram[floor(m)] += 1

    total = sum(histogram.values())
    hues = []
    h = 0
    for i in range(max_iter):
        h += histogram[i] / total
        hues.append(h)
    hues.append(h)

    im = Image.new('HSV', (WIDTH, HEIGHT), (0, 0, 0))
    draw = ImageDraw.Draw(im)

    for x in range(0, WIDTH):
        for y in range(0, HEIGHT):
            m = values[(x, y)]
            # The color depends on the number of iterations
            hue = 255 - \
                int(255 *
                    linear_interpolation(hues[floor(m)], hues[ceil(m)], m % 1))
            saturation = 255
            value = 255 if m < max_iter else 0
            # Plot the point
            draw.point([x, y], (hue, saturation, value))

    # Some voodoo that serves the picture as a response in Flask.
    im.convert('RGB').save('output.png', 'PNG')
    tempFileObj = NamedTemporaryFile(mode='w+b', suffix='png')
    pillImage = open('output.png', 'rb')
    copyfileobj(pillImage, tempFileObj)
    pillImage.close()
    remove('output.png')
    tempFileObj.seek(0, 0)

    response = flask.send_file(tempFileObj, attachment_filename='output.png')
    return response