Algorithm of emotional states

Description

The algorithm processes the data by a sliding window of a given length with a given frequency. If artifacts are detected on one of the bipolar channels, the artifacts on the second bipolar channel are checked, and if there are no artifacts, they are switched to that channel; in case of artifacts on both channels, the spectral values and values of mental levels are filled with previous actual values, while the counter of the number of successive artifact windows increases.

Artifacts

When the maximum number of consecutive artifact windows is reached, math.is_artifacted_sequence() returns true, which allows you to give the user information about the need to check the position of the device. This flag is usually raised 4 sec after receiving continuous artifacts. If there is no need to give notification of momentary artifacts, you can use this function as the primary for artifact notifications. Otherwise, use math.is_both_sides_artifacted() to check for momentary artifacts, returning true for artifacts on both bipolar channels for the current window.

Emotional states

The estimate of emotional states (mental levels - relaxation and concentration) is available in two variants:

  1. immediate assessment through alpha and beta wave intensity (and theta in the case of independent assessment).
  2. relative to the baseline calibration values of alpha and beta wave intensity

In both cases, the current intensity of the waves is defined as the average for the last N windows.

The algorithm starts processing the data after the first N seconds after connecting the device and when the minimum number of points for the spectrum calculation is accumulated. When reading spectral and mental values an array of appropriate structures (SpectralDataPercents and MindData) of length is returned, which is determined by the number of new recorded points, signal frequency and analysis frequency.

In this version the filters are built-in and clearly defined: BandStop_45_55, BandStop_55_65, BandStop_62, HighPass_10, LowPass_30

Calibration

According to the results of calibration, the average base value of alpha and beta waves expression is determined in percent, which are further used to calculate the relative mental levels.

Library mode

The library can operate in two modes - bipolar and multichannel. In bipolar mode only two channels are processed - left and right bipolar. In multichannel mode you can process for any number of channels using the same algorithms.

Parameters

Main parameters description

Structure MathLibSettings with fields:

  1. samplingRate - raw signal sampling frequency, Hz, integer value
  2. processWinFreq - frequency of spectrum analysis and emotional levels, Hz, integer value
  3. fftWindow - spectrum calculation window length, integer value
  4. nFirstSecSkipped - skipping the first seconds after connecting to the device, integer value
  5. bipolarMode - enabled bipolar mode, boolean value
  6. squaredSpectrum - mode of calculating spectral values of frequencies. If squared = true then values are calculated as the sum of squares of FFT bins of the spectrum of the interval of the corresponding frequency (e.g. alpha), if squared = false then as the sum of FFT bins.
  7. channelsNumber - count channels for multy-channel library mode, integer value
  8. channelForAnalysis - in case of multichannel mode: channel by default for computing spectral values and emotional levels, integer value

channelsNumber and channelForAnalysis are not used explicitly for bipolar mode, you can leave the default ones.

Separate parameters:

  1. MentalEstimationMode - type of evaluation of instant mental levels - disabled by default, boolean value
  2. SpectNormalizationByBandsWidth - spectrum normalization by bandwidth - disabled by default, boolean value

Artifact detection parameters description

Structure ArtifactDetectSetting with fields:

  1. artBord - boundary for the long amplitude artifact, mcV, integer value
  2. allowedPercentArtpoints - percent of allowed artifact points in the window, integer value
  3. rawBetapLimit - boundary for spectral artifact (beta power), detection of artifacts on the spectrum occurs by checking the excess of the absolute value of the raw beta wave power, integer value
  4. totalPowBorder - boundary for spectral artifact (in case of assessment by total power) and for channels signal quality estimation, integer value
  5. globalArtwinSec - number of seconds for an artifact sequence, the maximum number of consecutive artifact windows (on both channels) before issuing a prolonged artifact notification / device position check, integer value
  6. spectArtByTotal - assessment of spectral artifacts by total power, boolean value
  7. hanningWinSpectrum - setting the smoothing of the spectrum calculation by Hamming, boolean value
  8. hammingWinSpectrum - setting the smoothing of the spectrum calculation by Henning, boolean value
  9. numWinsForQualityAvg - number of windows for estimation of signals quality, by default = 100, which, for example, with process_win_freq=25Hz, will be equal to 4 seconds, integer value

