Exemplo n.º 1
0
def main():
    # This precomputes the color palette for maximum speed
    # You could change it to compute the color palette of your choice
    w = [wheel(i) for i in range(256)]

    # This sets up the initial wave as a smooth gradient
    u = ulab.zeros(num_pixels)
    um = ulab.zeros(num_pixels)
    f = ulab.zeros(num_pixels)

    slope = ulab.linspace(0, 256, num=num_pixels)
    th = 1

    # the first time is always random (is that a contradiction?)
    r = 0

    while True:

        # Some of the time, add a random new wave to the mix
        # increase .15 to add waves more often
        # decrease it to add waves less often
        if r < .01:
            ii = random.randrange(1, num_pixels - 1)
            # increase 2 to make bigger waves
            f[ii] = (random.random() - .5) * 2

        # Here's where to change dx, dt, and c
        # try .2, .02, 2 for relaxed
        # try 1., .7, .2 for very busy / almost random
        u, um = step(u, um, f, num_pixels, .1, .02, 1), u

        v = u * 200000 + slope + th
        for i, vi in enumerate(v):
            # Scale up by an empirical value, rotate by th, and look up the color
            pixels[i] = w[round(vi) % 256]

        # Take away a portion of the energy of the waves so they don't get out
        # of control
        u = u * .99

        # incrementing th causes the wheel to slowly cycle even if nothing else is happening
        th = (th + .25) % 256
        pixels.show()

        # Clear out the old random value, if any
        f[ii] = 0

        # and get a new random value
        r = random.random()
Exemplo n.º 2
0
    def __call__(self, leds):
        num = len(leds)

        left = np.zeros(num, dtype=np.uint8)
        right = np.zeros(num, dtype=np.uint8)
        right[:self.length] = np.linspace(0, 255, self.length)

        while True:
            # Shift left/right
            offLeft = left[0]
            offRight = right[num - 1]
            left[:-1] = left[1:]
            right[1:] = right[:-1]
            right[0] = offLeft
            left[num - 1] = offRight

            # Display
            value = np.clip * ((left + right) / 255, 0.0, 1.0)
            leds[:] = hsv2rgb(self.hue, self.sat, value)
            yield self.pause
Exemplo n.º 3
0
import math
try:
    import ulab as np
    use_ulab = True
except ImportError:
    import numpy as np
    use_ulab = False

x = np.linspace(-np.pi, np.pi, num=8)
y = np.sin(x)
if use_ulab:
    a, b = np.fft.fft(y)
    c, d = np.fft.ifft(a, b)
    # c should be equal to y
    cmp_result = []
    for p, q in zip(list(y), list(c)):
        cmp_result.append(math.isclose(p, q, rel_tol=1e-09, abs_tol=1e-09))
    print(cmp_result)

    z = np.zeros(len(x))
    a, b = np.fft.fft(y, z)
    c, d = np.fft.ifft(a, b)
    # c should be equal to y
    cmp_result = []
    for p, q in zip(list(y), list(c)):
        cmp_result.append(math.isclose(p, q, rel_tol=1e-09, abs_tol=1e-09))
    print(cmp_result)

    g = np.fft.spectrogram(y)
    h = np.sqrt(a * a + b * b)
    cmp_result = []
Exemplo n.º 4
0
#PYCLOUDIOT : LIBRARY,2,4,polyfit_library.py,
import ulab as np


def polyvalCalc(array1, array2):
    return np.polyval(array1, array2)


#PYCLOUDIOT : MAIN,7,10,polyfit_main.py, #IMPORTS :polyfit_library.py  ;ulab,
N = 1000
x = np.linspace(0, 10, num=N)
p = [1, 2, 3, 4]
polyvalCalc(x, p)
Exemplo n.º 5
0
    print(np.log2(2**1))

print(np.log10(10**1))
print(np.exp(1) - np.expm1(1))

x = np.array([-1, +1, +1, -1])
y = np.array([-1, -1, +1, +1])
result = (np.arctan2(y, x) * 180 / np.pi)
ref_result = np.array([-135.0, -45.0, 45.0, 135.0], dtype=np.float)
cmp_result = []
for i in range(len(x)):
    cmp_result.append(
        math.isclose(result[i], ref_result[i], rel_tol=1E-9, abs_tol=1E-9))
print(cmp_result)

x = np.linspace(-2 * np.pi, 2 * np.pi, 5)
result = np.sin(x)
ref_result = np.array([
    2.4492936e-16, -1.2246468e-16, 0.0000000e+00, 1.2246468e-16, -2.4492936e-16
],
                      dtype=np.float)
cmp_result = []
for i in range(len(x)):
    cmp_result.append(
        math.isclose(result[i], ref_result[i], rel_tol=1E-9, abs_tol=1E-9))
print(cmp_result)

