Exemplo n.º 1
0
def main():
    max_all = 10

    while True:
        mic.record(samples_bit, len(samples_bit))
        samples = np.array(samples_bit[3:])
        spectrogram1 = spectrogram(samples)
        # spectrum() is always nonnegative, but add a tiny value
        # to change any zeros to nonzero numbers
        spectrogram1 = np.log(spectrogram1 + 1e-7)
        spectrogram1 = spectrogram1[1:(fft_size // 2) - 1]
        min_curr = np.min(spectrogram1)
        max_curr = np.max(spectrogram1)

        if max_curr > max_all:
            max_all = max_curr
        else:
            max_curr = max_curr - 1

        print(min_curr, max_all)
        min_curr = max(min_curr, 3)
        # Plot FFT
        data = (spectrogram1 - min_curr) * (51. / (max_all - min_curr))
        # This clamps any negative numbers to zero
        data = data * np.array((data > 0))
        graph.show(data)
Exemplo n.º 2
0
    def gotopoint(self, position, speed=None, absolute=True):
        '''move machine to position or with displacement at constant speed

        Axes are moved independently to simplify the calculation.
        The move is carried out as a first order spline, i.e. only velocity.

        position     -- list with position or displacement in mm for each motor
        speed        -- list with speed in mm/s, if None default speeds used
        absolute     -- True if position, False if displacement
        '''
        assert len(position) == self.platform.motors
        if speed is not None:
            assert len(speed) == self.platform.motors
        else:
            speed = [10]*self.platform.motors
        # conversions to steps / count give rounding errors
        # minimized by setting speed to integer
        speed = np.absolute(np.array(speed))
        displacement = np.array(position)
        if absolute:
            # TODO: position machine should be in line with self._position
            #       which to pick?
            displacement -= self._position

        homeswitches_hit = [0]*len(position)
        for idx, disp in enumerate(displacement):
            if disp == 0:
                # no displacement, go to next axis
                continue
            # Time needed for move
            #    unit oscillator ticks (times motor position is updated)
            time = abs(disp/speed[idx])
            ticks_total = (time*MOTORFREQ).round().astype(int)
            # mm -> steps
            steps_per_mm = list(self.platform.stepspermm.values())[idx]
            speed_steps = int(round(speed[idx] * steps_per_mm*np.sign(disp)))
            speed_cnts = self.steps_to_count(speed_steps)/MOTORFREQ
            velocity = np.zeros_like(speed).astype('int64')
            velocity[idx] = speed_cnts

            if self.test:
                (yield from self.set_parsing(True))
            else:
                self.set_parsing(True)
            while ticks_total > 0:
                ticks_move = \
                     MOVE_TICKS if ticks_total >= MOVE_TICKS else ticks_total
                # execute move and retrieve if switch is hit
                switches_hit = (yield from self.spline_move(int(ticks_move),
                                                            velocity.tolist()))
                ticks_total -= ticks_move
                # move is aborted if home switch is hit and
                # velocity is negative
                cond = (switches_hit[idx] == 1) & (np.sign(disp) < 0)
                if cond:
                    break
        # update internally stored position
        self._position += displacement
        # set position to zero if home switch hit
        self._position[homeswitches_hit == 1] = 0
Exemplo n.º 3
0
    def home_axes(self, axes, speed=None, displacement=-200):
        '''home given axes, i.e. [1,0,1] homes x, z and not y

        axes         -- list with axes to home
        speed        -- speed in mm/s used to home
        displacement -- displacement used to touch home switch
        '''
        assert len(axes) == self.platform.motors
        dist = np.array(axes)*np.array([displacement]*self.platform.motors)
        yield from self.gotopoint(position=dist.tolist(),
                                  speed=speed, absolute=False)
def segmentAudio(featureData, audio, trailing_10ms):
    # In this example we have an array of 1 second of audio data.
    # This is a 16,000 element array.
    # each micro second is 16 elements in this array.
    # the stride is how far over we adjust the start of the window on each step
    # in this example it is 20 ms (20x16=320).
    # The width of the window for which we capture the spectogram is 30ms (16x30=480).
    # this function will turn the input array into a dictionary of start time to wav data

    input_audio = np.concatenate((trailing_10ms, audio), axis=0)

    input_size = input_audio.size()

    total_segments = math.floor(input_size / stride_size)

    start_index = 0

    for segment_index in range(total_segments):

        end_index = min(start_index + window_size, input_size)

        # print ("segment_index=%d,start_index=%d, end_index=%d, size=%d\n" % (segment_index, start_index, end_index, end_index-start_index))

        slice = Slice(input_audio[start_index:end_index], start_index)

        featureData.addSlice(slice)

        start_index = start_index + stride_size

    # return the trailing 10ms
    return np.array(input_audio[input_size - 160:input_size], dtype=np.int16)
Exemplo n.º 5
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)
def predict(new_data):
    """
    Predict label for a single new data instance.
    """

    gc.collect()
    score = np.array([(np.dot(new_data, w) + b)
                      for w, b in zip(weights, bias)])
    return labels[np.argmin(score)]
Exemplo n.º 7
0
 def _set_val(self, val):
     if val is None:
         return
     else:
         self._target = np.clip(np.array(val), self._min, self._max)
         if self._maxStep == 0:
             self._val = self._target
         else:
             self._nInc = self._maxStep
             self._inc = (self._target - self._val) / self._maxStep
Exemplo n.º 8
0
def main():
    #  value for audio samples
    max_all = 10
    #  variable to move data along the matrix
    scroll_offset = 0
    #  setting the y axis value to equal the scroll_offset
    y = scroll_offset

    while True:
        #  record the audio sample
        mic.record(samples_bit, len(samples_bit))
        #  send the sample to the ulab array
        samples = np.array(samples_bit[3:])
        #  creates a spectogram of the data
        spectrogram1 = spectrogram(samples)
        # spectrum() is always nonnegative, but add a tiny value
        # to change any zeros to nonzero numbers
        spectrogram1 = np.log(spectrogram1 + 1e-7)
        spectrogram1 = spectrogram1[1:(fft_size//2)-1]
        #  sets range of the spectrogram
        min_curr = np.min(spectrogram1)
        max_curr = np.max(spectrogram1)
        #  resets values
        if max_curr > max_all:
            max_all = max_curr
        else:
            max_curr = max_curr-1
        min_curr = max(min_curr, 3)
        # stores spectrogram in data
        data = (spectrogram1 - min_curr) * (51. / (max_all - min_curr))
        # sets negative numbers to zero
        data = data * np.array((data > 0))
        #  resets y
        y = scroll_offset
        #  runs waves to write data to the LED's
        waves(data, y)
        #  updates scroll_offset to move data along matrix
        scroll_offset = (y + 1) % 9
        #  writes data to the RGB matrix
        is31.show()
Exemplo n.º 9
0
 def __init__(self, platform=None):
     '''  platform  -- object which has gateware settings
                       only passed to controller if virtual
                       test is executed. Needed in lasers.py
                       as each test here has a slightly
                       different TestPlatform
     '''
     # case raspberry
     if platform is None:
         self.test = False
         from gpiozero import LED
         import spidev
         from smbus2 import SMBus
         self.platform = Firestarter(micropython=False)
         # IC bus used to set power laser
         self.bus = SMBus(self.platform.ic_dev_nr)
         # SPI to sent data to scanner
         self.spi = spidev.SpiDev()
         self.spi.open(*self.platform.spi_dev)
         self.spi.mode = 1
         self.spi.max_speed_hz = round(1E6)
         self.chip_select = LED(self.platform.chip_select)
         # programs TMC2130
         self.init_steppers()
         # stepper motor enable pin
         self.enable = LED(self.platform.enable_pin)
     # case micropython:
     elif upython:
         self.test = False
         import machine
         self.platform = platformmicro(micropython=True)
         # IC bus
         self.bus = machine.I2C(self.platform.ic_dev_nr)
         self.bus.init(machine.I2C.CONTROLLER, adr=self.platform.ic_addr)
         # SPI
         # spi port is hispi
         self.spi = machine.SPI(self.spi_dev, baudrate=round(1E6))
         self.chip_select = machine.Pin(self.platform.chip_select)
         # program TMC2130
         # TODO: add TMC2130 library to micropython
         # self.init_steppers()
         # stepper motor enable pin
         self.enable = machine.Pin(self.platform.enable_pin)
     else:
         self.platform = platform
         self.test = True
     # maximum number of times tried to write to FIFO
     # if memoery is full
     self.maxtrials = 10 if self.test else 1E5
     self.laser_params = params(self.platform)
     self._position = np.array([0]*self.platform.motors, dtype='float64')
Exemplo n.º 10
0
    def preprocess_data(self, signal):
        """Preprocess incoming signal before decoding algorithms.
        This involves applying a bandpass filter to isolate the target SSVEP range
        and then downsampling the signal to the Nyquist boundary.

        Returns:
            [np.ndarray]: filtered and downsampled signal
        """
        from lib.signal import sos_filter

        ds_factor = self.downsampling_factor
        signal = np.array(signal) - np.mean(signal)  # remove DC component

        # downsample filtered signal by only selecting every `ds_factor` sample
        return sos_filter(signal, fs=self.base_sample_freq)[::ds_factor]
Exemplo n.º 11
0
    def position(self):
        '''retrieves position from FPGA and updates internal position

           position is stored on the FPGA in steps
           position is stored on object in mm

           return positions as np.array in mm
                  order is [x, y, z]
        '''
        command = [COMMANDS.POSITION] + WORD_BYTES*[0]
        for i in range(self.platform.motors):
            read_data = (yield from self.send_command(command))
            self._position[i] = unpack('!q', read_data[1:])[0]
        # step --> mm
        self._position = (self._position /
                          np.array(list(self.platform.stepspermm.values())))
        return self._position
Exemplo n.º 12
0
def power_iteration(A, iterations):
    """
    Iterative algo. to find the eigenvector of a matrix A corresponding to the largest
    eigenvalue.

    TODO: Establish some measure or heuristic of min number of iterations required
    """
    # choose random initial vector to reduce risk of choosing one orthogonal to
    # target eigen vector
    b_k = np.array([urandom.random() for i in range(len(A))])

    for _ in range(iterations):
        b_k1 = np.dot(A, b_k)
        b_k1_norm = np.linalg.norm(b_k1)
        # re normalize the vector
        b_k = b_k1 / b_k1_norm

    return b_k1_norm, b_k
Exemplo n.º 13
0
    def spline_move(self, ticks, coefficients):
        '''write spline move instruction with ticks and coefficients to FIFO

        If you have 2 motors and execute a second order spline
        You send 4 coefficients.
        If the controller supports a third order spline,
        remaining coefficients are padded as zero.
        User needs to submit all coefficients up to highest order used.

        ticks           -- number of ticks in move, integer
        coefficients    -- coefficients for spline move per axis, list

        returns array with zero if home switch is hit
        '''
        platform = self.platform
        # maximum allowable ticks is move ticks,
        # otherwise counters overflow in FPGA
        assert ticks <= MOVE_TICKS
        assert len(coefficients) % platform.motors == 0
        write_byte = COMMANDS.WRITE.to_bytes(1, 'big')
        move_byte = INSTRUCTIONS.MOVE.to_bytes(1, 'big')
        commands = [write_byte +
                    ticks.to_bytes(7, 'big') + move_byte]
        # check max order given by caller of function
        max_coeff_order = (len(coefficients)//platform.motors)
        # prepare commands
        for motor in range(platform.motors):
            for degree in range(platform.poldegree):
                # set to zero if coeff not provided by caller
                if degree > max_coeff_order-1:
                    coeff = 0
                else:
                    idx = degree+motor*max_coeff_order
                    coeff = coefficients[idx]
                data = coeff.to_bytes(8, 'big', signed=True)
                commands += [write_byte + data]
        # send commands to FPGA
        for command in commands:
            data_out = (yield from self.send_command(command,
                                                     blocking=True))
            state = (yield from self.get_state(data_out))
        axes_names = list(platform.stepspermm.keys())
        return np.array([state[key] for key in axes_names])
def fit():
    """
    Train the model with dataset.
    """

    gc.collect()

    global weights, bias, training_time

    weights = []
    bias = []
    training_time = 0

    start_time = time.monotonic_ns()

    for l in labels:

        pos_labels = np.array([x for x, y in zip(data, target) if y != l])
        neg_labels = np.array([x for x, y in zip(data, target) if y == l])

        avg_pos = np.mean(pos_labels, axis=0) / data_factor
        avg_neg = np.mean(neg_labels, axis=0) / data_factor

        weight = ((avg_pos - avg_neg) / (avg_pos + avg_neg))
        weights.append(weight)

        weighted_scores = np.array([np.dot(d, weight) for d in data])

        weighted_pos_labels = np.array(
            [x for x, y in zip(weighted_scores, target) if y != l])
        weighted_neg_labels = np.array(
            [x for x, y in zip(weighted_scores, target) if y == l])

        pos_score_avg = np.mean(weighted_pos_labels) / data_factor
        neg_score_avg = np.mean(weighted_neg_labels) / data_factor

        bias_label = -(neg_labels.size * pos_score_avg + pos_labels.size *
                       neg_score_avg) / (pos_labels.size + neg_labels.size)

        bias.append(bias_label)

    training_time = (time.monotonic_ns() - start_time) / 1000000
    weights = np.array(weights)
    bias = np.array(bias)
Exemplo n.º 15
0
    def decode(self, *args):
        """
        Run decoding on current state of output buffer.

        Note that `*args` is specified but not used directly: this allows
        this function to be called using `micropython.schedule` which
        requires the scheduled func to accept an argument.
        """
        data = np.array(self.output_buffer)
        data = data.reshape((1, len(data)))  # reshape to row vector
        gc.collect()

        result = self.decoder.compute_corr(data)

        # note: need to be careful not to change the memory address of this variable using direct
        # assignment since the logger depends on this reference. Also would just be inefficient.
        self.decoded_output.update(
            {freq: round(corr[0], 5)
             for freq, corr in result.items()})
        gc.collect()
        return self.decoded_output
Exemplo n.º 16
0
  def listen(self, record_length=10000, listener = [], early_stop=False):
    gc.collect()
    print("Hz:", self.HZ, "T:", self.T, "record_length: ", record_length, "min_freq:", self.min_freq, "max_freq:", self.max_freq, "min_amp:", self.min_amp, "Free mem:", gc.mem_free())
    
    self.start_ticks  = time.ticks_ms()
    self.last_sample_time, self.ticks = 0, 0
    t0 = time.ticks_us()
    while True:
 
      # SOFTWARE SAMPLING
      if time.ticks_us() - self.last_sample_time >= self.SAMPLE_INTERVAL_US: 
        self.last_sample_time = self.last_sample_time +  self.SAMPLE_INTERVAL_US
        
        self.ticks = self.ticks + 1
        self.MEMORY.append(pot.read())
        
        if self.ticks % self.N == 0:
          # COPY BUFFERS
          samples = np.array(self.MEMORY)
          del self.MEMORY[:]
                    
          # ANALYZE
          self._analyze(samples, listener, time.ticks_us() - t0)
          
          # BLINK
          self.led(self.iamp > 0)
          
          # SLEEP TO BREAK SYMMETRIC SAMPLING
          self.MEMORY = []
          gc.collect()
          t0 = time.ticks_us()
                                       
        # TIME LIMIT
        if (time.ticks_ms() >= self.start_ticks + record_length) or (self.detected and early_stop):
          break
        
    gc.collect()
    print("Free mem:", gc.mem_free())
Exemplo n.º 17
0
SOS_SSVEP_BANDPASS_256HZ = np.array([
    [
        5.18442631e-04,
        5.91022291e-04,
        5.18442631e-04,
        1.00000000e00,
        -1.58700686e00,
        6.47826110e-01,
    ],
    [
        1.00000000e00,
        -6.71721317e-01,
        1.00000000e00,
        1.00000000e00,
        -1.56164716e00,
        7.42956116e-01,
    ],
    [
        1.00000000e00,
        -1.19862825e00,
        1.00000000e00,
        1.00000000e00,
        -1.53434369e00,
        8.53024717e-01,
    ],
    [
        1.00000000e00,
        -1.36462221e00,
        1.00000000e00,
        1.00000000e00,
        -1.52074686e00,
        9.31086238e-01,
    ],
    [
        1.00000000e00,
        -1.41821305e00,
        1.00000000e00,
        1.00000000e00,
        -1.52570664e00,
        9.80264626e-01,
    ],
])
Exemplo n.º 18
0
print(math.isclose(result, ref_result, rel_tol=1E-6, abs_tol=1E-6))
    
print(np.degrees(np.pi))
print(np.radians(np.degrees(np.pi)))
print(np.floor(np.pi))
print(np.ceil(np.pi))
print(np.sqrt(np.pi))
print(np.exp(1))
print(np.log(np.exp(1)))

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)
Exemplo n.º 19
0
import math

try:
    from ulab import numpy as np
except ImportError:
    import numpy as np

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
Exemplo n.º 20
0
import math
try:
    from ulab import numpy as np
except ImportError:
    import numpy as np

print("Testing np.min:")
print(np.min([1]))
print(np.min(np.array([1], dtype=np.float)))
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.uint8)
print(np.min(a))
print(np.min(a, axis=0))
print(np.min(a, axis=1))
a = np.array([range(255 - 5, 255),
              range(240 - 5, 240),
              range(250 - 5, 250)],
             dtype=np.uint8)
print(np.min(a))
print(np.min(a, axis=0))
print(np.min(a, axis=1))
a = np.array([range(255 - 5, 255),
              range(240 - 5, 240),
              range(250 - 5, 250)],
             dtype=np.int8)
print(np.min(a))  ## Problem here
print(np.min(a, axis=0))
print(np.min(a, axis=1))
a = np.array([range(255 - 5, 255),
              range(240 - 5, 240),
              range(250 - 5, 250)],
             dtype=np.uint16)
Exemplo n.º 21
0
    def __getitem__(self, key: Union[_RClassKeyType, Tuple[_RClassKeyType,
                                                           ...]]):

        if not isinstance(key, tuple):
            key = (key, )

        objs: List[np.ndarray] = []
        scalars: List[int] = []
        arraytypes: List[_DType] = []
        scalartypes: List[_DType] = []

        # these may get overridden in following loop
        axis = 0

        for idx, item in enumerate(key):
            scalar = False

            try:
                if isinstance(item, np.ndarray):
                    newobj = item

                elif isinstance(item, slice):
                    step = item.step
                    start = item.start
                    stop = item.stop
                    if start is None:
                        start = 0
                    if step is None:
                        step = 1
                    if isinstance(step, complex):
                        size = int(abs(step))
                        newobj: np.ndarray = np.linspace(start, stop, num=size)
                    else:
                        newobj = np.arange(start, stop, step)

                # if is number
                elif isinstance(item, (int, float, bool)):
                    newobj = np.array([item])
                    scalars.append(len(objs))
                    scalar = True
                    scalartypes.append(newobj.dtype())

                else:
                    newobj = np.array(item)

            except TypeError:
                raise Exception(
                    "index object %s of type %s is not supported by r_[]" %
                    (str(item), type(item)))

            objs.append(newobj)
            if not scalar and isinstance(newobj, np.ndarray):
                arraytypes.append(newobj.dtype())

        # Ensure that scalars won't up-cast unless warranted
        final_dtype = min(arraytypes + scalartypes)
        for idx, obj in enumerate(objs):
            if obj.dtype != final_dtype:
                objs[idx] = np.array(objs[idx], dtype=final_dtype)

        return np.concatenate(tuple(objs), axis=axis)
Exemplo n.º 22
0
import math

try:
    from ulab import numpy as np
except ImportError:
    import numpy as np


def matrix_is_close(A, B, n):
    # primitive (i.e., independent of other functions) check of closeness of two square matrices
    for i in range(n):
        for j in range(n):
            print(math.isclose(A[i][j], B[i][j], rel_tol=1E-9, abs_tol=1E-9))


a = np.array([1, 2, 3], dtype=np.int16)
b = np.array([4, 5, 6], dtype=np.int16)
ab = np.dot(a.transpose(), b)
print(math.isclose(ab, 32.0, rel_tol=1E-9, abs_tol=1E-9))

a = np.array([1, 2, 3], dtype=np.int16)
b = np.array([4, 5, 6], dtype=np.float)
ab = np.dot(a.transpose(), b)
print(math.isclose(ab, 32.0, rel_tol=1E-9, abs_tol=1E-9))

a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])

