Exemplo n.º 1
0
    def get_avg_band_powers(cls, data: NDArray, channels: List,
                            sampling_rate: int, apply_filter: bool) -> Tuple:
        """calculate avg and stddev of BandPowers across all channels

        :param data: 2d array for calculation
        :type data: NDArray
        :param channels: channels - rows of data array which should be used for calculation
        :type channels: List
        :param sampling_rate: sampling rate
        :type sampling_rate: int
        :param apply_filter: apply bandpass and bandstop filtrers or not
        :type apply_filter: bool
        :return: avg and stddev arrays for bandpowers
        :rtype: tuple
        """

        if (data.ndim != 2):
            raise BrainFlowError(
                'Shape of data array must be 2',
                BrainflowExitCodes.INVALID_ARGUMENTS_ERROR.value)

        avg_bands = numpy.zeros(5).astype(numpy.float64)
        stddev_bands = numpy.zeros(5).astype(numpy.float64)
        data_1d = numpy.zeros(len(channels) * data.shape[1])
        for i, channel in enumerate(channels):
            for j in range(data.shape[1]):
                data_1d[j + data.shape[1] * i] = data[channel][j]
        res = DataHandlerDLL.get_instance().get_avg_band_powers(
            data_1d, len(channels), data.shape[1], sampling_rate,
            int(apply_filter), avg_bands, stddev_bands)
        if res != BrainflowExitCodes.STATUS_OK.value:
            raise BrainFlowError('unable to get_avg_band_powers', res)

        return avg_bands, stddev_bands
Exemplo n.º 2
0
    def perform_highpass(cls, data: NDArray[Float64], sampling_rate: int,
                         cutoff: float, order: int, filter_type: int,
                         ripple: float) -> None:
        """apply high pass filter to provided data

        :param data: data to filter, filter works in-place
        :type data: NDArray[Float64]
        :param sampling_rate: board's sampling rate
        :type sampling_rate: int
        :param cutoff: cutoff frequency
        :type cutoff: float
        :param order: filter order
        :type order: int
        :param filter_type: filter type from special enum
        :type filter_type: int
        :param ripple: ripple value for Chebyshev filter
        :type ripple: float
        """
        if not isinstance(sampling_rate, int):
            raise BrainFlowError(
                'wrong type for sampling rate',
                BrainflowExitCodes.INVALID_ARGUMENTS_ERROR.value)
        if not isinstance(filter_type, int):
            raise BrainFlowError(
                'wrong type for filter type',
                BrainflowExitCodes.INVALID_ARGUMENTS_ERROR.value)
        if len(data.shape) != 1:
            raise BrainFlowError(
                'wrong shape for filter data array, it should be 1d array',
                BrainflowExitCodes.INVALID_ARGUMENTS_ERROR.value)
        res = DataHandlerDLL.get_instance().perform_highpass(
            data, data.shape[0], sampling_rate, cutoff, order, filter_type,
            ripple)
        if res != BrainflowExitCodes.STATUS_OK.value:
            raise BrainFlowError('unable to apply high pass filter', res)
Exemplo n.º 3
0
    def perform_rolling_filter(cls, data: NDArray[Float64], period: int,
                               operation: int) -> None:
        """smooth data using moving average or median

        :param data: data to smooth, it works in-place
        :type data: NDArray[Float64]
        :param period: window size
        :type period: int
        :param operation: int value from AggOperation enum
        :type operation: int
        """
        if not isinstance(period, int):
            raise BrainFlowError(
                'wrong type for period',
                BrainflowExitCodes.INVALID_ARGUMENTS_ERROR.value)
        if not isinstance(operation, int):
            raise BrainFlowError(
                'wrong type for operation',
                BrainflowExitCodes.INVALID_ARGUMENTS_ERROR.value)
        if len(data.shape) != 1:
            raise BrainFlowError(
                'wrong shape for filter data array, it should be 1d array',
                BrainflowExitCodes.INVALID_ARGUMENTS_ERROR.value)
        res = DataHandlerDLL.get_instance().perform_rolling_filter(
            data, data.shape[0], period, operation)
        if res != BrainflowExitCodes.STATUS_OK.value:
            raise BrainFlowError('unable to smooth data', res)
Exemplo n.º 4
0
    def write_file(cls, data, file_name: str, file_mode: str) -> None:
        """write data to file, in file data will be transposed

        :param data: data to store in a file
        :type data: 2d numpy array
        :param file_name: file name to store data
        :type file_name: str
        :param file_mode: 'w' to rewrite file or 'a' to append data to file
        :type file_mode: str
        """
        if len(data.shape) != 2:
            raise BrainFlowError(
                'wrong shape for filter data array, it should be 2d array',
                BrainflowExitCodes.INVALID_ARGUMENTS_ERROR.value)
        try:
            file = file_name.encode()
        except:
            file = file_name
        try:
            mode = file_mode.encode()
        except:
            mode = file_mode
        data_flatten = data.flatten()
        res = DataHandlerDLL.get_instance().write_file(data_flatten,
                                                       data.shape[0],
                                                       data.shape[1], file,
                                                       mode)
        if res != BrainflowExitCodes.STATUS_OK.value:
            raise BrainFlowError('unable to write file', res)
Exemplo n.º 5
0
    def perform_downsampling (cls, data, period, operation):
        """perform data downsampling, it doesnt apply lowpass filter for you, it just aggregates several data points

        :param data: initial data
        :type data: 1d numpy array
        :param period: downsampling period
        :type period: int
        :param operation: int value from AggOperation enum
        :type operation: int
        :return: downsampled data
        :rtype: 1d numpy array
        """
        if not isinstance (period, int):
            raise BrainFlowError ('wrong type for period', BrainflowExitCodes.INVALID_ARGUMENTS_ERROR.value)
        if not isinstance (operation, int):
            raise BrainFlowError ('wrong type for operation', BrainflowExitCodes.INVALID_ARGUMENTS_ERROR.value)
        if len (data.shape) != 1:
            raise BrainFlowError ('wrong shape for filter data array, it should be 1d array', BrainflowExitCodes.INVALID_ARGUMENTS_ERROR.value)
        if period <= 0:
            raise BrainFlowError ('Invalid value for period', BrainflowExitCodes.INVALID_ARGUMENTS_ERROR.value)

        downsampled_data = numpy.zeros (int (data.shape[0] / period)).astype (numpy.float64)
        res = DataHandlerDLL.get_instance ().perform_downsampling (data, data.shape[0], period, operation, downsampled_data)
        if res != BrainflowExitCodes.STATUS_OK.value:
            raise BrainFlowError ('unable to perform downsampling', res)

        return downsampled_data
Exemplo n.º 6
0
    def perform_bandstop (cls, data, sampling_rate, center_freq, band_width, order, filter_type, ripple):
        """apply band stop filter to provided data

        :param data: data to filter, filter works in-place
        :type data: 1d numpy array
        :param sampling_rate: board's sampling rate
        :type sampling_rate: float
        :param center_freq: center frequency
        :type center_freq: float
        :param band_width: band width
        :type band_width: float
        :param order: filter order
        :type order: int
        :param filter_type: filter type from special enum
        :type filter_type: int
        :param ripple: ripple value for Chebyshev filter
        :type ripple: float
        """
        if not isinstance (sampling_rate, int):
            raise BrainFlowError ('wrong type for sampling rate', BrainflowExitCodes.INVALID_ARGUMENTS_ERROR.value)
        if not isinstance (filter_type, int):
            raise BrainFlowError ('wrong type for filter type', BrainflowExitCodes.INVALID_ARGUMENTS_ERROR.value)
        if len (data.shape) != 1:
            raise BrainFlowError ('wrong shape for filter data array, it should be 1d array', BrainflowExitCodes.INVALID_ARGUMENTS_ERROR.value)
        res = DataHandlerDLL.get_instance ().perform_bandstop (data, data.shape[0], sampling_rate, center_freq, band_width, order, filter_type, ripple)
        if res != BrainflowExitCodes.STATUS_OK.value:
            raise BrainFlowError ('unable to apply band stop filter', res)
