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
21 changes: 20 additions & 1 deletion .github/workflows/run_unix.yml
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,26 @@ jobs:
if: (matrix.os == 'ubuntu-latest')
run: |
docker pull dockcross/manylinux_2_28-x64:20240418-88c04a4
docker run -e BRAINFLOW_VERSION=$BRAINFLOW_VERSION -e GITHUB_WORKSPACE=$GITHUB_WORKSPACE -v $GITHUB_WORKSPACE:$GITHUB_WORKSPACE dockcross/manylinux_2_28-x64:20240418-88c04a4 /bin/bash -c "yum install -y bluez-libs-devel dbus-devel && /opt/python/cp36-cp36m/bin/pip3.6 install cmake==3.21.4 && cd $GITHUB_WORKSPACE && mkdir build_docker && cd build_docker && /opt/_internal/cpython-3.6.15/bin/cmake -DBRAINFLOW_VERSION=$BRAINFLOW_VERSION -DBUILD_ONNX=ON -DBUILD_BLE=ON -DBUILD_BLUETOOTH=ON -DCMAKE_INSTALL_PREFIX=$GITHUB_WORKSPACE/installed_docker -DCMAKE_BUILD_TYPE=Release .. && make && make install"
docker run -e BRAINFLOW_VERSION -e GITHUB_WORKSPACE -v "$GITHUB_WORKSPACE:$GITHUB_WORKSPACE" dockcross/manylinux_2_28-x64:20240418-88c04a4 /bin/bash -e -c '
# A mirror can return empty repomd.xml; discard cached metadata before retrying.
for attempt in 1 2 3; do
if yum install -y bluez-libs-devel dbus-devel; then
break
fi
if [ "$attempt" -eq 3 ]; then
exit 1
fi
yum clean metadata
sleep 5
done
/opt/python/cp36-cp36m/bin/pip3.6 install cmake==3.21.4
cd "$GITHUB_WORKSPACE"
mkdir build_docker
cd build_docker
/opt/_internal/cpython-3.6.15/bin/cmake -DBRAINFLOW_VERSION="$BRAINFLOW_VERSION" -DBUILD_ONNX=ON -DBUILD_BLE=ON -DBUILD_BLUETOOTH=ON -DCMAKE_INSTALL_PREFIX="$GITHUB_WORKSPACE/installed_docker" -DCMAKE_BUILD_TYPE=Release ..
make
make install
'
env:
BRAINFLOW_VERSION: ${{ steps.version.outputs.version }}
- name: C# build
Expand Down
48 changes: 37 additions & 11 deletions csharp_package/brainflow/brainflow/data_filter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -694,6 +694,40 @@ public static int get_nearest_power_of_two (int value)
return output[0];
}

private static unsafe double[] pack_channels (double[,] data, int[] channels)
{
if (data == null || channels == null || channels.Length == 0)
throw new BrainFlowError ((int)BrainFlowExitCodes.INVALID_ARGUMENTS_ERROR);

int cols = data.GetLength (1);
long packed_length = (long)channels.Length * cols;
if (cols == 0 || data.GetLowerBound (1) != 0 || packed_length > int.MaxValue)
throw new BrainFlowError ((int)BrainFlowExitCodes.INVALID_ARGUMENTS_ERROR);

int rows = data.GetLength (0);
int first_row = data.GetLowerBound (0);
int last_row = data.GetUpperBound (0);
long row_bytes = (long)cols * sizeof (double);
double[] packed = new double[(int)packed_length];
fixed (double* destination = packed)
{
for (int i = 0; i < channels.Length; i++)
{
int row = channels[i];
// Preserve GetRow's indexing from the end of the array.
if (row < 0)
row += rows;
if (row < first_row || row > last_row)
throw new BrainFlowError ((int)BrainFlowExitCodes.INVALID_ARGUMENTS_ERROR);
fixed (double* source = &data[row, 0])
{
Buffer.MemoryCopy (source, destination + i * cols, row_bytes, row_bytes);
}
}
}
return packed;
}

/// <summary>
/// Calculate normalized mean band powers and coefficients of variation across channels.
/// Filtering removes DC and applies padded, initialized zero-phase 48-52 and 58-62 Hz
Expand All @@ -718,11 +752,7 @@ public static int get_nearest_power_of_two (int value)
/// <returns>Normalized mean band powers and coefficients of variation</returns>
public static Tuple<double[], double[]> get_custom_band_powers (double[,] data, Tuple<double, double>[] bands, int[] channels, int sampling_rate, bool apply_filters)
{
double[] data_1d = new double[data.GetRow (0).Length * channels.Length];
for (int i = 0; i < channels.Length; i++)
{
Array.Copy (data.GetRow (channels[i]), 0, data_1d, i * data.GetRow (channels[i]).Length, data.GetRow (channels[i]).Length);
}
double[] data_1d = pack_channels (data, channels);
double[] avgs = new double[bands.Length];
double[] stddevs = new double[bands.Length];
double[] start_freqs = new double[bands.Length];
Expand All @@ -733,7 +763,7 @@ public static Tuple<double[], double[]> get_custom_band_powers (double[,] data,
stop_freqs[i] = bands[i].Item2;
}

int res = DataHandlerLibrary.get_custom_band_powers (data_1d, channels.Length, data.GetRow (0).Length, start_freqs, stop_freqs, bands.Length, sampling_rate, (apply_filters) ? 1 : 0, avgs, stddevs);
int res = DataHandlerLibrary.get_custom_band_powers (data_1d, channels.Length, data.GetLength (1), start_freqs, stop_freqs, bands.Length, sampling_rate, (apply_filters) ? 1 : 0, avgs, stddevs);
if (res != (int)BrainFlowExitCodes.STATUS_OK)
{
throw new BrainFlowError (res);
Expand Down Expand Up @@ -777,11 +807,7 @@ public static Tuple<double[,], double[,], double[,], double[,]> perform_ica (dou
throw new BrainFlowError((int)BrainFlowExitCodes.INVALID_ARGUMENTS_ERROR);
}
int cols = data.GetLength (1);
double[] data_1d = new double[cols * channels.Length];
for (int i = 0; i < channels.Length; i++)
{
Array.Copy (data.GetRow (channels[i]), 0, data_1d, i * data.GetRow (channels[i]).Length, data.GetRow (channels[i]).Length);
}
double[] data_1d = pack_channels (data, channels);
int channels_len = channels.Length;
double[] w = new double[num_components * num_components];
double[] k = new double[channels_len * num_components];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,34 @@ static void CheckMLSnapshot(string modelPath)
Console.WriteLine("ML capacity snapshot validation passed.");
}

static void CheckChannelPacking()
{
var data = new double[4, 1024];
for (int row = 0; row < 4; row++)
for (int col = 0; col < 1024; col++)
data[row, col] = Math.Sin(2 * Math.PI * (5 + row * 7.0) * col / 256.0);
var original = (double[,])data.Clone();
int[] rows = {3, 1, 3};
var selected = new double[rows.Length, 1024];
for (int row = 0; row < rows.Length; row++)
for (int col = 0; col < 1024; col++)
selected[row, col] = data[rows[row], col];
var bands = new[] {Tuple.Create(2.0, 15.0), Tuple.Create(15.0, 40.0)};
var actual = DataFilter.get_custom_band_powers(data, bands, new[] {3, 1, -1}, 256, false);
var expected = DataFilter.get_custom_band_powers(selected, bands, new[] {0, 1, 2}, 256, false);
for (int band = 0; band < bands.Length; band++)
if (!(Math.Abs(actual.Item1[band] - expected.Item1[band]) <= 1e-12 &&
Math.Abs(actual.Item2[band] - expected.Item2[band]) <= 1e-12))
throw new Exception("Selected/repeated channel powers changed");
for (int row = 0; row < 4; row++)
for (int col = 0; col < 1024; col++)
if (BitConverter.DoubleToInt64Bits(data[row, col]) != BitConverter.DoubleToInt64Bits(original[row, col]))
throw new Exception("Channel packing modified input");
Reject(() => DataFilter.get_custom_band_powers(data, bands, new[] {-5}, 256, false));
Reject(() => DataFilter.get_custom_band_powers(data, bands, new[] {4}, 256, false));
Reject(() => DataFilter.perform_ica(data, 2, new[] {0, 4}));
}

static void CheckSignalQuality()
{
const int samples = 1024;
Expand Down Expand Up @@ -68,6 +96,7 @@ static void CheckSignalQuality()

static void Main(string[] args)
{
CheckChannelPacking();
CheckSignalQuality();
var batch = new double[8, 2048];
for (int row = 0; row < 8; row++)
Expand Down
28 changes: 17 additions & 11 deletions python_package/brainflow/data_filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -1423,15 +1423,15 @@ def perform_fft(cls, data, window: int):

check_memory_layout_row_major(data, 1)

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)
temp_re = numpy.empty(data.shape[0] // 2 + 1, dtype=numpy.float64)
temp_im = numpy.empty(data.shape[0] // 2 + 1, dtype=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]))
output = numpy.empty(temp_re.shape[0], dtype=numpy.complex128)
output.real = temp_re
output.imag = temp_im

return output

Expand Down Expand Up @@ -1798,12 +1798,18 @@ def perform_ifft(cls, data):
:return: restored data
:rtype: NDArray[Shape["*"], Float64]
"""
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)
if len(data.shape) != 1:
raise BrainFlowError('unable to perform ifft', BrainFlowExitCodes.INVALID_ARGUMENTS_ERROR.value)

bins = data.shape[0]
if isinstance(data, numpy.ndarray) and not data.dtype.hasobject and not numpy.ma.is_masked(data):
temp_re = numpy.require(data.real, dtype=numpy.float64, requirements=('C', 'A'))
temp_im = numpy.require(data.imag, dtype=numpy.float64, requirements=('C', 'A'))
else:
# Object arrays and other array-like inputs expose complex parts on each element.
temp_re = numpy.fromiter((data[i].real for i in range(bins)), dtype=numpy.float64, count=bins)
temp_im = numpy.fromiter((data[i].imag for i in range(bins)), dtype=numpy.float64, count=bins)
output = numpy.empty(2 * (bins - 1), dtype=numpy.float64)

res = DataHandlerDLL.get_instance().perform_ifft(temp_re, temp_im, output.shape[0], output)
if res != BrainFlowExitCodes.STATUS_OK.value:
Expand Down
17 changes: 17 additions & 0 deletions python_package/examples/tests/signal_processing_regression.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,23 @@ def test_fft_and_ifft_match_numpy_and_preserve_input(self):
np.testing.assert_allclose(DataFilter.perform_ifft(actual), data * weights, atol=1e-12)
np.testing.assert_array_equal(data, original)

def test_ifft_accepts_strided_complex_input_without_modifying_it(self):
signal_data = np.random.default_rng(31).normal(size=256)
spectrum = np.fft.rfft(signal_data)
storage = np.zeros(spectrum.size * 2, dtype=np.complex128)
storage[::2] = spectrum
before = storage.copy()
np.testing.assert_allclose(DataFilter.perform_ifft(storage[::2]), signal_data, atol=1e-12)
np.testing.assert_array_equal(storage, before)

def test_ifft_accepts_complex_values_in_object_arrays(self):
signal_data = np.random.default_rng(31).normal(size=256)
spectrum = np.fft.rfft(signal_data).astype(object)
np.testing.assert_allclose(DataFilter.perform_ifft(spectrum), signal_data, atol=1e-12)

def test_ifft_rejects_multidimensional_input(self):
self.assert_invalid(DataFilter.perform_ifft, np.empty((129, 0), dtype=np.complex128))

def test_spectral_nonfinite_inputs_are_rejected(self):
for value in (np.nan, np.inf, -np.inf):
data = np.ones(256)
Expand Down
Loading