def main():
    # This precomputes the color palette for maximum speed
    # You could change it to compute the color palette of your choice
    w = [colorwheel(i) for i in range(256)]

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

    slope = np.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 colorwheel 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()
Esempio n. 2
0
def harmonic_reference(f0, fs, Ns, Nh=1, standardise_out=False):
    """
    Generate reference signals for canonical correlation analysis (CCA)
    -based steady-state visual evoked potentials (SSVEPs) detection [1, 2].
    function [ y_ref ] = cca_reference(listFreq, fs,  Ns, Nh)
    Input:
      f0        : stimulus frequency
      fs              : Sampling frequency
      Ns              : # of samples in trial
      Nh          : # of harmonics
    Output:
      X           : Generated reference signals with shape (Nf, Ns, 2*Nh)
    """
    X = np.zeros((Nh * 2, Ns))

    for harm_i in range(Nh):
        # Sin and Cos
        X[2 * harm_i, :] = np.sin(
            np.arange(1, Ns + 1) * (1 / fs) * 2 * np.pi * (harm_i + 1) * f0)
        gc.collect()
        X[2 * harm_i + 1, :] = np.cos(
            np.arange(1, Ns + 1) * (1 / fs) * 2 * np.pi * (harm_i + 1) * f0)
        gc.collect()

    # print(micropython.mem_info(1))
    if standardise_out:  # zero mean, unit std. dev
        return standardise(X)
    return X
Esempio n. 3
0
    def __init__(self, val: list, _minmax, lim=0, max_steps=0, unit="-"):
        super().__init__(lim, max_steps, unit)

        # Convert into np.array
        self._min = np.array(_minmax[0])
        self._max = np.array(_minmax[1])
        _val = np.array(val)
        n = len(_val)
        if n != len(self._min) or n != len(self._max):
            raise ValueError("Parameters are not consistent")

        # Initialize other variables
        self._target = np.zeros(n)
        self._inc = np.zeros(n)
        self._val = np.zeros(n)
        self._dim = n
        self._set_val(_val)
Esempio n. 4
0
        self.nfft = nfft
        self.ncep = ncep
        self.nfilt = nfilt
        self.frate = frate
        self.fshift = float(samprate) / frate

        # Build Hamming window
        self.wlen = int(wlen * samprate)
        self.win = numpy.hamming(self.wlen)

        # Prior sample for pre-emphasis
        self.prior = 0
        self.alpha = alpha

        # Build mel filter matrix
        self.filters = numpy.zeros((nfft/2+1,nfilt), 'd')
        dfreq = float(samprate) / nfft
        if upperf > samprate/2:
            raise(Exception,
                  "Upper frequency %f exceeds Nyquist %f" % (upperf, samprate/2))
        melmax = mel(upperf)
        melmin = mel(lowerf)
        dmelbw = (melmax - melmin) / (nfilt + 1)
        # Filter edges, in Hz
        filt_edge = melinv(melmin + dmelbw * numpy.arange(nfilt + 2, dtype='d'))

        for whichfilt in range(0, nfilt):
            # Filter triangles, in DFT points
            leftfr = round(filt_edge[whichfilt] / dfreq)
            centerfr = round(filt_edge[whichfilt + 1] / dfreq)
            rightfr = round(filt_edge[whichfilt + 2] / dfreq)
Esempio n. 5
0
def main():
    sensor.enable_proximity = True
    while True:
        # Wait for user to put finger over sensor
        while sensor.proximity < PROXIMITY_THRESHOLD_HI:
            time.sleep(.01)

        # After the finger is sensed, set up the color sensor
        sensor.enable_color = True
        # This sensor integration time is just a little bit shorter than 125ms,
        # so we should always have a fresh value when we ask for it, without
        # checking if a value is available.
        sensor.integration_time = 220
        # In my testing, 64X gain saturated the sensor, so this is the biggest
        # gain value that works properly.
        sensor.color_gain = APDS9660_AGAIN_4X
        white_leds.value = True

        # And our data structures
        # The most recent data samples, equal in number to the filter taps
        data = np.zeros(len(taps))
        # The filtered value on the previous iteration
        old_value = 1
        # The times of the most recent pulses registered.  Increasing this number
        # makes the estimation more accurate, but at the expense of taking longer
        # before a pulse number can be computed
        pulse_times = []
        # The estimated heart rate based on the recent pulse times
        rate = None
        # the number of samples taken
        n = 0

        # Rather than sleeping for a fixed duration, we compute a deadline
        # in nanoseconds and wait for the new deadline time to arrive.  This
        # helps the long term frequency of measurements better match the desired
        # frequency.
        t0 = deadline = time.monotonic_ns()
        # As long as their finger is over the sensor, capture data
        while sensor.proximity >= PROXIMITY_THRESHOLD_LO:
            deadline += dt
            sleep_deadline(deadline)
            value = sum(sensor.color_data)  # Combination of all channels
            data = np.roll(data, 1)
            data[-1] = value
            # Compute the new filtered variable by applying the filter to the
            # recent data samples
            filtered = np.sum(data * taps)

            # We gathered enough data to fill the filters, and
            # the light value crossed the zero line in the positive direction
            # Therefore we need to record a pulse
            if n > len(taps) and old_value < 0 <= filtered:
                # This crossing time is estimated, but it increases the pulse
                # estimate resolution quite a bit.  If only the nearest 1/8s
                # was used for pulse estimation, the smallest pulse increment
                # that can be measured is 7.5bpm.
                cross = estimated_cross_time(old_value, filtered, deadline)
                # store this pulse time (in seconds since sensor-touch)
                pulse_times.append((cross - t0) * 1e-9)
                # and maybe delete an old pulse time
                del pulse_times[:-10]
                # And compute a rate based on the last recorded pulse times
                if len(pulse_times) > 1:
                    rate = 60 / (pulse_times[-1] -
                                 pulse_times[0]) * (len(pulse_times) - 1)
            old_value = filtered

            # We gathered enough data to fill the filters, so report the light
            # value and possibly the estimated pulse rate
            if n > len(taps):
                print((filtered, rate))
            n += 1

        # Turn off the sensor and the LED and go back to the top for another run
        sensor.enable_color = False
        white_leds.value = False
        print()
    while time.monotonic_ns() < deadline_ns:
        pass