Exemplo n.º 7
0
    def perform_fft (cls, data, window):
        """perform direct fft

        :param data: data for fft, len of data must be a power of 2
        :type data: 1d numpy array
        :param window: window function
        :type window: int
        :return: numpy array of complex values, len of this array is N / 2 + 1
        :rtype: 1d numpy array
        """
        def is_power_of_two (n):
            return (n != 0) and (n & (n - 1) == 0)

        if (not is_power_of_two (data.shape[0])):
            raise BrainFlowError ('data len is not power of 2: %d' % data.shape[0], BrainflowExitCodes.INVALID_ARGUMENTS_ERROR.value)

        temp_re = numpy.zeros (int (data.shape[0] / 2 + 1)).astype (numpy.float64)
        temp_im = numpy.zeros (int (data.shape[0] / 2 + 1)).astype (numpy.float64)
        res = DataHandlerDLL.get_instance ().perform_fft (data, data.shape[0], window, temp_re, temp_im)
        if res != BrainflowExitCodes.STATUS_OK.value:
            raise BrainFlowError ('unable to perform fft', res)

        output = numpy.zeros (int (data.shape[0] / 2 + 1)).astype (numpy.complex128)
        for i in range (output.shape[0]):
            output[i] = numpy.complex128 (complex (temp_re[i], temp_im[i]))

        return output
Exemplo n.º 8
0
    def get_log_psd (cls, data, sampling_rate, window):
        """calculate log PSD

        :param data: data to calc log psd, len of data must be a power of 2
        :type data: 1d numpy array
        :param sampling_rate: sampling rate
        :type sampling_rate: int
        :param window: window function
        :type window: int
        :return: amplitude and frequency arrays of len N / 2 + 1
        :rtype: tuple(ndarray, ndarray)
        """
        def is_power_of_two (n):
            return (n != 0) and (n & (n - 1) == 0)

        if (not is_power_of_two (data.shape[0])):
            raise BrainFlowError ('data len is not power of 2', BrainflowExitCodes.INVALID_ARGUMENTS_ERROR.value)

        ampls = numpy.zeros (int (data.shape[0] / 2 + 1)).astype (numpy.float64)
        freqs = numpy.zeros (int (data.shape[0] / 2 + 1)).astype (numpy.float64)
        res = DataHandlerDLL.get_instance ().get_log_psd (data, data.shape[0], sampling_rate, window, ampls, freqs)
        if res != BrainflowExitCodes.STATUS_OK.value:
            raise BrainFlowError ('unable to calc log psd', res)

        return ampls, freqs
Exemplo n.º 9
0
    def get_psd(cls, data: NDArray[Float64], sampling_rate: int,
                window: int) -> Tuple:
        """calculate PSD

        :param data: data to calc psd, len of data must be a power of 2
        :type data: NDArray[Float64]
        :param sampling_rate: sampling rate
        :type sampling_rate: int
        :param window: window function
        :type window: int
        :return: amplitude and frequency arrays of len N / 2 + 1
        :rtype: tuple
        """

        check_memory_layout_row_major(data, 1)

        def is_power_of_two(n):
            return (n != 0) and (n & (n - 1) == 0)

        if (not is_power_of_two(data.shape[0])):
            raise BrainFlowError(
                'data len is not power of 2: %d' % data.shape[0],
                BrainflowExitCodes.INVALID_ARGUMENTS_ERROR.value)

        ampls = numpy.zeros(int(data.shape[0] / 2 + 1)).astype(numpy.float64)
        freqs = numpy.zeros(int(data.shape[0] / 2 + 1)).astype(numpy.float64)
        res = DataHandlerDLL.get_instance().get_psd(data, data.shape[0],
                                                    sampling_rate, window,
                                                    ampls, freqs)
        if res != BrainflowExitCodes.STATUS_OK.value:
            raise BrainFlowError('unable to calc psd', res)

        return ampls, freqs
Exemplo n.º 10
0
    def read_file (cls, file_name):
        """read data from file

        :param file_name: file name to read
        :type file_name: str
        :return: 2d numpy array with data from this file, data will be transposed to original dimensions
        :rtype: 2d numpy array
        """
        try:
            file = file_name.encode ()
        except:
            file = file_name

        num_elements = numpy.zeros (1).astype (numpy.int32)
        res = DataHandlerDLL.get_instance ().get_num_elements_in_file (file, num_elements)
        if res != BrainflowExitCodes.STATUS_OK.value:
            raise BrainFlowError ('unable to determine number of elements in file', res)

        data_arr = numpy.zeros (num_elements[0]).astype (numpy.float64)
        num_rows = numpy.zeros (1).astype (numpy.int32)
        num_cols = numpy.zeros (1).astype (numpy.int32)

        res = DataHandlerDLL.get_instance ().read_file (data_arr, num_rows, num_cols, file, num_elements[0])
        if res != BrainflowExitCodes.STATUS_OK.value:
            raise BrainFlowError ('unable to read file', res)

        if len (num_rows) == 0 or len (num_cols) == 0:
            return None

        data_arr = data_arr[0:num_rows[0] * num_cols[0]].reshape (num_rows[0], num_cols[0])
        return data_arr        
Exemplo n.º 11
0
    def perform_bandstop(cls, data: NDArray[Float64], sampling_rate: int,
                         center_freq: float, band_width: float, order: int,
                         filter_type: int, ripple: float) -> None:
        """apply band stop filter to provided data

        :param data: data to filter, filter works in-place
        :type data: NDArray[Float64]
        :param sampling_rate: board's sampling rate
        :type sampling_rate: int
        :param center_freq: center frequency
        :type center_freq: float
        :param band_width: band width
        :type band_width: float
        :param order: filter order
        :type order: int
        :param filter_type: filter type from special enum
        :type filter_type: int
        :param ripple: ripple value for Chebyshev filter
        :type ripple: float
        """
        check_memory_layout_row_major(data, 1)
        if not isinstance(sampling_rate, int):
            raise BrainFlowError(
                'wrong type for sampling rate',
                BrainflowExitCodes.INVALID_ARGUMENTS_ERROR.value)
        if not isinstance(filter_type, int):
            raise BrainFlowError(
                'wrong type for filter type',
                BrainflowExitCodes.INVALID_ARGUMENTS_ERROR.value)
        res = DataHandlerDLL.get_instance().perform_bandstop(
            data, data.shape[0], sampling_rate, center_freq, band_width, order,
            filter_type, ripple)
        if res != BrainflowExitCodes.STATUS_OK.value:
            raise BrainFlowError('unable to apply band stop filter', res)
Exemplo n.º 12
0
    def get_psd_welch(cls, data: NDArray[Float64], nfft: int, overlap: int,
                      sampling_rate: int, window: int) -> Tuple:
        """calculate PSD using Welch method

        :param data: data to calc psd
        :type data: NDArray[Float64]
        :param nfft: FFT Window size, must be power of 2
        :type nfft: int
        :param overlap: overlap of FFT Windows, must be between 0 and nfft
        :type overlap: int
        :param sampling_rate: sampling rate
        :type sampling_rate: int
        :param window: window function
        :type window: int
        :return: amplitude and frequency arrays of len N / 2 + 1
        :rtype: tuple
        """
        def is_power_of_two(n):
            return (n != 0) and (n & (n - 1) == 0)

        if (not is_power_of_two(nfft)):
            raise BrainFlowError(
                'nfft is not power of 2: %d' % nfft,
                BrainflowExitCodes.INVALID_ARGUMENTS_ERROR.value)

        ampls = numpy.zeros(int(nfft / 2 + 1)).astype(numpy.float64)
        freqs = numpy.zeros(int(nfft / 2 + 1)).astype(numpy.float64)
        res = DataHandlerDLL.get_instance().get_psd_welch(
            data, data.shape[0], nfft, overlap, sampling_rate, window, ampls,
            freqs)
        if res != BrainflowExitCodes.STATUS_OK.value:
            raise BrainFlowError('unable to calc psd welch', res)

        return ampls, freqs
