Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion .github/workflows/run_unix.yml
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,13 @@ jobs:
env:
LD_LIBRARY_PATH: ${{ github.workspace }}/installed/lib
- name: Signal Processing Regression Csharp
run: dotnet run --project $GITHUB_WORKSPACE/csharp_package/brainflow/examples/signal_processing_regression
run: |
project=$GITHUB_WORKSPACE/csharp_package/brainflow/examples/signal_processing_regression
dotnet build "$project" --configuration Release
if [[ "$RUNNER_OS" == "macOS" ]]; then
cp "$GITHUB_WORKSPACE/installed/lib/"*.dylib "$project/bin/Release/net8.0/"
fi
dotnet run --project "$project" --configuration Release --no-build
env:
LD_LIBRARY_PATH: ${{ github.workspace }}/installed/lib
- name: Signal Processing Regression Rust
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ static void reject (const std::function<void ()> &action)
}

int main ()
try
{
BrainFlowArray<double, 2> data (2, 256);
reject ([&] { data.at (-1, 0); });
Expand Down Expand Up @@ -72,4 +73,10 @@ int main ()
reject (
[&] { DataFilter::perform_inverse_wavelet_transform (coefficients, lengths, 256, 3, 3); });
std::cout << "Signal-processing binding validation passed." << std::endl;
return 0;
}
catch (const std::exception &error)
{
std::cerr << "Signal-processing binding validation failed: " << error.what () << std::endl;
return 1;
}
78 changes: 78 additions & 0 deletions csharp_package/brainflow/brainflow/band_power_context.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
using System;