# Initialize our sensor
i2c = board.I2C()
sensor = adafruit_bmp280.Adafruit_BMP280_I2C(i2c)
sensor.standby_period = adafruit_bmp280.STANDBY_TC_1000
# Disable in-sensor filtering, because we want to show how it's done in
# CircuitPython
sensor.iir_filter = adafruit_bmp280.IIR_FILTER_DISABLE
sensor.overscan_pressure = adafruit_bmp280.OVERSCAN_X1

# And our data structures
# The most recent data samples, equal in number to the filter taps
data = np.zeros(len(taps))
t0 = deadline = time.monotonic_ns()
n = 0
# Take an initial reading to subtract off later, so that the graph in mu
# accentuates the small short term changes in pressure rather than the large
# DC offset of around 980
offset = sensor.pressure

while True:
    deadline += dt
    sleep_deadline(deadline)
    # Move the trace near the origin so small differences can be seen in the mu
    # plot window .. you wouldn't do this subtraction step if you are really
    # interested in absolute barometric pressure.
    value = sensor.pressure - offset
    if n == 0:
Esempio n. 7
0
try:
    from ulab import numpy as np
except:
    import numpy as np


def print_as_buffer(a):
    print(len(memoryview(a)), list(memoryview(a)))


print_as_buffer(np.ones(3))
print_as_buffer(np.zeros(3))
print_as_buffer(np.eye(4))
print_as_buffer(np.ones(1, dtype=np.int8))
print_as_buffer(np.ones(2, dtype=np.uint8))
print_as_buffer(np.ones(3, dtype=np.int16))
print_as_buffer(np.ones(4, dtype=np.uint16))
print_as_buffer(np.ones(5, dtype=np.float))
print_as_buffer(np.linspace(0, 1, 9))
Esempio n. 8
0
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:")
print(np.zeros(3))
print(np.zeros((3,3)))
print(np.zeros((3,3), dtype=np.uint8))
print(np.zeros((3,3), dtype=np.uint16))
print(np.zeros((3,3), dtype=np.int8))
print(np.zeros((3,3), dtype=np.int16))
print(np.zeros((4,3), dtype=np.float))
print(np.zeros((3,4), dtype=np.float))
print("Array creation using ONES:")
print(np.ones(3))
print(np.ones((3,3)))
print(np.ones((3,3), dtype=np.uint8))
print(np.ones((3,3), dtype=np.uint16))
print(np.ones((3,3), dtype=np.int8))
print(np.ones((3,3), dtype=np.int16))
print(np.ones((4,3), dtype=np.float))
sdin_pin = Pin(13)

audio_in = I2S(0,
               sck=bck_pin,
               ws=ws_pin,
               sd=sdin_pin,
               mode=I2S.RX,
               bits=16,
               format=I2S.MONO,
               rate=16000,
               ibuf=9600)

mic_samples = bytearray(3200)
mic_samples_mv = memoryview(mic_samples)

trailing_10ms = np.zeros(160, dtype=np.int16)

audio_in.irq(processAudio)

num_read = audio_in.readinto(mic_samples_mv)

inferenceNeeded = False


def timerCallback(timer):
    global printPerSecondStats

    printPerSecondStats = True


bytes_processed_since_last_inference = 0
Esempio n. 10
0
from ulab import numpy as np

print(np.ones(3))
print(np.ones((2, 3)))
print(np.zeros(3))
print(np.zeros((2, 3)))
print(np.eye(3))
print(np.ones(1, dtype=np.int8))
print(np.ones(2, dtype=np.uint8))
print(np.ones(3, dtype=np.int16))
print(np.ones(4, dtype=np.uint16))
print(np.ones(5, dtype=np.float))
print(np.linspace(0, 1, 9))