Exemplo n.º 13
0
    def remove_environmental_noise(cls, data: NDArray[Float64],
                                   sampling_rate: int,
                                   noise_type: float) -> None:
        """remove env noise using notch filter

        :param data: data to filter, filter works in-place
        :type data: NDArray[Float64]
        :param sampling_rate: board's sampling rate
        :type sampling_rate: int
        :param noise_type: noise type
        :type noise_type: int
        """
        check_memory_layout_row_major(data, 1)
        if not isinstance(sampling_rate, int):
            raise BrainFlowError(
                'wrong type for sampling rate',
                BrainflowExitCodes.INVALID_ARGUMENTS_ERROR.value)
        if not isinstance(noise_type, int):
            raise BrainFlowError(
                'wrong type for noise type',
                BrainflowExitCodes.INVALID_ARGUMENTS_ERROR.value)
        res = DataHandlerDLL.get_instance().remove_environmental_noise(
            data, data.shape[0], sampling_rate, noise_type)
        if res != BrainflowExitCodes.STATUS_OK.value:
            raise BrainFlowError('unable to apply notch filter', res)
Exemplo n.º 14
0
def check_memory_layout_row_major(data, ndim):
    if data is None:
        raise BrainFlowError('data is None',
                             BrainflowExitCodes.EMPTY_BUFFER_ERROR.value)
    if len(data.shape) != ndim:
        raise BrainFlowError('wrong shape for filter data array, it should be %dd array' % ndim,
                             BrainflowExitCodes.INVALID_ARGUMENTS_ERROR.value)
    if not data.flags['C_CONTIGUOUS']:
        raise BrainFlowError('wrong memory layout, should be row major, make sure you didnt tranpose array',
                             BrainflowExitCodes.INVALID_ARGUMENTS_ERROR.value)
Exemplo n.º 15
0
    def detrend (cls, data: NDArray[Float64], detrend_operation: int) -> None:
        """detrend data

        :param data: data to calc psd
        :type data: NDArray[Float64]
        :param detrend_operation: Type of detrend operation
        :type detrend_operation: int
        """
        if len (data.shape) != 1:
            raise BrainFlowError ('wrong shape for data, should be 1d array', BrainflowExitCodes.INVALID_ARGUMENTS_ERROR.value)
        res = DataHandlerDLL.get_instance ().detrend (data, data.shape[0], detrend_operation)
        if res != BrainflowExitCodes.STATUS_OK.value:
            raise BrainFlowError ('unable to detrend data', res)
Exemplo n.º 16
0
    def write_file(cls, data, file_name, file_mode):
        """write data to file, in file data will be transposed

        :param data: data to store in a file
        :type data: numpy array
        :param file_name: file name to store data
        :type file_name: str
        :param file_mode: 'w' to rewrite file or 'a' to append data to file
        :type file_mode: str
        """
        try:
            file = file_name.encode()
        except:
            file = file_name
        try:
            mode = file_mode.encode()
        except:
            mode = file_mode

        data_flatten = data.flatten()
        res = DataHandlerDLL.get_instance().write_file(data_flatten,
                                                       data.shape[0],
                                                       data.shape[1], file,
                                                       mode)
        if res != BrainflowExitCodes.STATUS_OK.value:
            raise BrainFlowError('unable to write file', res)
