bcijs

Namespaces

features

Members

(static) oscStream

Listen for messages over OSC

This method is exclusive to Node.js

Source:

Methods

(static) accuracy(confusionMatrix) → {number}

Calculate the accuracy of a classifier given its confusion matrix as defined by the confusionMatrix method

Parameters:
Name Type Description
confusionMatrix Array.<Array.<number>>

a confusion matrix

Source:
Returns:

The accuracy

Type
number

(static) balancedAccuracy(confusionMatrix) → {number}

Calculate the balanced accuracy of a classifier given its confusion matrix as defined by the confusionMatrix method

Parameters:
Name Type Description
confusionMatrix Array.<Array.<number>>

a confusion matrix

Source:
Returns:

The balanced accuracy

Type
number

(static) bandpower(samples, sample_rate, bands, options) → {number|Array.<number>|Array.<Array.<number>>}

Calculate the bandpower of a signal or multiple signals in the specified frequency bands.

Uses a modified periodogram with a Hann window by default. (see: bci.periodogram()) Bandpower is calculated as the area under the PSD curve estimated using the rectangular method.

Units of bandpower are the square of the input signal's units. If the input signal has units of μV, then the bandpower estimate has units μV^2.

Returns absolute power by default. Relative band power (absolute power divided by total power in the signal) can be calculated by passing the option {relative: true}.

You can also pass custom PSD estimates instead of directly passing the signal. This may be useful if you wish to use your own PSD estimation method of choice, such as Welch's method. In this case, pass a single PSD array or pass multiple PSDs in the same form as multiple signals (columns are channels). Then be sure to pass the option {input: 'psd'}.

Example usages are provided below.

Parameters:
Name Type Description
samples Array.<number> | Array.<Array.<number>>

An array of samples, ex: [1,2,3,4, ...], or, in the case of multiple channels, ex (2 channels): [[1,2], [3,4], [5,6], ...]

sample_rate number

Sample rate

bands string | Array

The frequency band provided as an array [frequencyStart, frequencyStop] or a string 'delta' (1-3 Hz), 'theta' (4-7 Hz), 'alpha' (8-12 Hz), 'beta' (13-30 Hz), or 'gamma' (31-50 Hz).

options object
Properties
Name Type Attributes Default Description
fftSize number <optional>
Math.pow(2, bci.nextpow2(signal.length))

Size of the fft to be used. Should be a power of 2.

average boolean <optional>
false

Average powers across channels. Default is false.

input boolean <optional>
'samples'

Input type. Can be either 'samples' (default) or 'psd'. If you already have a PSD calculated, you can pass the estimates as an array with the input type 'psd'. You can also pass the entire PSD object if it was calculated using the bci.periodogram method, and the input type of 'psd' will be inferred.

relative boolean <optional>
false

Calculate relative bandpower instead of absolute bandpower. Default is false.

window number <optional>
'hann'

Window function to apply, either 'hann' or 'rectangular'. Default is 'hann'.

Source:
Returns:

Bandpower | array of bandpowers if an array of bands is passed as input for a single signal or multiple signals are passed with a single band | array of array of powers for each band if multiple signals are passed

Type
number | Array.<number> | Array.<Array.<number>>
Example
// Single signal example
let samples = [0.23, 0.14, 0.78, ...];
let sample_rate = 256; // Hz

bandpower(samples, sample_rate, 'alpha'); // returns power, ex: 1.652
bandpower(samples, sample_rate, ['alpha', 'beta']); // returns an array with the powers in the alpha and beta bands. Ex: [1.473, 0.383]

// 2 channel example
samples = [[0.1, 0.3], [0.4, 0.2], [0.6, 0.5], ...]

bandpower(samples, sample_rate, 'alpha'); // returns an array of alpha powers for each channel, ex: [1.342, 0.342]

bandpower(samples, sample_rate, ['alpha', 'beta']);
// returns an array of arrays of powers in each band, ex: [[1.342, 0.342], [0.245, 1.343]].
// The first array is an array of alpha powers for channels 1 and 2
// The second array is an array of beta powers for channels 1 and 2

bandpower(samples, sample_rate, ['alpha', 'beta'], {average: true});
// Calculate average alpha across all channels and average beta across all channels
// Returns a value such as [0.842, 0.794]
// Note these are the average of [1.342, 0.342] and the average of [0.245, 1.343] from the previous example

(static) confusionMatrix(predictedClasses, actualClasses) → {Array.<Array.<number>>}

Generate a confusion matrix C where rows are actual classes and columns are predicted classes. C = [ [true negative, false positive], [false negative, true positive] ].

If two classes are passed, class 0 represents the negative case, and class 1 represents the positive case. If more than two classes are passed, an NxN confusion matrix is returned where N is the number of classes.

