From 33c567cbffd51a53f0f1e1400ae6c1b4abb1cc9e Mon Sep 17 00:00:00 2001 From: Ryan Harvey Date: Thu, 19 Nov 2026 14:59:28 +0100 Subject: [PATCH 1/4] Cap auto-selected EMGFromLFP channels when there are many spike groups getEMGFromLFP picks one channel per spike group and correlates every channel pair, so the work grows with the square of the number of spike groups. A layout with 42 spike groups gives 42 channels and 861 pairs, compared with 6-28 pairs for 4-8 groups. - New 'maxAutoChannels' option (default 16). With more usable spike groups than that, use that many groups spread evenly over the spike-group list. Recordings with <= 16 usable groups take the unchanged selection path and consume the RNG identically, so they get the same channels. specialChannels are still added on top; inf disables the cap. - Replace the per-bin corr() loop with blocked, vectorised Pearson correlations (same formula, NaN for flat windows). Values match the former loop to rounding error (<1e-12 in the regression tests). - Record the selection in EMGFromLFP.detectorinfo. - Call loadBinary with its actual case so the function runs on Linux. - Tests compare layouts with few spike groups against a frozen copy of the former implementation and check the cap on a 42-group layout. --- lfp/getEMGFromLFP.m | 98 +++++++++++++++------- test/test_getEMGFromLFP.m | 168 +++++++++++++++++++++++++++++++++++++- 2 files changed, 234 insertions(+), 32 deletions(-) diff --git a/lfp/getEMGFromLFP.m b/lfp/getEMGFromLFP.m index 9dd20b4..facbfc7 100644 --- a/lfp/getEMGFromLFP.m +++ b/lfp/getEMGFromLFP.m @@ -34,6 +34,16 @@ % 'samplingFrequency' - desired sampling rate for EMG output. default:2 % 'noPrompts' (default: false) prevents prompts about saving/adding metadata % 'fromDat' -uses the .dat file instead of .lfp (default:false) +% 'maxAutoChannels' - maximum number of spike groups sampled when +% channels are picked automatically (one channel +% per group). Recordings with more usable spike +% groups use this many groups spread evenly +% across the spike-group list, because the cost +% grows with the number of channel pairs. +% Recordings with at most this many usable +% groups are unaffected. +% specialChannels are always added on top. +% Use inf to disable the cap. default: 16 % % % OUTPUTS @@ -45,6 +55,8 @@ % .channels - channel #'s used for analysis % .detectorName - string name of function used % .samplingFrequency - 1 / sampling rate of EMGCorr data +% .detectorinfo - how channels were selected (method, +% maxAutoChannels, spike groups used, ...) % % ========================================================================= @@ -68,6 +80,7 @@ addParameter(p, 'noPrompts', false, @islogical); addParameter(p, 'fromDat', false, @islogical); addParameter(p, 'chInfo', [], @isstruct); +addParameter(p, 'maxAutoChannels', 16, @(x) isnumeric(x) && isscalar(x) && x >= 2); parse(p, varargin{:}) restrict = p.Results.restrict; @@ -80,6 +93,7 @@ noPrompts = p.Results.noPrompts; fromDat = p.Results.fromDat; chInfo = p.Results.chInfo; +maxAutoChannels = p.Results.maxAutoChannels; if ~isempty(p.Results.saveLocation) matfilename = fullfile(p.Results.saveLocation, [recordingname, '.EMGFromLFP.LFP.mat']); @@ -120,7 +134,6 @@ binScootS = 1 ./ samplingFrequency; binScootSamps = round(Fs*binScootS); % must be integer, or error on line 190 -corrChunkSz = 20; %for batch-processed correlations %% Pick channels and to analyze % get spike groups, @@ -132,8 +145,11 @@ % xcorrs_chs is a list of channels that will be loaded % spkgrpstouse is a list of spike groups to find channels from +nUsableSpikeGroups = NaN; +spkgrpsused = []; if ~isempty(restrictChannels) % If restrict channel case: xcorr_chs = restrictChannels; + selectionMethod = 'restrictChannels'; else % get list of spike groups (aka shanks) that should be used usablechannels = []; @@ -149,6 +165,24 @@ % okay, lets limit usableshankchannels with spkgrpstouse. Thus, empty shanks will be excluded. usableshankchannels = usableshankchannels(spkgrpstouse); + nUsableSpikeGroups = length(spkgrpstouse); + + % The number of channel pairs, and with it the run time, grows + % quadratically with the number of spike groups. Keep at most + % maxAutoChannels groups, spread evenly over the spike-group list. + % Recordings with <= maxAutoChannels usable groups take the unchanged + % path below. + if nUsableSpikeGroups > maxAutoChannels + keepgroups = unique(round(linspace(1, nUsableSpikeGroups, floor(maxAutoChannels)))); + usableshankchannels = usableshankchannels(keepgroups); + spkgrpstouse = spkgrpstouse(keepgroups); + selectionMethod = 'onePerSpikeGroupCapped'; + elseif length(usableshankchannels) > 1 + selectionMethod = 'onePerSpikeGroup'; + else + selectionMethod = 'fiveFromSingleSpikeGroup'; + end + spkgrpsused = spkgrpstouse; % get number of channels per shank. If one valid shank, choose 5 channels if length(usableshankchannels) > 1 @@ -185,7 +219,7 @@ switch fromDat case false - lfp = LoadBinary(lfpFile, 'nChannels', nChannels, 'channels', xcorr_chs, ... + lfp = loadBinary(lfpFile, 'nChannels', nChannels, 'channels', xcorr_chs, ... 'start', restrict(1), 'duration', diff(restrict), 'frequency', Fs); %read and convert to mV if isempty(lfp) @@ -193,7 +227,7 @@ end case true - lfp = LoadBinary(datFile, 'nChannels', nChannels, 'channels', xcorr_chs, ... + lfp = loadBinary(datFile, 'nChannels', nChannels, 'channels', xcorr_chs, ... 'start', restrict(1), 'duration', diff(restrict), 'frequency', datFs, ... 'downsample', datFs./Fs); %read and convert to mV if isempty(lfp) @@ -214,40 +248,35 @@ xcorr_window_samps = round(binScootS*Fs); xcorr_window_inds = -xcorr_window_samps:xcorr_window_samps; %+- that number of ms in samples -% new version... batches of correlation calculated at once +% Pearson correlation of every channel pair in each window, summed over +% pairs. Windows are processed in blocks of bins: each channel's windows are +% centered and scaled once per block, so a pair costs one elementwise +% product instead of a per-bin corr() call. Same formula as corr (NaN for a +% flat window), results agree with the former per-bin loop to rounding error. timestamps = (1 + xcorr_window_inds(end)):binScootSamps:(size(lfp, 1) - xcorr_window_inds(end)); numbins = length(timestamps); EMGCorr = zeros(numbins, 1); -% tic -counter = 1; -for j = 1:(length(xcorr_chs)) - for k = (j + 1):length(xcorr_chs) - %disp([num2str(counter*2 ./ (length(xcorr_chs)*length(xcorr_chs)*length(timestamps)))]) - bz_Counter(counter, (length(xcorr_chs) * (length(xcorr_chs) - 1))./2, 'Channel Pair') - c1 = []; - c2 = []; - binind = 0; - binindstart = 1; - for i = timestamps - binind = binind + 1; - s1 = lfp(i + xcorr_window_inds, j); - s2 = lfp(i + xcorr_window_inds, k); - c1 = cat(2, c1, s1); - c2 = cat(2, c2, s2); - if size(c1, 2) == corrChunkSz || i == timestamps(end) - binindend = binind; - tmp = corr(c1, c2); - tmp = diag(tmp); - EMGCorr(binindstart:binindend) = EMGCorr(binindstart:binindend) + tmp; - c1 = []; - c2 = []; - binindstart = binind + 1; - end +nCh = length(xcorr_chs); +nPairs = nCh * (nCh - 1) / 2; +nWin = length(xcorr_window_inds); +% bins per block, keeping the block of windowed data near 256 MB +binsPerBlock = max(1, floor(256e6/(8 * nWin * max(nCh, 1)))); +for binindstart = 1:binsPerBlock:numbins + binindend = min(numbins, binindstart+binsPerBlock-1); + nb = binindend - binindstart + 1; + sampleinds = xcorr_window_inds(:) + timestamps(binindstart:binindend); + z = reshape(double(lfp(sampleinds(:), :)), nWin, nb, nCh); + z = z - sum(z, 1) / nWin; + z = z ./ sqrt(sum(z.^2, 1)); + for j = 1:nCh + for k = (j + 1):nCh + r = sum(z(:, :, j).*z(:, :, k), 1); + r(r > 1) = 1; % guard against rounding, as corr does + r(r < -1) = -1; + EMGCorr(binindstart:binindend) = EMGCorr(binindstart:binindend) + r(:); end - counter = counter + 1; end end -% toc EMGCorr = EMGCorr / (length(xcorr_chs) * (length(xcorr_chs) - 1) / 2); % normalize @@ -256,6 +285,13 @@ EMGFromLFP.channels = xcorr_chs; EMGFromLFP.detectorName = 'getEMGFromLFP'; EMGFromLFP.samplingFrequency = samplingFrequency; +EMGFromLFP.detectorinfo.channelSelection = selectionMethod; +EMGFromLFP.detectorinfo.maxAutoChannels = maxAutoChannels; +EMGFromLFP.detectorinfo.nUsableSpikeGroups = nUsableSpikeGroups; +EMGFromLFP.detectorinfo.spikeGroupsUsed = spkgrpsused; +EMGFromLFP.detectorinfo.specialChannels = specialChannels; +EMGFromLFP.detectorinfo.rejectChannels = rejectChannels; +EMGFromLFP.detectorinfo.nChannelPairs = nPairs; if ~any(~isnan(EMGFromLFP.data)) keyboard diff --git a/test/test_getEMGFromLFP.m b/test/test_getEMGFromLFP.m index 1a51651..b8732a9 100644 --- a/test/test_getEMGFromLFP.m +++ b/test/test_getEMGFromLFP.m @@ -121,4 +121,170 @@ function test_with_fromDat_option(testCase) % Verify that the data is not all NaNs verifyFalse(testCase, all(isnan(EMGFromLFP.data))); -end \ No newline at end of file +end + +function test_few_groups_selection_and_values_match_legacy(testCase) +% Layouts with <= maxAutoChannels spike groups must give the same +% channels as the former implementation for the same random seed, and the +% same EMG values up to floating-point rounding. +basepath = testCase.TestData.tempDir; +cases = {{}, {'rejectChannels', [1, 2, 9]}, {'specialChannels', [5, 30]}}; +for c = 1:numel(cases) + opts = cases{c}; + rng(7 + c); + newEMG = getEMGFromLFP(basepath, 'restrict', [0, 8], 'saveMat', false, ... + 'overwrite', true, 'noPrompts', true, opts{:}); + rng(7 + c); + [legacyChannels, legacyData] = legacyEMGFromLFP(basepath, [0, 8], opts{:}); + verifyEqual(testCase, newEMG.channels, legacyChannels); + verifyEqual(testCase, newEMG.data, legacyData, 'AbsTol', 1e-12); + verifyEqual(testCase, newEMG.detectorinfo.channelSelection, 'onePerSpikeGroup'); +end +end + +function test_single_shank_selection_matches_legacy(testCase) +basepath = makeSession(testCase, {1:16}, 16); +rng(3); +newEMG = getEMGFromLFP(basepath, 'restrict', [0, 8], 'saveMat', false, ... + 'overwrite', true, 'noPrompts', true); +rng(3); +[legacyChannels, legacyData] = legacyEMGFromLFP(basepath, [0, 8]); +verifyEqual(testCase, newEMG.channels, legacyChannels); +verifyEqual(testCase, numel(newEMG.channels), 5); +verifyEqual(testCase, newEMG.data, legacyData, 'AbsTol', 1e-12); +verifyEqual(testCase, newEMG.detectorinfo.channelSelection, 'fiveFromSingleSpikeGroup'); +end + +function test_many_spike_groups_are_capped(testCase) +% Many small spike groups: 42 groups of 6 channels. +nGroups = 42; +groups = arrayfun(@(g) (g - 1)*6+(1:6), 1:nGroups, 'UniformOutput', false); +basepath = makeSession(testCase, groups, nGroups*6); + +EMG = getEMGFromLFP(basepath, 'restrict', [0, 4], 'saveMat', false, ... + 'overwrite', true, 'noPrompts', true); +verifyEqual(testCase, numel(EMG.channels), 16); +verifyEqual(testCase, EMG.detectorinfo.channelSelection, 'onePerSpikeGroupCapped'); +verifyEqual(testCase, EMG.detectorinfo.nUsableSpikeGroups, nGroups); +expectedGroups = unique(round(linspace(1, nGroups, 16))); +verifyEqual(testCase, EMG.detectorinfo.spikeGroupsUsed, expectedGroups); +groupOfChannel = ceil(EMG.channels/6); +verifyEqual(testCase, sort(groupOfChannel), expectedGroups); +verifyEqual(testCase, EMG.detectorinfo.nChannelPairs, 16*15/2); + +% special channels are added on top of the cap +EMG = getEMGFromLFP(basepath, 'restrict', [0, 4], 'saveMat', false, ... + 'overwrite', true, 'noPrompts', true, 'specialChannels', [2, 3]); +verifyTrue(testCase, all(ismember([2, 3], EMG.channels))); +verifyLessThanOrEqual(testCase, numel(EMG.channels), 18); + +% the cap can be raised or disabled +EMG = getEMGFromLFP(basepath, 'restrict', [0, 4], 'saveMat', false, ... + 'overwrite', true, 'noPrompts', true, 'maxAutoChannels', inf); +verifyEqual(testCase, numel(EMG.channels), nGroups); +verifyEqual(testCase, EMG.detectorinfo.channelSelection, 'onePerSpikeGroup'); +end + +% --------------------------------------------------------------------- +function basepath = makeSession(testCase, groups, nChannels) +basepath = tempname; +mkdir(basepath); +testCase.addTeardown(@() rmdir(basepath, 's')); +[~, recordingname] = fileparts(basepath); +session.extracellular.nChannels = nChannels; +session.extracellular.spikeGroups.channels = groups; +session.extracellular.srLfp = 1250; +session.extracellular.sr = 20000; +save(fullfile(basepath, [recordingname, '.session.mat']), 'session'); +data = round(1000*randn(10*1250, nChannels)); +fid = fopen(fullfile(basepath, [recordingname, '.lfp']), 'w'); +fwrite(fid, data', 'int16'); +fclose(fid); +end + +function [xcorr_chs, EMGCorr] = legacyEMGFromLFP(basepath, restrict, varargin) +% Frozen copy of the channel selection, filtering and per-bin corr() loop +% of getEMGFromLFP before the many-spike-group change (neurocode 732cbbd). +p = inputParser; +addParameter(p, 'specialChannels', []); +addParameter(p, 'rejectChannels', []); +parse(p, varargin{:}); +specialChannels = p.Results.specialChannels; +rejectChannels = p.Results.rejectChannels; + +[~, recordingname] = fileparts(basepath); +load(fullfile(basepath, [recordingname, '.session.mat']), 'session'); +nChannels = session.extracellular.nChannels; +SpkGrps = session.extracellular.spikeGroups.channels; +Fs = session.extracellular.srLfp; +binScootS = 1 ./ 2; +binScootSamps = round(Fs*binScootS); +corrChunkSz = 20; + +usablechannels = []; +spkgrpstouse = []; +for gidx = 1:length(SpkGrps) + usableshankchannels{gidx} = setdiff(SpkGrps{gidx}, rejectChannels); %#ok + usablechannels = cat(2, usablechannels, usableshankchannels{gidx}); + if ~isempty(usableshankchannels{gidx}) + spkgrpstouse = cat(2, spkgrpstouse, gidx); + end +end +usableshankchannels = usableshankchannels(spkgrpstouse); +if length(usableshankchannels) > 1 + n = 1; +else + n = 5; +end +xcorr_chs = []; +for gidx = 1:length(usableshankchannels) + if ~isempty(usableshankchannels{gidx}) + if n == 1 + randChfromShank = usableshankchannels{gidx}(randi(length(usableshankchannels{gidx}), n, 1)); + elseif n > 1 + randChfromShank = usableshankchannels{gidx}(randperm(length(usableshankchannels{gidx}), n)); + end + xcorr_chs = [xcorr_chs, randChfromShank]; %#ok + end +end +xcorr_chs = unique([xcorr_chs, specialChannels]); + +lfp = loadBinary(fullfile(basepath, [recordingname, '.lfp']), 'nChannels', nChannels, ... + 'channels', xcorr_chs, 'start', restrict(1), 'duration', diff(restrict), 'frequency', Fs); +maxfreqband = floor(max([625, Fs / 2])); +h = fdesign.bandpass(275, 300, maxfreqband-25, maxfreqband, 60, 1, 60, Fs); +Filt = design(h, 'butter', 'MatchExactly', 'passband'); +filt_sig = zeros(size(lfp)); +for i = 1:size(filt_sig, 2) + filt_sig(:, i) = filter(Filt, lfp(:, i)); + filt_sig(:, i) = filter(Filt, filt_sig(end:-1:1, i)); + filt_sig(:, i) = filt_sig(end:-1:1, i); +end +lfp = filt_sig; + +xcorr_window_samps = round(binScootS*Fs); +xcorr_window_inds = -xcorr_window_samps:xcorr_window_samps; +timestamps = (1 + xcorr_window_inds(end)):binScootSamps:(size(lfp, 1) - xcorr_window_inds(end)); +EMGCorr = zeros(length(timestamps), 1); +for j = 1:(length(xcorr_chs)) + for k = (j + 1):length(xcorr_chs) + c1 = []; + c2 = []; + binind = 0; + binindstart = 1; + for i = timestamps + binind = binind + 1; + c1 = cat(2, c1, lfp(i + xcorr_window_inds, j)); + c2 = cat(2, c2, lfp(i + xcorr_window_inds, k)); + if size(c1, 2) == corrChunkSz || i == timestamps(end) + tmp = diag(corr(c1, c2)); + EMGCorr(binindstart:binind) = EMGCorr(binindstart:binind) + tmp; + c1 = []; + c2 = []; + binindstart = binind + 1; + end + end + end +end +EMGCorr = EMGCorr / (length(xcorr_chs) * (length(xcorr_chs) - 1) / 2); +end From c50ca5a2f503f8adeceed34b693512487ac468aa Mon Sep 17 00:00:00 2001 From: Ryan Harvey Date: Fri, 20 Nov 2026 12:02:59 +0100 Subject: [PATCH 2/4] Fix MATLAB setup in CI ubuntu-latest now resolves to Ubuntu 26.04, where setup-matlab@v1 installs the latest MATLAB release with an installer that is no longer supported, and activation fails before any test runs. - Pin the runner to ubuntu-24.04. - Use setup-matlab@v2 with a pinned release (R2025b) and the toolboxes the tests need (Signal Processing, DSP System, Statistics and Machine Learning); v2 installs only MATLAB unless products are listed. - Update actions/checkout to v4. --- .github/workflows/ci.yml | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d66adab..6752d1f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,22 +10,28 @@ on: jobs: test: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - name: Checkout repository - uses: actions/checkout@v2 + uses: actions/checkout@v4 with: path: neurocode # Checkout into a folder named 'neurocode' - name: Checkout external repository - uses: actions/checkout@v2 + uses: actions/checkout@v4 with: repository: ayalab1/CellExplorer path: CellExplorer - name: Set up MATLAB - uses: matlab-actions/setup-matlab@v1 + uses: matlab-actions/setup-matlab@v2 + with: + release: R2025b + products: > + Signal_Processing_Toolbox + DSP_System_Toolbox + Statistics_and_Machine_Learning_Toolbox - name: Compile MEX files run: | From 29018d9fd160bc02a742fee32ac7d3ed5a06a248 Mon Sep 17 00:00:00 2001 From: Ryan Harvey Date: Fri, 20 Nov 2026 12:13:02 +0100 Subject: [PATCH 3/4] Run MATLAB in CI through run-command With setup-matlab@v2, calling matlab -batch from a shell step finds no license ("Unable to find a license for MATLAB"). Public repositories are licensed only through the matlab-actions run steps, so compile the MEX files and run the tests with matlab-actions/run-command@v2. --- .github/workflows/ci.yml | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6752d1f..4e65811 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -33,11 +33,19 @@ jobs: DSP_System_Toolbox Statistics_and_Machine_Learning_Toolbox - - name: Compile MEX files - run: | - matlab -batch "cd neurocode/utilities/intervalsC+; mex CountInIntervals.c; mex FindInInterval.c; mex MatchUpIndices.c" - matlab -batch "cd neurocode/utilities/mapsC+; mex Contiguous.c; mex FindField.c" + # Public repositories get a MATLAB license only through the + # matlab-actions run steps, not by calling matlab from a shell. + - name: Compile interval MEX files + uses: matlab-actions/run-command@v2 + with: + command: cd neurocode/utilities/intervalsC+; mex CountInIntervals.c; mex FindInInterval.c; mex MatchUpIndices.c + + - name: Compile map MEX files + uses: matlab-actions/run-command@v2 + with: + command: cd neurocode/utilities/mapsC+; mex Contiguous.c; mex FindField.c - name: Run MATLAB tests - run: | - matlab -batch "addpath(genpath('neurocode')); addpath('CellExplorer/calc_CellMetrics'); results = runtests('neurocode/test'); assertSuccess(results);" \ No newline at end of file + uses: matlab-actions/run-command@v2 + with: + command: addpath(genpath('neurocode')); addpath('CellExplorer/calc_CellMetrics'); results = runtests('neurocode/test'); assertSuccess(results); From 37e329c73f5c0421a4589e0d5fe590071a30b24d Mon Sep 17 00:00:00 2001 From: Ryan Harvey Date: Fri, 20 Nov 2026 12:26:55 +0100 Subject: [PATCH 4/4] Install Parallel Computing Toolbox in CI LFPfromDat calls gpuDeviceCount (useGPU defaults to true) and its progress reporter uses parallel.pool.DataQueue, both from Parallel Computing Toolbox, so test_LFPfromDat errors without it. --- .github/workflows/ci.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4e65811..1cdd4e5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -32,6 +32,7 @@ jobs: Signal_Processing_Toolbox DSP_System_Toolbox Statistics_and_Machine_Learning_Toolbox + Parallel_Computing_Toolbox # Public repositories get a MATLAB license only through the # matlab-actions run steps, not by calling matlab from a shell.