Exemplo n.º 17
0
    def perform_wavelet_transform(cls, data: NDArray[Float64], wavelet: str,
                                  decomposition_level: int) -> Tuple:
        """perform wavelet transform

        :param data: initial data
        :type data: NDArray[Float64]
        :param wavelet: supported vals: db1..db15,haar,sym2..sym10,coif1..coif5,bior1.1,bior1.3,bior1.5,bior2.2,bior2.4,bior2.6,bior2.8,bior3.1,bior3.3,bior3.5 ,bior3.7,bior3.9,bior4.4,bior5.5,bior6.8
        :type wavelet: str
        :param decomposition_level: level of decomposition
        :type decomposition_level: int
        :return: tuple of wavelet coeffs in format [A(J) D(J) D(J-1) ..... D(1)] where J is decomposition level, A - app coeffs, D - detailed coeffs, and array with lengths for each block
        :rtype: tuple
        """
        try:
            wavelet_func = wavelet.encode()
        except:
            wavelet_func = wavelet

        wavelet_coeffs = numpy.zeros(data.shape[0] + 2 * (40 + 1)).astype(
            numpy.float64)
        lengths = numpy.zeros(decomposition_level + 1).astype(numpy.int32)
        res = DataHandlerDLL.get_instance().perform_wavelet_transform(
            data, data.shape[0], wavelet_func, decomposition_level,
            wavelet_coeffs, lengths)
        if res != BrainflowExitCodes.STATUS_OK.value:
            raise BrainFlowError('unable to perform wavelet transform', res)

        return wavelet_coeffs[0:sum(lengths)], lengths
Exemplo n.º 18
0
    def perform_inverse_wavelet_transform (cls, wavelet_output, original_data_len, wavelet, decomposition_level):
        """perform wavelet transform

        :param wavelet_output: tuple of wavelet_coeffs and array with lengths
        :type wavelet_coeffs: typle of 2 1d numpy arrays
        :param original_data_len: len of signal before wavelet transform
        :type original_data_len: int
        :param wavelet: supported vals: db1..db15,haar,sym2..sym10,coif1..coif5,bior1.1,bior1.3,bior1.5,bior2.2,bior2.4,bior2.6,bior2.8,bior3.1,bior3.3,bior3.5 ,bior3.7,bior3.9,bior4.4,bior5.5,bior6.8
        :type wavelet: str
        :param decomposition_level: level of decomposition
        :type decomposition_level: int
        :param decomposition_lengths: array with lengths for each block
        :type decomposition_lengths: 1d numpy array
        :return: restored data
        :rtype: 1d numpy array
        """
        try:
            wavelet_func = wavelet.encode ()
        except:
            wavelet_func = wavelet

        original_data = numpy.zeros (original_data_len).astype (numpy.float64)
        res = DataHandlerDLL.get_instance ().perform_inverse_wavelet_transform (wavelet_output[0], original_data_len, wavelet_func, 
                                                                                decomposition_level, wavelet_output[1], original_data)
        if res != BrainflowExitCodes.STATUS_OK.value:
            raise BrainFlowError ('unable to perform inverse wavelet transform', res)

        return original_data
Exemplo n.º 19
0
    def _set_log_level (cls, log_level: int) -> None:
        """set BrainFlow log level, use it only if you want to write your own messages to BrainFlow logger,
        otherwise use enable_data_logger, enable_dev_data_logger or disable_data_logger

        :param log_level: log level, to specify it you should use values from LogLevels enum
        :type log_level: int
        """
        res = DataHandlerDLL.get_instance ().set_log_level (log_level)
        if res != BrainflowExitCodes.STATUS_OK.value:
            raise BrainFlowError ('unable to enable logger', res)
Exemplo n.º 20
0
    def get_csp(cls, data: NDArray[Float64],
                labels: NDArray[Float64]) -> Tuple:
        """calculate filters and the corresponding eigenvalues using the Common Spatial Patterns

        :param data: [epochs x channels x times]-shaped 3D array of data for two classes
        :type data: NDArray[Float64]
        :param labels: n_epochs-length 1D array of zeros and ones that assigns class labels for each epoch. Zero corresponds to the first class
        :type labels: NDArray[Int64] 
        :return: [channels x channels]-shaped 2D array of filters and [channels]-length 1D array of the corresponding eigenvalues
        :rtype: Tuple
        """
        if not (len(labels.shape) == 1):
            raise BrainFlowError(
                'Invalid shape of array <labels>',
                BrainflowExitCodes.INVALID_ARGUMENTS_ERROR.value)
        if not (len(labels) == data.shape[0]):
            raise BrainFlowError(
                'Invalid number of elements in array <labels>',
                BrainflowExitCodes.INVALID_ARGUMENTS_ERROR.value)

        n_epochs, n_channels, n_times = data.shape

        temp_data1d = numpy.reshape(data, (n_epochs * n_channels * n_times, ))

        output_filters = numpy.zeros(int(n_channels * n_channels)).astype(
            numpy.float64)
        output_eigenvalues = numpy.zeros(int(n_channels)).astype(numpy.float64)

        res = DataHandlerDLL.get_instance().get_csp(temp_data1d, labels,
                                                    n_epochs, n_channels,
                                                    n_times, output_filters,
                                                    output_eigenvalues)
        if res != BrainflowExitCodes.STATUS_OK.value:
            raise BrainFlowError('unable to calc csp', res)

        output_filters = numpy.reshape(output_filters,
                                       (n_channels, n_channels))

        return output_filters, output_eigenvalues
Exemplo n.º 21
0
    def predict (self, data: NDArray) -> float:
        """calculate metric from data

        :param data: input array
        :type data: NDArray
        :return: metric value
        :rtype: float
        """
        output = numpy.zeros (1).astype (numpy.float64)
        res = MLModuleDLL.get_instance ().predict (data, data.shape[0], output, self.serialized_params)
        if res != BrainflowExitCodes.STATUS_OK.value:
            raise BrainFlowError ('unable to calc metric', res)
        return output[0]
Exemplo n.º 22
0
    def set_log_file (cls, log_file: str) -> None:
        """redirect logger from stderr to file, can be called any time

        :param log_file: log file name
        :type log_file: str
        """
        try:
            file = log_file.encode ()
        except:
            file = log_file
        res = DataHandlerDLL.get_instance ().set_log_file (file)
        if res != BrainflowExitCodes.STATUS_OK.value:
            raise BrainFlowError ('unable to redirect logs to a file', res)
Exemplo n.º 23
0
    def get_nearest_power_of_two (cls, value):
        """calc nearest power of two

        :param value: input value
        :type value: int
        :return: nearest power of two
        :rtype: int
        """
        output = numpy.zeros (1).astype (numpy.int32)
        res = DataHandlerDLL.get_instance ().get_nearest_power_of_two (value, output)
        if res != BrainflowExitCodes.STATUS_OK.value:
            raise BrainFlowError ('unable to calc nearest power of two', res)

        return output[0]
Exemplo n.º 24
0
    def detrend(cls, data: NDArray[Float64], detrend_operation: int) -> None:
        """detrend data

        :param data: data to calc psd
        :type data: NDArray[Float64]
        :param detrend_operation: Type of detrend operation
        :type detrend_operation: int
        """

        check_memory_layout_row_major(data, 1)
        res = DataHandlerDLL.get_instance().detrend(data, data.shape[0],
                                                    detrend_operation)
        if res != BrainflowExitCodes.STATUS_OK.value:
            raise BrainFlowError('unable to detrend data', res)