Parameters:
Name Type Description
predictedClasses Array.<number>

An array of predicted classes, with class numbers starting at 0

actualClasses Array.<number>

An array of the actual classes, with class numbers starting at 0

Source:
Returns:

The confusion matrix

Type
Array.<Array.<number>>

(static) cspLearn(class1, class2) → {Object}

Learn common spatial pattern (CSP) for two datasets. Check out https://bci.js.org/examples/csp/ for an interactive example of how CSP works.

Parameters:
Name Type Description
class1 Array.<Array.<number>>

Data samples for class 1. Rows should be samples, columns should be signals.

class2 Array.<Array.<number>>

Data samples for class 2. Rows should be samples, columns should be signals.

Source:
Returns:

Learned CSP parameters

Type
Object
Example
let cspParams = bci.cspLearn(class_a, class_b);

(static) cspProject(cspParams, data, dimensionsopt) → {Array.<Array.<number>>}

Projects data using common spatial pattern (CSP) and reduces to given number of dimensions. Check out https://bci.js.org/examples/csp/ for an interactive example of how CSP works.

Parameters:
Name Type Attributes Description
cspParams object

CSP parameters computed using the cspLearn function

data Array.<Array.<number>>

Data points to be projected. Rows should be samples, columns should be signals.

dimensions number <optional>

Number of dimensions to be returned. Can range from 1 to number of signals. Defaults to number of signals.

Source:
Returns:

Projected data. Rows are samples, columns are dimensions sorted by descending importance.

Type
Array.<Array.<number>>
Example
// Learn the CSP params
let cspParams = bci.cspLearn(class_a, class_b);

// Project the signals
let class_a_csp = bci.cspProject(cspParams, class_a);
let class_b_csp = bci.cspProject(cspParams, class_b);

(static) f1(confusionMatrix) → {number}

Calculate the f1 score of a binary classifier given its confusion matrix as defined by the confusionMatrix method

Parameters:
Name Type Description
confusionMatrix Array.<Array.<number>>

a 2x2 confusion matrix

Source:
Returns:

The f1 score

Type
number

(static) fastICA(signals, options) → {Object}

FastICA algorithm for independent component analysis

Parameters:
Name Type Description
signals Array.<Array.<number>>

The mixed signals. Each row should be a signal and each column a sample.

options Object
Properties
Name Type Attributes Default Description
maxIterations number <optional>
1000

Maximum number of iterations

debug boolean <optional>
false

If true, prints out debug information while running

fun string <optional>
logcosh

The functional form of the G function used in the approximation of negentropy. Can be either 'exp' or 'logcosh.

Source:
Returns:

An object with the following values: {source: the estimated source matrix, weights: the estimated unmixing matrix, whitening: the computed whitening matrix, iterations: number of iterations taken to converge on each weight}

Type
Object

(static) generateSignal(amplitudes, frequencies, sampleRate, duration) → {Array.<number>}

Generate a signal with the given frequencies and their amplitudes.

Parameters:
Name Type Description
amplitudes Array.<number>

The amplitudes of each frequency.

frequencies Array.<number>

The frequencies.

sampleRate number

Sample rate of the signal in Hz.

duration number

Duration of the signal in seconds.

Source:
Returns:

The generated signal.

Type
Array.<number>
Example
let amplitudes = [4, 8];
let frequencies = [10, 20]; // 10 Hz (alpha), 20 Hz (beta)
let sampleRate = 512; // Hz
let duration = 1; // Seconds

let signal = bci.generateSignal(amplitudes, frequencies, sampleRate, duration);

(static) ldaClassify(ldaParams, point) → {number}

Classify an unknown data point.

Parameters:
Name Type Description
ldaParams object

The parameters for the LDA, computed with the function ldaLearn

point Array.<number> | Array.<Array.<number>>

The data point or array of points to be classified.

Source:
Returns:

0 if the first class, 1 if the second class

Type
number
Example
let features = [[1,3], [5,2]]; // Example feature vectors
let classification = bci.ldaClassify(ldaParams, features[0]); // Outputs a number (0 or 1 depending on class)
let classifications = bci.ldaClassify(ldaParams, features); // Outputs an array of classifications

(static) ldaLearn(class1, class2) → {Object}

Perform linear discriminant analysis between two datasets

Parameters:
Name Type Description
class1 Array.<Array.<number>>

Data set for class 1, rows are samples, columns are variables

class2 Array.<Array.<number>>

Data set for class 2, rows are samples, columns are variables

Source:
Returns:

Computed LDA parameters

Type
Object
Example
// Training set
let class1 = [[0, 0], [1, 2], [2, 2], [1.5, 0.5]];
let class2 = [[8, 8], [9, 10], [7, 8], [9, 9]];