result = np.cos(x)
ref_result = np.array([1., -1., 1., -1., 1.], dtype=np.float)
cmp_result = []
for i in range(len(x)):
import gc
gc.collect()
free_ram_i = gc.mem_free()
import time
ti_time = time.ticks_us()
dt_time = time.ticks_diff(time.ticks_us(), ti_time)
ti_import = time.ticks_us()
import ulab as np
from ulab import vector
from ulab import fft
dt_import = time.ticks_diff(time.ticks_us(), ti_import)

n_points = 1024
x = np.linspace(0, 10, num=n_points)
y = vector.sin(x)
ti_fft = time.ticks_us()
a, b = fft.fft(y)
dt_fft = time.ticks_diff(time.ticks_us(), ti_fft)

gc.collect()
free_ram_f = gc.mem_free()

print("Free RAM from {} to {} bytes, so {} bytes used ".format(free_ram_i, free_ram_f, free_ram_i - free_ram_f))
print("Time to import ulab v{} : {:.3f} ms".format(np.__version__, (dt_import - dt_time)/1000))
print("Time to calculate FFT of {} points : {:.3f} ms".format(n_points, (dt_fft - dt_time)/1000))
Exemplo n.º 7
0
try:
    import ulab as np
except ImportError:
    import numpy as np

x = np.linspace(0, 9, num=10)
y = x * x
print(np.trapz(y))
print(np.trapz(y, x=x))
def generateLinSpace(N):
    return np.linspace(0, N, N)
Exemplo n.º 9
0
p = [1, 1, 1, 0]
x = [0, 1, 2, 3, 4]
result = np.polyval(p, x)
ref_result = np.array([0, 3, 14, 39, 84])
for i in range(len(x)):
    print(math.isclose(result[i], ref_result[i], rel_tol=1E-9, abs_tol=1E-9))

a = np.array(x)
result = np.polyval(p, a)
ref_result = np.array([0, 3, 14, 39, 84])
for i in range(len(x)):
    print(math.isclose(result[i], ref_result[i], rel_tol=1E-9, abs_tol=1E-9))

# linear fit
x = np.linspace(-10, 10, 20)
y = 1.5 * x + 3
result = np.polyfit(x, y, 1)
ref_result = np.array([1.5, 3.0])
for i in range(2):
    print(math.isclose(result[i], ref_result[i], rel_tol=1E-9, abs_tol=1E-9))

# 2nd degree fit
x = np.linspace(-10, 10, 20)
y = x * x * 2.5 - x * 0.5 + 1.2
result = np.polyfit(x, y, 2)
ref_result = np.array([2.5, -0.5, 1.2])
for i in range(3):
    print(math.isclose(result[i], ref_result[i], rel_tol=1E-9, abs_tol=1E-9))

# 3rd degree fit
Exemplo n.º 10
0
import ulab as np

# polynom evaluation
x = np.linspace(0, 10, num=9)
p = [1, 2, 3]
y = np.polyval(p, x)
print(y)

# linear fit
x = np.linspace(-5, 5, num=11)
y = x + np.sin(x)
p = np.polyfit(x, y, 1)
print(p)

# quadratic fit
x = np.linspace(-5, 5, num=11)
y = x * x + np.sin(x) * 3.0
p = np.polyfit(x, y, 2)
print(p)

# cubic fit
x = np.linspace(-5, 5, num=11)
y = x * x * x + np.sin(x) * 10.0
p = np.polyfit(x, y, 3)
print(p)
Exemplo n.º 11
0
from ulab import linalg
import ulab
print(ulab.ones(3))
print(ulab.ones((2,3)))
print(ulab.zeros(3))
print(ulab.zeros((2,3)))
print(ulab.eye(3))
print(ulab.ones(1, dtype=ulab.int8))
print(ulab.ones(2, dtype=ulab.uint8))
print(ulab.ones(3, dtype=ulab.int16))
print(ulab.ones(4, dtype=ulab.uint16))
print(ulab.ones(5, dtype=ulab.float))
print(ulab.linspace(0, 1, 9))
Exemplo n.º 12
0
import ulab
from ulab import poly
from ulab import vector

# polynom evaluation
x = ulab.linspace(0, 10, num=9)
p = [1, 2, 3]
y = poly.polyval(p, x)
print(y)

# linear fit
x = ulab.linspace(-5, 5, num=11)
y = x + vector.sin(x)
p = poly.polyfit(x, y, 1)
print(p)

# quadratic fit
x = ulab.linspace(-5, 5, num=11)
y = x * x + vector.sin(x) * 3.0
p = poly.polyfit(x, y, 2)
print(p)