Exemplo n.º 25
0
    def get_version(cls) -> str:
        """get version of brainflow libraries

        :return: version
        :rtype: str
        :raises BrainFlowError
        """
        string = numpy.zeros(64).astype(numpy.ubyte)
        string_len = numpy.zeros(1).astype(numpy.int32)
        res = MLModuleDLL.get_instance().get_version_ml_module(
            string, string_len, 64)
        if res != BrainflowExitCodes.STATUS_OK.value:
            raise BrainFlowError('unable to request info', res)
        return string.tobytes().decode('utf-8')[0:string_len[0]]
Exemplo n.º 26
0
    def get_window(cls, window_function: int, window_len: int) -> NDArray[Float64]:
        """perform data windowing

        :param window_function: window function
        :type window: int
        :param window_len: len of the window function
        :return: numpy array, len of the array is the same as data
        :rtype: NDArray[Float64]
        """
        window_data = numpy.zeros(int(window_len)).astype(numpy.float64)
        res = DataHandlerDLL.get_instance().get_window(window_function, window_len, window_data)
        if res != BrainflowExitCodes.STATUS_OK.value:
            raise BrainFlowError('unable to perform windowing', res)

        return window_data
Exemplo n.º 27
0
    def get_band_power (cls, psd, freq_start, freq_end):
        """calculate band power

        :param psd: psd from get_psd or get_log_psd
        :type psd: typle(ndarray, ndarray)
        :param freq_start: start freq
        :type freq_start: int
        :param freq_end: end freq
        :type freq_end: int
        :return: band power
        :rtype: float64 value
        """
        band_power = numpy.zeros (1).astype (numpy.float64)
        res = DataHandlerDLL.get_instance ().get_band_power (psd[0], psd[1], psd[0].shape[0], freq_start, freq_end, band_power)
        if res != BrainflowExitCodes.STATUS_OK.value:
            raise BrainFlowError ('unable to calc band power', res)

        return band_power[0]
Exemplo n.º 28
0
    def perform_wavelet_denoising (cls, data, wavelet, decomposition_level):
        """perform wavelet denoising

        :param data: data to denoise
        :type data: 1d numpy array
        :param wavelet: supported vals: db1..db15,haar,sym2..sym10,coif1..coif5,bior1.1,bior1.3,bior1.5,bior2.2,bior2.4,bior2.6,bior2.8,bior3.1,bior3.3,bior3.5 ,bior3.7,bior3.9,bior4.4,bior5.5,bior6.8
        :type wavelet: str
        :param decomposition_level: decomposition level
        :type decomposition_level: int
        """
        try:
            wavelet_func = wavelet.encode ()
        except:
            wavelet_func = wavelet

        res = DataHandlerDLL.get_instance ().perform_wavelet_denoising (data, data.shape[0], wavelet_func, decomposition_level)
        if res != BrainflowExitCodes.STATUS_OK.value:
            raise BrainFlowError ('unable to denoise data', res)
Exemplo n.º 29
0
    def perform_ifft (cls, data):
        """perform inverse fft

        :param data: data from fft
        :type data: 1d numpy array of numpy.complex128
        :return: restored data
        :rtype: 1d numpy array of doubles
        """
        temp_re = numpy.zeros (data.shape[0]).astype (numpy.float64)
        temp_im = numpy.zeros (data.shape[0]).astype (numpy.float64)
        for i in range (data.shape[0]):
            temp_re[i] = data[i].real
            temp_im[i] = data[i].imag
        output = numpy.zeros (2 * (data.shape[0] - 1)).astype (numpy.float64)

        res = DataHandlerDLL.get_instance ().perform_ifft (temp_re, temp_im, output.shape[0], output)
        if res != BrainflowExitCodes.STATUS_OK.value:
            raise BrainFlowError ('unable to perform ifft', res)

        return output
Exemplo n.º 30
0
    def release(self) -> None:
        """release classifier"""

        res = MLModuleDLL.get_instance().release(self.serialized_params)
        if res != BrainflowExitCodes.STATUS_OK.value:
            raise BrainFlowError('unable to release classifier', res)