c = np.array([[19, 22], [43, 50]])
matrix_is_close(np.dot(a, b), c, 2)
MODE = 0
LASTMODE = 1  # start up in sound reactive mode
i = 0

# Main loop
while True:
    i = (i + 0.5) % 256  # run from 0 to 255
    TILT_COLOR = colorwheel(i)
    if MODE == 0:  # If currently off...
        enable.value = True
        power_on(POWER_ON_DURATION)  # Power up!
        MODE = LASTMODE

    elif MODE >= 1:  # If not OFF MODE...
        mic.record(samples_bit, len(samples_bit))
        samples = np.array(samples_bit[3:])
        spectrum = spectrogram(samples)
        spectrum = spectrum[:128]
        spectrum[0] = 0
        spectrum[1] = 0
        peak_idx = np.argmax(spectrum)
        peak_freq = peak_idx * 16000 / 256
        #        print((peak_idx, peak_freq, spectrum[peak_idx]))
        magnitude = spectrum[peak_idx]
        #         time.sleep(1)
        if peak_freq == 812.50 and magnitude > SOUND_THRESHOLD:
            animations.next()
            time.sleep(1)
        if peak_freq == 875 and magnitude > SOUND_THRESHOLD:
            if MODE == 1:
                MODE = 2
Exemplo n.º 24
0
# Filter computed at https://fiiir.com/
# Sampling rate: 8Hz
# Cutoff freqency: 0.5Hz
# Transition bandwidth 0.25Hz
# Window type: Regular
# Number of coefficients: 31
# Manually trimmed to 16 coefficients
taps = np.array([
    +0.861745279666917052 / 2,
    -0.134728583242092248,
    -0.124472980501612152,
    -0.108421190967457198,
    -0.088015688587190874,
    -0.065052714580474319,
    -0.041490993500537393,
    -0.019246940463156042,
    -0.000000000000000005,
    +0.014969842582454691,
    +0.024894596100322432,
    +0.029569415718397409,
    +0.029338562862396955,
    +0.025020274838643962,
    +0.017781854357373172,
    +0.008981905549472832,
])