namespace brainflow
{
/// <summary>
/// Reusable band-power workspace. Bounds limit native scratch storage; workers=0 chooses up to
/// four persistent workers and workers=1 is serial. Dispose promptly to release workers.
/// Calls on one context serialize. Uses the existing windowed, zero-phase preprocessing.
/// </summary>
public sealed class BandPowerContext : IDisposable
{
private int handle;
private readonly int band_count;

public BandPowerContext (Tuple<double, double>[] bands, int sampling_rate,
int max_channels, int max_samples, bool apply_filters = true, int nfft = 0,
double low_cutoff = 0, double high_cutoff = 0, int mains = -1,
int? detrend_operation = null, int workers = 0)
{
if (bands == null || bands.Length == 0)
throw new BrainFlowError ((int)BrainFlowExitCodes.INVALID_ARGUMENTS_ERROR);
band_count = bands.Length;
double[] starts = new double[band_count], stops = new double[band_count];
for (int i = 0; i < band_count; i++)
{
if (bands[i] == null)
throw new BrainFlowError ((int)BrainFlowExitCodes.INVALID_ARGUMENTS_ERROR);
starts[i] = bands[i].Item1;
stops[i] = bands[i].Item2;
}
int[] created = new int[1];
Check (DataHandlerLibrary.create_band_power_context (max_channels, max_samples,
starts, stops, band_count, sampling_rate, apply_filters ? 1 : 0, nfft,
low_cutoff, high_cutoff, mains, detrend_operation ?? (apply_filters ? 1 : 0),
workers, created));
handle = created[0];
}

private static void Check (int result)
{
if (result != (int)BrainFlowExitCodes.STATUS_OK)
throw new BrainFlowError (result);
}

/// <summary>Process selected rows directly into reusable output arrays.</summary>
public void process (double[,] data, int[] channels, double[] averages, double[] deviations)
{
if (handle == 0 || data == null || channels == null || averages == null ||
deviations == null || averages.Length != band_count || deviations.Length != band_count ||
ReferenceEquals (averages, deviations))
throw new BrainFlowError ((int)BrainFlowExitCodes.INVALID_ARGUMENTS_ERROR);
Check (DataHandlerLibrary.process_band_power_context (handle, data, data.Length,
data.GetLength (0), data.GetLength (1), data.GetLength (1), channels,
channels.Length, averages, deviations, band_count));
}

public Tuple<double[], double[]> process (double[,] data, int[] channels)
{
double[] averages = new double[band_count], deviations = new double[band_count];
process (data, channels, averages, deviations);
return Tuple.Create (averages, deviations);
}

public void Dispose ()
{
int released = System.Threading.Interlocked.Exchange (ref handle, 0);
if (released != 0)
Check (DataHandlerLibrary.release_band_power_context (released));
GC.SuppressFinalize (this);
}

~BandPowerContext ()
{
try { Dispose (); }
catch { /* The native library may be unavailable during shutdown. */ }
}
}
}
48 changes: 48 additions & 0 deletions csharp_package/brainflow/brainflow/data_handler_library.cs
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,12 @@ class DataHandlerLibrary64
[DllImport ("DataHandler", SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
public static extern int read_file (double[] data, int[] num_rows, int[] num_cols, string file_name, int max_elements);
[DllImport ("DataHandler", SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
public static extern int create_band_power_context (int max_channels, int max_samples, double[] starts, double[] stops, int bands, int fs, int apply, int nfft, double low, double high, int mains, int detrend, int workers, int[] handle);
[DllImport ("DataHandler", SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
public static extern int process_band_power_context (int handle, double[,] data, int capacity, int rows, int samples, int stride, int[] channels, int count, double[] averages, double[] deviations, int output_capacity);
[DllImport ("DataHandler", SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
public static extern int release_band_power_context (int handle);
[DllImport ("DataHandler", SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
public static extern int get_num_elements_in_file (string file_name, int[] num_elements);
[DllImport ("DataHandler", SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
public static extern int perform_wavelet_transform (double[] data, int data_len, int wavelet, int decomposition_level, int extension, double[] output_data, int[] decomposition_lengths);
Expand Down Expand Up @@ -254,6 +260,12 @@ class DataHandlerLibrary32
[DllImport ("DataHandler32", SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
public static extern int read_file (double[] data, int[] num_rows, int[] num_cols, string file_name, int max_elements);
[DllImport ("DataHandler32", SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
public static extern int create_band_power_context (int max_channels, int max_samples, double[] starts, double[] stops, int bands, int fs, int apply, int nfft, double low, double high, int mains, int detrend, int workers, int[] handle);
[DllImport ("DataHandler32", SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
public static extern int process_band_power_context (int handle, double[,] data, int capacity, int rows, int samples, int stride, int[] channels, int count, double[] averages, double[] deviations, int output_capacity);
[DllImport ("DataHandler32", SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
public static extern int release_band_power_context (int handle);
[DllImport ("DataHandler32", SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
public static extern int get_num_elements_in_file (string file_name, int[] num_elements);
[DllImport ("DataHandler32", SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
public static extern int perform_wavelet_transform (double[] data, int data_len, int wavelet, int decomposition_level, int extension, double[] output_data, int[] decomposition_lengths);
Expand Down Expand Up @@ -528,6 +540,42 @@ public static int perform_downsampling (double[] data, int len, int period, int
return (int)BrainFlowExitCodes.GENERAL_ERROR;
}

public static int create_band_power_context (int max_channels, int max_samples, double[] starts, double[] stops, int bands, int fs, int apply, int nfft, double low, double high, int mains, int detrend, int workers, int[] handle)
{
switch (PlatformHelper.get_library_environment ())
{
case LibraryEnvironment.x64:
return DataHandlerLibrary64.create_band_power_context (max_channels, max_samples, starts, stops, bands, fs, apply, nfft, low, high, mains, detrend, workers, handle);
case LibraryEnvironment.x86:
return DataHandlerLibrary32.create_band_power_context (max_channels, max_samples, starts, stops, bands, fs, apply, nfft, low, high, mains, detrend, workers, handle);
}
return (int)BrainFlowExitCodes.GENERAL_ERROR;
}

public static int process_band_power_context (int handle, double[,] data, int capacity, int rows, int samples, int stride, int[] channels, int count, double[] averages, double[] deviations, int output_capacity)
{
switch (PlatformHelper.get_library_environment ())
{
case LibraryEnvironment.x64:
return DataHandlerLibrary64.process_band_power_context (handle, data, capacity, rows, samples, stride, channels, count, averages, deviations, output_capacity);
case LibraryEnvironment.x86:
return DataHandlerLibrary32.process_band_power_context (handle, data, capacity, rows, samples, stride, channels, count, averages, deviations, output_capacity);
}
return (int)BrainFlowExitCodes.GENERAL_ERROR;
}

public static int release_band_power_context (int handle)
{
switch (PlatformHelper.get_library_environment ())
{
case LibraryEnvironment.x64:
return DataHandlerLibrary64.release_band_power_context (handle);
case LibraryEnvironment.x86:
return DataHandlerLibrary32.release_band_power_context (handle);
}
return (int)BrainFlowExitCodes.GENERAL_ERROR;
}

public static int read_file (double[] data, int[] num_rows, int[] num_cols, string file_name, int max_elements)
{
switch (PlatformHelper.get_library_environment ())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,27 @@ static void CheckMLSnapshot(string modelPath)

static void Main(string[] args)
{
var batch = new double[8, 2048];
for (int row = 0; row < 8; row++)
for (int col = 0; col < 2048; col++)
batch[row, col] = Math.Sin((row + 1) * col * 0.1);
var bands = new[] {Tuple.Create(2.0, 13.0), Tuple.Create(13.0, 40.0)};
int[] channels = {7, 1, 2, 3, 4, 5, 6, 7};
var expected = DataFilter.get_custom_band_powers(batch, bands, channels, 250, true);
using (var context = new BandPowerContext(bands, 250, 8, 2048, workers: 4))
{
var averages = new double[2];
var variations = new double[2];
for (int repeat = 0; repeat < 5; repeat++)
{
context.process(batch, channels, averages, variations);
for (int band = 0; band < 2; band++)
if (Math.Abs(averages[band] - expected.Item1[band]) > 1e-12 ||
Math.Abs(variations[band] - expected.Item2[band]) > 1e-12)
throw new Exception("Context differs from band-power API");
}
Reject(() => context.process(batch, new[] {8}, averages, variations));
}
var data = new double[2, 256];
Reject(() => DataFilter.perform_fft(data, 1, 0, 512, 0));
Reject(() => DataFilter.get_psd(data, 1, 0, 512, 256, 0));
Expand Down
39 changes: 39 additions & 0 deletions docs/UserAPI.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,45 @@ This abstraction allows you to switch boards without any changes in code.

In BoardShim, all board data is returned as a 2d array. Rows in this array may contain timestamps, EEG and EMG data and so on. To see instructions how to query specific kind of data check :ref:`data-format-label` and :ref:`code-samples-label`.

Reusable band-power workspaces
------------------------------

Python and C# provide ``BandPowerContext`` for repeatedly processing windows with
fixed band/filter settings. The native C API exposes ``create_band_power_context``,
``process_band_power_context`` and ``release_band_power_context``. Existing APIs
remain available and use the same spectral and preprocessing definitions.

A context retains filter coefficients, FFT plans, windows and scratch arrays.
``max_channels`` bounds the number of selected channels; ``max_samples`` bounds
samples per input row. Select rows directly from a channel-major matrix without
packing them first. Native callers supply row stride and input/output capacities
in elements. Outputs must be disjoint from input and each other. Calls on one
context serialize; independent contexts can run concurrently.

``workers=0`` chooses up to four persistent native threads; ``workers=1`` is
serial. Batches below eight channels run serially; contexts whose ``max_channels``
is below eight allocate one workspace and no worker threads. No OpenMP runtime is required.
Close/dispose the context promptly; Python context managers and C# ``using`` are
recommended. This remains windowed zero-phase processing, not causal streaming.

.. code-block:: python

from brainflow.data_filter import BandPowerContext
import numpy as np

bands = [(2.0, 8.0), (8.0, 13.0), (13.0, 30.0)]
output = (np.empty(len(bands)), np.empty(len(bands)))
with BandPowerContext(bands, 250, max_channels=16, max_samples=2000) as context:
# data is a contiguous float64 matrix; eeg_channels selects source rows.
averages, variations = context.process(data, eeg_channels, out=output)

Each call may use fewer channels/samples within the configured bounds, provided
it still satisfies the FFT and filter-settling minimum. Failed calls leave outputs
unchanged. The context allocates bounded scratch memory at creation, so choose
bounds for the actual workload rather than the entire recording length.
Closing a context removes its handle. A call that has already acquired the native
context can finish; a call racing with close before acquisition may report an invalid handle.

Band power preprocessing and data length
----------------------------------------

Expand Down
Loading
Loading