Structure ShortArtifactDetectSetting with fields:

  1. amplArtDetectWinSize - the length of the sliding window segments for the detection of short-term amplitude artifacts, ms, integer value
  2. amplArtZerodArea - signal replacement area of the previous non-artefact to the left and right of the extremum point, ms, integer value
  3. amplArtExtremumBorder - boundary for the extremum considered to be artifactual, mcV, integer value

Structure MentalAndSpectralSetting with fields:

  1. nSecForInstantEstimation - the number of seconds to calculate the values of mental levels, integer value
  2. nSecForAveraging - spectrum averaging, integer value

Separate setting is the number of windows after the artifact with the previous actual value - to smooth the switching process after artifacts (SkipWinsAfterArtifact).

Initialization

Main parameters

final mls = MathLibSetting(samplingRate: 250,
                           processWinFreq: 25,
                           nSirstSecSkipped: 4,
                           fftWindow=1000,
                           bipolarMode: true,
                           squaredSpectrum: true,
                           channelsNumber: 4,
                           channelForAnalysis: 0);

final ads = ArtifactDetectSetting(artBord: 110,
                                  allowedPercentArtpoints: 70,
                                  rawBetapLimit: 800000,
                                  globalArtwinSec: 4,
                                  numWinsForQualityAvg: 125,
                                  hammingWinSpectrum: true,
                                  hanningWinSpectrum: false,
                                  totalPowBorder: 400000000,
                                  spectArtByTotalp: true);

final sads = ShortArtifactDetectSetting(amplArtDetectWinSize: 200,
                                        amplArtZerodArea: 200,
                                        amplArtExtremumBorder: 25);

final mss = MentalAndSpectralSetting(nSecForAveraging: 2,
                                     nSecForInstantEstimation: 4);

EmotionalMath math = EmotionalMath(mls, ads, sads, mss);

Optional parameters

// setting calibration length
int calibrationLength = 6;
math.setCalibrationLength(calibrationLength);

// type of evaluation of instant mental levels
bool independentMentaLevels = false;
math.setMentalEstimationMode(independentMentaLevels);

// number of windows after the artifact with the previous actual value
int nwinsSkipAfterArtifact = 10;
math.setSkipWinsAfterArtifact(nwinsSkipAfterArtifact);

// calculation of mental levels relative to calibration values
math.setZeroSpectWaves(true, 0, 1, 1, 1, 0);

// spectrum normalization by bandwidth
math.setSpectNormalizationByBandsWidth(True);

Types

RawChannels

Structure contains left and right bipolar values to bipolar library mode with fields:

  1. leftBipolar - left bipolar value, double value
  2. rightBipolar - right bipolar value, double value

MindData

Mental levels. Struct with fields:

  1. relAttention - relative attention value
  2. reRelaxation - relative relaxation value
  3. instAttention - instantiate attention value
  4. instRelaxation - instantiate relaxation value

SpectralDataPercents

Relative spectral values. Struct with double fields:

  1. delta
  2. theta
  3. alpha
  4. beta
  5. gamma

SideType

Side of current artufact. Enum with values:

  1. LEFT
  2. RIGHT
  3. NONE

Usage

  1. If you need calibration start calibration right after library init:
math.startCalibration();
  1. Adding and process data In bipolar mode:
StreamSubscription<List<BrainBitSignalData>>? signalSubscr =
                  sensor.signalDataStream
                      .listen((event) {
                        final samples = event.map((data) => RawChanel(leftBipolar: data.t3 - data.o1, rightBipolar: data.t4 - data.o2)).toList();
                        _math.pushBipolars(samples);
                        _math.processData();
                      }));

In multy-channel mode:

final samples = List<List<double>>.generate(size, (i) => [0, 0, 0, 0]);
math.pushMonopolars(samples);
math.processData();
  1. Then check calibration status if you need to calibrate values:
bool calibrationFinished = math.isCalibrationFinished();
// and calibration progress
int calibrationProgress = math.getCalibrationPercents();
  1. If calibration finished (or you don't need to calibrate) read output values:
// Reading mental levels in percent
List<MindData> mentalData = math.readMentalData();
// Reading relative spectral values in percent
List<SpectralDataPercents> spData = math.readSpectralDataPercents();
  1. Check artifacts 4.1. During calibration
if(math.isBothSidesArtefacted())
    // signal corruption

4.2. After (without) calibration

if(math.isArtifactedSequence())
    // signal corruption

Finishing work with the library

math.dispose();