# How much reflected light is required before pulse sensor activates
# These values are triggered when I bring my finger within a half inch.
# The sensor works when the finger is pressed lightly against the sensor.
PROXIMITY_THRESHOLD_HI = 225
PROXIMITY_THRESHOLD_LO = 215
Exemplo n.º 25
0
import math

try:
    from ulab import numpy as np
except ImportError:
    import numpy as np

x = np.array((1,2,3))
y = np.array((1,10,100,1000))
result = (np.convolve(x, y))
ref_result = np.array([1, 12, 123, 1230, 2300, 3000],dtype=np.float)
cmp_result = []
for p,q in zip(list(result), list(ref_result)):
    cmp_result.append(math.isclose(p, q, rel_tol=1e-06, abs_tol=1e-06))
print(cmp_result)
    ])
# print(column_table)

# MAIN LOOP -------------

dynamic_level = 10  # For responding to changing volume levels
frames, start_time = 0, monotonic()  # For frames-per-second calc

while True:
    # The try/except here is because VERY INFREQUENTLY the I2C bus will
    # encounter an error when accessing the LED driver, whether from bumping
    # around the wires or sometimes an I2C device just gets wedged. To more
    # robustly handle the latter, the code will restart if that happens.
    try:
        mic.record(rec_buf, fft_size)  # Record batch of 16-bit samples
        samples = np.array(rec_buf)  # Convert to ndarray
        # Compute spectrogram and trim results. Only the left half is
        # normally needed (right half is mirrored), but we trim further as
        # only the low_bin to high_bin elements are interesting to graph.
        spectrum = spectrogram(samples)[low_bin:high_bin + 1]
        # Linearize spectrum output. spectrogram() is always nonnegative,
        # but add a tiny value to change any zeros to nonzero numbers
        # (avoids rare 'inf' error)
        spectrum = np.log(spectrum + 1e-7)
        # Determine minimum & maximum across all spectrum bins, with limits
        lower = max(np.min(spectrum), 4)
        upper = min(max(np.max(spectrum), lower + 6), 20)

        # Adjust dynamic level to current spectrum output, keeps the graph
        # 'lively' as ambient volume changes. Sparkle but don't saturate.
        if upper > dynamic_level:
Exemplo n.º 27
0
import math

try:
    from ulab import scipy, numpy as np
except ImportError:
    import scipy
    import numpy as np

A = np.array([[3, 0, 2, 6], [2, 1, 0, 1], [1, 0, 1, 4], [1, 2, 1, 8]])
b = np.array([4, 2, 4, 2])

# forward substitution
result = scipy.linalg.solve_triangular(A, b, lower=True)
ref_result = np.array([1.333333333, -0.666666666, 2.666666666, -0.083333333])
for i in range(4):
    print(math.isclose(result[i], ref_result[i], rel_tol=1E-6, abs_tol=1E-6))

# backward substitution
result = scipy.linalg.solve_triangular(A, b, lower=False)
ref_result = np.array([-1.166666666, 1.75, 3.0, 0.25])
for i in range(4):
    print(math.isclose(result[i], ref_result[i], rel_tol=1E-6, abs_tol=1E-6))
Exemplo n.º 28
0
try:
    from ulab import numpy as np
except ImportError:
    import numpy as np

print(len(np.array([1, 2, 3, 4, 5], dtype=np.uint8)))
print(len(np.array([[1, 2, 3], [4, 5, 6]])))

print(~np.array([0, -1, -100], dtype=np.uint8))
print(~np.array([0, -1, -100], dtype=np.uint16))
print(~np.array([0, -1, -100], dtype=np.int8))
print(~np.array([0, -1, -100], dtype=np.int16))