// Learn an LDA classifier
let ldaParams = bci.ldaLearn(class1, class2);

(static) ldaProject(ldaParams, point) → {number}

Predict the class of an unknown data point.

Parameters:
Name Type Description
ldaParams object

The parameters for the LDA, computed with the function ldaLearn

point Array.<number> | Array.<Array.<number>>

The data point or array of points to be projected.

Source:
Returns:

value less than 0 if predicted to be in class 1, 0 if exactly inbetween, greater than 0 if class 2

Type
number

(static) loadCSV(filePath) → {Promise}

Loads a CSV file into an array

This method is exclusive to Node.js

Parameters:
Name Type Description
filePath string

The path to the CSV file

Source:
Returns:

A promise object which resolves to the CSV data array

Type
Promise

(static) loadEDF(filename) → {Object}

Load data from an EDF file

This method is exclusive to Node.js

Parameters:
Name Type Description
filename string

Path to the EDF file

Source:
Returns:

An object with the following parameters:

subject [string] - The name of the subject
recording [string] - The name of the recording
start_time [string] - The start time as a date time string
channels [Array] - An array of channel objects

A channel object has the following parameters:

label [string] - The label for the channel
sample_rate [number] - The sample rate for the channel
physical_dimension [string] - The units for each channel (ex: uV)
samples [number[]] - An array of samples from the channel

Type
Object

(static) mcc(confusionMatrix) → {number}

Calculate the Matthews correlation coefficient (MCC) of a binary classifier given its confusion matrix as defined by the confusionMatrix method

Parameters:
Name Type Description
confusionMatrix Array.<Array.<number>>

a 2x2 confusion matrix

Source:
Returns:

The Matthews correlation coefficient

Type
number

(static) nextpow2(num) → {number}

Returns the ceil of the log2 of the absolute value of the passed number

Parameters:
Name Type Description
num number
Source:
Returns:

The ceil of the log2 of the absolute value of the passed number

Type
number
Example
nextpow2(8); // 3
nextpow2(9); // 4
nextpow2(16); // 4
nextpow2(30); // 5
nextpow2(0); // -Infinity

(static) oscCollect(address, port, header, samples) → {Promise}

Collect a set number of samples over OSC

This method is exclusive to Node.js

Parameters:
Name Type Description
address string

OSC address

port number

OSC port

header string

OSC header, can be found by scanning with oscHeaderScan if unknown

samples number

The number of samples to collect

Source:
Returns:

Resolves with collected data

Type
Promise

(static) oscHeaderScan(address, port, duration) → {Promise}

Scan for OSC headers on a port and address

This method is exclusive to Node.js

Parameters:
Name Type Description
address any

OSC address

port any

OSC port

duration any

Duration of scan in milliseconds

Source:
Returns:

Resolves with an array of found headers

Type
Promise

(static) partition(array, …divisions) → {Array.<Array>}

Partitions an array into multiple arrays Can be used to split data into training and testing sets

Parameters:
Name Type Attributes Description
array Array

The array to be partitioned

divisions Array.<number> <repeatable>

The size of each partition, each value should range from 0 to 1

Source:
Returns:

Array of subarrays which are the partitons

Type
Array.<Array>
Example
partition([1, 2, 3, 4], 0.25, 0.75); // returns [[1], [2, 3, 4]]

(static) periodogram(signal, sample_rate, optionsopt) → {Object}

Estimates the power spectral density of a real-valued input signal using the periodogram method and a rectangular window. Output units are based on that of the input signal, of the form X^2/Hz, where X is the units of the input signal. For example, if the input is an EEG signal measured in μV, then this method returns values of μV^2/Hz.

Parameters:
Name Type Attributes Description
signal Array.<number>

The signal.

sample_rate number

sample rate in Hz

options Object <optional>
Properties
Name Type Attributes Default Description
fftSize number <optional>
Math.pow(2, bci.nextpow2(signal.length))

Size of the fft to be used. Should be a power of 2.

window string | Array.<number> <optional>
'rectangular'

Window function to apply, either 'hann', 'rectangular', or an array for a custom window. Default is 'rectangular'.

Source:
Returns:

Object with keys 'estimates' (the psd estimates) and 'frequencies' (the corresponding frequencies in Hz)

Type
Object

(static) precision(confusionMatrix) → {number}

Calculate the precision of a binary classifier given its confusion matrix as defined by the confusionMatrix method

Parameters:
Name Type Description
confusionMatrix Array.<Array.<number>>

a 2x2 confusion matrix

Source:
Returns:

The precision (positive predictive value)

Type
number

(static) prompt(question) → {Promise}

Prompts the user for input via stdin

This method is exclusive to Node.js

Parameters:
Name Type Description
question string