# cubic fit
x = ulab.linspace(-5, 5, num=11)
y = x * x * x + vector.sin(x) * 10.0
p = poly.polyfit(x, y, 3)
print(p)
Exemplo n.º 13
0
print(np.eye(3, M=4, k=1))
print(np.eye(3, M=4, k=2))
print(np.eye(3, M=4, k=3))
print(np.eye(4, M=4))
print(np.eye(4, M=3, k=0))
print(np.eye(4, M=3, k=-1))
print(np.eye(4, M=3, k=-2))
print(np.eye(4, M=3, k=-3))
print(np.eye(4, M=3, k=1))
print(np.eye(4, M=3, k=2))
print(np.eye(4, M=3, k=3))
print("Array creation using FULL:")
print(np.full((2, 4), 3, dtype=np.float))
print(np.full((2, 4), 3, dtype=np.uint8))
print("Array creation using LINSPACE:")
print(np.linspace(0, 10, num=5))
print(np.linspace(0, 10, num=5, endpoint=False))
print(np.linspace(0, 10, num=5, endpoint=True))
print(np.linspace(0, 10, num=5, endpoint=False, dtype=np.uint8))
print(np.linspace(0, 10, num=5, endpoint=False, dtype=np.uint16))
print(np.linspace(0, 10, num=5, endpoint=False, dtype=np.int8))
print(np.linspace(0, 10, num=5, endpoint=False, dtype=np.int16))
print("Array creation using LOGSPACE:")
print(np.logspace(0, 10, num=5))
print(np.logspace(0, 10, num=5, endpoint=False))
print(np.logspace(0, 10, num=5, endpoint=True))
print(np.logspace(0, 10, num=5, endpoint=False, dtype=np.uint8))
print(np.logspace(0, 10, num=5, endpoint=False, dtype=np.uint16))
print(np.logspace(0, 10, num=5, endpoint=False, dtype=np.int8))
print(np.logspace(0, 10, num=5, endpoint=False, dtype=np.int16))
print("Array creation using ZEROS:")
Exemplo n.º 14
0
def quasicrystal_opt(width, height, N=256, group=None, f=None, p=None, n=None):
    """
    # Quasicrystal Pattern Generator
    # https://code.activestate.com/recipes/579094-quasicrystal-pattern-generator/
    # https://en.wikipedia.org/wiki/Quasicrystal
    # http://mainisusuallyafunction.blogspot.com/2011/10/quasicrystals-as-sums-of-waves-in-plane.html
    #
    N : number of colors (default : 256)
    group : displayio.Group object.
    f : frequency, int [5-30] (default : random)
    p : phase, float [0-pi] (default : random)
    n : rotations, int [5-20] (default: random)
    (range indicate random range choice)
    """

    init = 0
    init_calc = 0
    time_row = 0
    inner = 0
    draw = 0

    start = time.monotonic()

    if group is None:
        group = displayio.Group()
    elif group:
        group.pop()
    gc.collect()
    pixels = displayio.Bitmap(width, height, N)
    palette = displayio.Palette(N)

    # corral colors
    def ColorMap(p):
        sr = sg = sb = 0
        if (p < 64):
            sr=0 ; sg=p*4 ; sb=255
        elif (p < 128):
            sr=(p-64)*4 ; sg=255 ; sb=(255-(p-64)*4)
        elif (p < 192):
            sr=255 ; sg=255  ;sb = (p-128)*4
        elif (p < 256):
            sr=255 ; sg=(255-(p-191)*4) ; sb= (255-(p-191)*4)
        return (sr,sg,sb)

    for i in range(N):
        r=255*i//(N-1)
        s=ColorMap(r)
        palette[i]=s[0]*2**16+s[1]*2**8+s[2]

    # blue to yellow
    #for i in range(N):
    #    j = int((i/N)*255)
    #    palette[i]=j*2**16+j*2**8+128-j//2
    #palette[0] = 0x000088

    # grayscale
    #for i in range(N):
        #j = 128+int(i*(128/N))
    #    j = int((i/N)*255)
    #    palette[i]=j*2**16+j*2**8+j
    #palette[0] = 0

    tile_grid = displayio.TileGrid(pixels, pixel_shader=palette)
    group.append(tile_grid)
    if f is None:
        f = random.random() * 27 + 8 # frequency
    if p is None:
        p = random.random() * math.pi # phase
    if n is None:
        n = random.randint(7, 15) # of rotations
    init += time.monotonic() - start
    # intermediary calculus
    start = time.monotonic()
    fp = f + p
    rot = 3.14 * 2.0 / n
    Nn = (N - 1) / n
    #row = ulab.array([i for i in range(width)])
    row = ulab.linspace(-6.28, 0, num=width//2)
    col = ulab.linspace(-6.28, 0, num=height//2)
    #x2 = row * row
    #y2 = col * col
    ky = 0
    init_calc += time.monotonic() - start
    for y in col:
        s_row = time.monotonic()
        #y = ky * h4pi - 6.28
        #y2 = y**2
        atan = ulab.vector.arctan2( col[ky], row )
        #atan = ulab.vector.atan( row / y )
        dist = ulab.vector.sqrt((row * row) + (y**2)) * fp
        #dist = dist * fp
        z = ulab.zeros(width//2)
        s_inner = time.monotonic()
        for i in range(n):
            z = z + ulab.vector.cos(ulab.vector.sin(atan + (i * rot)) * dist)
        inner += time.monotonic() - s_inner
        z = abs(z * Nn)
        time_row += time.monotonic() - s_row
        s_draw = time.monotonic()
        for i, c in enumerate(z):
            pixels[ky*width+i] = int(c)
            pixels[ky*width+(width-1 -i)] = int(c)
            pixels[(height-1-ky)*width+i] = int(c)
            pixels[(height-1-ky)*width+(width-1 -i)] = int(c)

        draw += time.monotonic() - s_draw
        ky += 1
        #gc.collect()
    #gc.collect()
    print("time report :")
    print(" init       :", init)
    print(" init calc  :", init_calc)
    print(" rows       :", time_row-inner)
    print("  inner loop:", inner)
    print(" draw       :", draw)

    return group
Exemplo n.º 15
0
def mandelbrot_ulab(WIDTH, HEIGHT, N=256, group=None, CENTER=(-0.5, 0), DIAMX=2.3):
    """
    mandelbrot()
    return a group with drawing of mandelbrot fractal in it.

    Parameters :
        WIDTH : width of the bitmap
        HEIGHT : height of the bitmap
        N : number of iterations, and number of colors (default 256)
        group : reuse a group instead of creating a new one
        CENTER : tuple containing the center coordinates
        DIAMX : "zoom" level, from 2.3 to 0.000027
    """

    DIAMY = DIAMX*HEIGHT/WIDTH

    XMIN=CENTER[0]-DIAMX/2
    XMAX=CENTER[0]+DIAMX/2

    YMIN=CENTER[1]-DIAMY/2
    YMAX=CENTER[1]+DIAMY/2

    r1 = ulab.linspace(XMIN, XMAX, num=WIDTH)
    r2 = ulab.linspace(YMIN, YMAX, num=HEIGHT)
    if group is None:
        group = displayio.Group()
    elif group:
        group.pop()

    bitmap = displayio.Bitmap(WIDTH, HEIGHT, N)

    def ColorMap(p):
        sr = sg = sb = 0
        if (p < 64):
            sr=0 ; sg=p*4 ; sb=255
        elif (p < 128):
            sr=(p-64)*4 ; sg=255 ; sb=(255-(p-64)*4)
        elif (p < 192):
            sr=255 ; sg=255  ;sb = (p-128)*4
        elif (p < 256):
            sr=255 ; sg=(255-(p-191)*4) ; sb= (255-(p-191)*4)
        return (sr,sg,sb)

    palette = displayio.Palette(N)

    for i in range(N):
        r=255*i//(N-1)
        s=ColorMap(r)
        palette[i]=s[0]*2**16+s[1]*2**8+s[2]

    palette[0]=0
    palette[1]=0xffffff

    tile_grid = displayio.TileGrid(bitmap, pixel_shader=palette)
    group.append(tile_grid)

    #############################

    # Mandelbrot Drawing        #

    #############################
    before = 0
    loop = 0
    after = 0

    print("Start drawing mandelbrot fractal :", CENTER, DIAMX, N)
    start = time.monotonic()
    for xp in range(WIDTH):
        s_before = time.monotonic()
        col_z_imag = ulab.array(r2)
        x = ulab.ones(HEIGHT)*r1[xp]
        x2 = x * x
        z2 = col_z_imag * col_z_imag
        output = ulab.zeros(HEIGHT, dtype=ulab.int16)
        notdone = [True]*HEIGHT
        before += time.monotonic() - s_before
        s_loop = time.monotonic()
        for i in range(N):
            z2 = col_z_imag * col_z_imag
            x2 = x * x
            try:
                output[(x2 + z2 ) < 4] = i
            except IndexError:
                break
            #col_z_imag[notdone] = ( ( x * col_z_imag )[notdone] * 2 ) + r2[notdone]
            col_z_imag = ( ( x * col_z_imag ) * 2 ) + r2
            #x[notdone] = (x2 - z2)[notdone] + r1[xp]
            x = (x2 - z2) + r1[xp]
        loop += time.monotonic() - s_loop
        s_after = time.monotonic()

        limit = output >= N-1
        if limit.count(True) > 0:
            output[limit] = -1
        output = output + 1
        for yp in range(HEIGHT):
            bitmap[xp,yp]= output[yp]
        after += time.monotonic() - s_after
    print("before :", before)
    print("loop   :", loop)
    print("after  :", after)
    print("total  :", time.monotonic() - start)
    return group