|
| 1 | +from lpython import i32, f64, TypeVar, Const |
| 2 | +from numpy import empty, int32 |
| 3 | + |
| 4 | +h = TypeVar("h") |
| 5 | +w = TypeVar("w") |
| 6 | + |
| 7 | +def show_img(w: i32, h: i32, A: i32[h, w]): |
| 8 | + print(w, h) |
| 9 | + print(A[0, 0]) |
| 10 | + print(A[h - 1, w - 1]) |
| 11 | + |
| 12 | + assert w == 600 |
| 13 | + assert h == 450 |
| 14 | + assert A[0, 0] == 254 |
| 15 | + assert A[h - 1, w - 1] == 254 |
| 16 | + |
| 17 | +def show_img_color(w: i32, h: i32, A: i32[h, w, 4]): |
| 18 | + print(w, h) |
| 19 | + print(A[0, 0, 0]) |
| 20 | + print(A[h - 1, w - 1, 3]) |
| 21 | + |
| 22 | + assert w == 600 |
| 23 | + assert h == 450 |
| 24 | + assert A[0, 0, 0] == 214 |
| 25 | + assert A[h - 1, w - 1, 3] == 255 |
| 26 | + |
| 27 | +def main0(): |
| 28 | + Nx: Const[i32] = 600; Ny: Const[i32] = 450; Nz: Const[i32] = 4; n_max: i32 = 255 |
| 29 | + |
| 30 | + xcenter: f64 = f64(-0.5); ycenter: f64 = f64(0.0) |
| 31 | + width: f64 = f64(4); height: f64 = f64(3) |
| 32 | + dx_di: f64 = width/f64(Nx); dy_dj: f64 = -height/f64(Ny) |
| 33 | + x_offset: f64 = xcenter - f64(Nx+1)*dx_di/f64(2.0) |
| 34 | + y_offset: f64 = ycenter - f64(Ny+1)*dy_dj/f64(2.0) |
| 35 | + |
| 36 | + i: i32; j: i32; n: i32; idx: i32 |
| 37 | + x: f64; y: f64; x_0: f64; y_0: f64; x_sqr: f64; y_sqr: f64 |
| 38 | + |
| 39 | + image: i32[450, 600] = empty([Ny, Nx], dtype=int32) |
| 40 | + image_color: i32[450, 600, 4] = empty([Ny, Nx, Nz], dtype=int32) |
| 41 | + palette: i32[4, 3] = empty([4, 3], dtype=int32) |
| 42 | + |
| 43 | + for j in range(Ny): |
| 44 | + y_0 = y_offset + dy_dj * f64(j + 1) |
| 45 | + for i in range(Nx): |
| 46 | + x_0 = x_offset + dx_di * f64(i + 1) |
| 47 | + x = 0.0; y = 0.0; n = 0 |
| 48 | + while(True): |
| 49 | + x_sqr = x ** 2.0 |
| 50 | + y_sqr = y ** 2.0 |
| 51 | + if (x_sqr + y_sqr > f64(4) or n == n_max): |
| 52 | + image[j,i] = 255 - n |
| 53 | + break |
| 54 | + y = y_0 + f64(2.0) * x * y |
| 55 | + x = x_0 + x_sqr - y_sqr |
| 56 | + n = n + 1 |
| 57 | + |
| 58 | + palette[0,0] = 0; palette[0,1] = 135; palette[0,2] = 68 |
| 59 | + palette[1,0] = 0; palette[1,1] = 87; palette[1,2] = 231 |
| 60 | + palette[2,0] = 214; palette[2,1] = 45; palette[2,2] = 32 |
| 61 | + palette[3,0] = 255; palette[3,1] = 167; palette[3,2] = 0 |
| 62 | + |
| 63 | + for j in range(Ny): |
| 64 | + for i in range(Nx): |
| 65 | + idx = image[j,i] - i32(image[j,i]/4)*4 |
| 66 | + image_color[j,i,0] = palette[idx,0] # Red |
| 67 | + image_color[j,i,1] = palette[idx,1] # Green |
| 68 | + image_color[j,i,2] = palette[idx,2] # Blue |
| 69 | + image_color[j,i,3] = 255 # Alpha |
| 70 | + |
| 71 | + print("The Mandelbrot image in color:") |
| 72 | + show_img_color(Nx, Ny, image_color) |
| 73 | + print("The Mandelbrot image in grayscale:") |
| 74 | + show_img(Nx, Ny, image) |
| 75 | + print("Done.") |
| 76 | + |
| 77 | +main0() |
0 commit comments