print(abs(np.array([0, -1, -100], dtype=np.uint8)))
print(abs(np.array([0, -1, -100], dtype=np.uint16)))
print(abs(np.array([0, -1, -100], dtype=np.int8)))
print(abs(np.array([0, -1, -100], dtype=np.int16)))
print(abs(np.array([0, -1, -100], dtype=np.float)))

print(-(np.array([0, -1, -100], dtype=np.uint8)))
print(-(np.array([0, -1, -100], dtype=np.uint16)))
print(-(np.array([0, -1, -100], dtype=np.int8)))
print(-(np.array([0, -1, -100], dtype=np.int16)))
print(-(np.array([0, -1, -100], dtype=np.float)))

print(+(np.array([0, -1, -100], dtype=np.uint8)))
print(+(np.array([0, -1, -100], dtype=np.uint16)))
print(+(np.array([0, -1, -100], dtype=np.int8)))
print(+(np.array([0, -1, -100], dtype=np.int16)))
print(+(np.array([0, -1, -100], dtype=np.float)))
Exemplo n.º 29
0
try:
    from ulab import numpy as np
    use_ulab = True
except ImportError:
    import numpy as np
    use_ulab = False

a = np.array([1, 2, 3, 4], dtype=np.int8)
b = a.copy()
print(b)
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.int16)
b = a.copy()
print(b)
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.float)
b = a.copy()
print(b)
if use_ulab:
    print(a.dtype())
    print(a.flatten())
    print(np.array([1, 2, 3], dtype=np.uint8).itemsize())
    print(np.array([1, 2, 3], dtype=np.uint16).itemsize())
    print(np.array([1, 2, 3], dtype=np.int8).itemsize())
    print(np.array([1, 2, 3], dtype=np.int16).itemsize())
    print(np.array([1, 2, 3], dtype=np.float).itemsize())
    print(np.array([1, 2, 3], dtype=np.float).shape())
    print(np.array([[1], [2], [3]], dtype=np.float).shape())
    print(np.array([[1], [2], [3]], dtype=np.float).reshape((1, 3)))
    print(np.array([[1], [2], [3]], dtype=np.float).size())
    print(np.array([1, 2, 3], dtype=np.float).size())
    print(np.array([1, 2, 3], dtype=np.uint8).tobytes())
    print(np.array([1, 2, 3], dtype=np.int8).tobytes())
Exemplo n.º 30
0
try:
    from ulab import numpy as np
except ImportError:
    import numpy as np

x = np.array([1, 2, 3, 4, 5])
xp = np.array([1, 2, 3, 4])
fp = np.array([1, 2, 3, 4])
print(np.interp(x, xp, fp))
print(np.interp(x, xp, fp, left=0.0))
print(np.interp(x, xp, fp, right=10.0))
print(np.interp(x, xp, fp, left=0.0, right=10.0))