Question shown to user

Source:
Returns:

A promise object that resolves with the response

Type
Promise

(static) recall(confusionMatrix) → {number}

Calculate the recall of a binary classifier given its confusion matrix as defined by the confusionMatrix method

Parameters:
Name Type Description
confusionMatrix Array.<Array.<number>>

a 2x2 confusion matrix

Source:
Returns:

The recall (true positive rate)

Type
number

(static) round(array, places) → {Array.<number>}

Rounds every value in an array to a set number of decimal places

Parameters:
Name Type Description
array Array.<number>
places number
Source:
Returns:

The rounded array

Type
Array.<number>

(static) saveCSV(array, filename) → {Promise}

Saves an array to a CSV file

This method is exclusive to Node.js

Parameters:
Name Type Description
array Array
filename string
Source:
Returns:

A promise object that resolves when the file has been saved. Does not currently reject on write error.

Type
Promise

(static) specificity(confusionMatrix) → {number}

Calculate the specificity of a binary classifier given its confusion matrix as defined by the confusionMatrix method

Parameters:
Name Type Description
confusionMatrix Array.<Array.<number>>

a 2x2 confusion matrix

Source:
Returns:

The specificity (true negative rate)

Type
number

(static) subscript(array, …params) → {Array}

Subscript an array with MATLAB-like syntax

Parameters:
Name Type Attributes Description
array Array

The array to be subscripted

params string <repeatable>

Colon notation for which elements to include in each dimension

Source:
Returns:

The subscripted array

Type
Array
Examples
var bci = require('bcijs');
var arr = [3, 2, 4, 1, 5];
var subarr = bci.subscript(arr, '1:3');
console.log(subarr); // [3, 2, 4]
var bci = require('bcijs');
var arr = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];
var subarr = bci.subscript(arr, '1 3', '2:3'); // rows 1 and 3, columns 2 through 3
console.log(subarr); // [[2, 3], [8, 9]]

(static) toFixed(array, places) → {Array.<string>}

Returns an array of numbers as strings rounded to the proper number of decimal places and padded with zeros as needed.

Parameters:
Name Type Description
array Array
places number
Source:
Returns:

Array of string representations of numbers

Type
Array.<string>

(static) toTable(array) → {string}

Returns an ASCII table representation of an array

Parameters:
Name Type Description
array Array
Source:
Returns:

ASCII table

Type
string

(static) transpose(array) → {Array}

Transpose an array

Parameters:
Name Type Description
array Array

The array to transpose

Source:
Returns:

The transposed array

Type
Array

(static) wait(ms) → {Promise}

Parameters:
Name Type Description
ms number

Number of milliseconds to wait

Source:
Returns:

A promise which resolves when the timeout occurs

Type
Promise

(static) welch(signal, sample_rate, options) → {object}

Welch's method
Computes overlapping modified periodograms and averages them together

Parameters:
Name Type Description
signal Array.<number>

The input signal

sample_rate number

The sample rate

options object
Properties
Name Type Attributes Default Description
segmentLength number <optional>
256

How long each segment should be in samples

overlapLength number <optional>
null

Amount of overlap between segments in samples. Defaults to floor(segmentLength / 2).

window string | Array.<number> <optional>
'hann'

Window function to apply, either 'hann', 'rectangular', or an array for a custom window. Default is 'hann'.

fftSize number <optional>
Math.pow(2, bci.nextpow2(signal.length))

Size of the fft to be used. Should be a power of 2.

Source:
Returns:

PSD object with keys {estimates: PSD estimates in units of X^2/Hz, frequencies: corresponding frequencies in Hz}

Type
object

(static) windowApply(array, func, length, step, tail) → {Array}

Similar to JavaScript's map, but it applies a function to sub arrays instead of each element. Each sub array, or window, starts at index 0 and has length 'length' Each next window will be shifted 'step' elements from the first. The result of each function is stored in a returned array.

Parameters:
Name Type Description
array Array

The array of elements which will be windowed

func function

The function to call on each window, the returned result is stored in a returned array

length number

The number of elements to include in each window

step number

The start of the window is incremented by this amount every iteration

tail boolean

If false, windows which begin near the end of the array which cannot reach length 'length' will be ignored

Source:
Returns:

An array containing the function result for each window

Type
Array
Examples
var bci = require('bcijs');
bci.windowApply([1, 2, 3, 4, 5], window => console.log(window), 3, 1);
// [1, 2, 3]
// [2, 3, 4]
// [3, 4, 5] 
var bci = require('bcijs');
var sums = bci.windowApply([1, 2, 3, 4, 5], window => {
  var sum = 0;
  window.forEach(x => sum += x);
  return sum;
}, 3, 1);
console.log(sums);
// [6, 9, 12]