Skip to content

Fix AttributeError in CNMF.fit when low_rank_background is None - #1590

Merged
pgunn merged 1 commit into
flatironinstitute:devfrom
zyyk78:fix-sparse-background-guard
Oct 12, 2026
Merged

pgunn merged 1 commit into
flatironinstitute:devfrom
zyyk78:fix-sparse-background-guard

Conversation

@zyyk78

@zyyk78 zyyk78 commented Oct 12, 2026

Copy link
Copy Markdown
Contributor

Problem

CNMF.fit() crashes with AttributeError: 'csr_matrix' object has no attribute 'any' at cnmf.py:469 when low_rank_background=None and nb_patch > 0.

Root cause

PR #1441 added a guard checking whether any background component is empty:

if (self.estimates.b is not None) and (len(list(np.where(~self.estimates.b.any(axis=0))[0])) > 0):

However, when low_rank_background=None, run_CNMF_patches() returns self.estimates.b as a scipy.sparse matrix (see map_reduce.py:411: b = Im.dot(B_tot)), and sparse matrices do not implement .any(axis=...).

Fix

Replace the .any(axis=0) call with a sparse-safe equivalent:

_b_nonempty = np.ravel(np.asarray((self.estimates.b != 0).sum(axis=0)))

This works for both dense ndarray and scipy.sparse matrices, preserves the original semantics (raise only when at least one background component is all-zero), and avoids densifying self.estimates.b (which is part of the public estimates API and is already handled as either representation downstream, e.g. in compute_residuals).

Related issue

Fixes the crash reported in #1441.

@pgunn
pgunn changed the base branch from main to dev October 12, 2026 21:06
@pgunn

pgunn commented Oct 12, 2026

Copy link
Copy Markdown
Member

Thanks!

@pgunn
pgunn merged commit 48caab5 into flatironinstitute:dev Oct 12, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants