-
Notifications
You must be signed in to change notification settings - Fork 689
Refactored scanpy.tools._sparse_nanmean to eliminate unnecessary data… #3570
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Reovirus
wants to merge
21
commits into
scverse:main
Choose a base branch
from
Reovirus:_sparse_nanmean_is_inefficient
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+76
−18
Open
Changes from all commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
acfbd11
Refactored scanpy.tools._sparse_nanmean to eliminate unnecessary data…
Reovirus 2882948
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] a36b33c
rewrite logics with numba (for scipy <1.15.0)
Reovirus cdb443b
Add types
Reovirus 8021f8c
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 523cccc
correct jit docorators
Reovirus 968e093
add correct fuction names
Reovirus 9d06854
rewrite logics without prange (prange tries to rewrite one element in…
Reovirus 4087447
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 45688e7
one ptr copy
Reovirus e089438
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] fa3c5c2
add score_genes benchmark
flying-sheep cad1db9
some changes
Reovirus baa0959
replace np.add.at by np.bincount + add some njint
Reovirus 6b3e891
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 2bb6d2a
Merge branch 'main' into _sparse_nanmean_is_inefficient
flying-sheep ffee669
Merge branch 'scverse:main' into _sparse_nanmean_is_inefficient
Reovirus 1c3a67e
add release notes
Reovirus 2630ee0
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 7130f25
style
Reovirus 7e23b19
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| Performance Enhancement: Optimized Mean Calculation in Gene Expression Matrix | ||
|
|
||
| Refactored the mean calculation logic in the gene expression matrix to eliminate unnecessary data copying. This optimization significantly improves execution speed, particularly beneficial for large-scale datasets. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -6,9 +6,10 @@ | |||||
|
|
||||||
| import numpy as np | ||||||
| import pandas as pd | ||||||
| from numba import prange | ||||||
|
|
||||||
| from .. import logging as logg | ||||||
| from .._compat import CSBase, old_positionals | ||||||
| from .._compat import CSBase, CSCBase, njit, old_positionals | ||||||
| from .._utils import _check_use_raw, is_backed_type | ||||||
| from ..get import _get_obs_rep | ||||||
|
|
||||||
|
|
@@ -28,28 +29,74 @@ | |||||
| _GetSubset = Callable[[_StrIdx], np.ndarray | CSBase] | ||||||
|
|
||||||
|
|
||||||
| @njit | ||||||
| def _get_sparce_nanmean_indptr( | ||||||
| data: NDArray[np.float64], indptr: NDArray[np.int32], shape: tuple[int, int] | ||||||
| ) -> NDArray[np.float64]: | ||||||
| n_rows = len(indptr) - 1 | ||||||
| result = np.empty(n_rows, dtype=np.float64) | ||||||
|
|
||||||
| for i in prange(n_rows): | ||||||
| start = indptr[i] | ||||||
| end = indptr[i + 1] | ||||||
| count = np.float64(shape[1]) | ||||||
| total = 0.0 | ||||||
| for j in prange(start, end): | ||||||
| val = data[j] | ||||||
| if not np.isnan(val): | ||||||
| total += val | ||||||
| else: | ||||||
| count -= 1 | ||||||
| if count == 0: | ||||||
| result[i] = np.nan | ||||||
| else: | ||||||
| result[i] = total / count | ||||||
| return result | ||||||
|
|
||||||
|
|
||||||
| @njit | ||||||
| def _get_sparce_nanmean_indices( | ||||||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
| data: NDArray[np.float64], indices: NDArray[np.int32], shape: tuple | ||||||
| ) -> NDArray[np.float64]: | ||||||
| num_bins = shape[1] | ||||||
| num_elements = np.float64(shape[0]) | ||||||
| sum_arr = np.zeros(num_bins, dtype=np.float64) | ||||||
| count_arr = np.repeat(num_elements, num_bins) | ||||||
| result = np.zeros(num_bins, dtype=np.float64) | ||||||
|
|
||||||
| for i in range(data.size): | ||||||
| idx = indices[i] | ||||||
| val = data[i] | ||||||
| if not np.isnan(val): | ||||||
| sum_arr[idx] += val | ||||||
| else: | ||||||
| count_arr[idx] -= 1.0 | ||||||
|
|
||||||
| for i in range(num_bins): | ||||||
| if count_arr[i] == 0: | ||||||
| result[i] = np.nan | ||||||
| else: | ||||||
| result[i] = sum_arr[i] / count_arr[i] | ||||||
| return result | ||||||
|
|
||||||
|
|
||||||
| def _sparse_nanmean(X: CSBase, axis: Literal[0, 1]) -> NDArray[np.float64]: | ||||||
| """np.nanmean equivalent for sparse matrices.""" | ||||||
| if not isinstance(X, CSBase): | ||||||
| msg = "X must be a compressed sparse matrix" | ||||||
| raise TypeError(msg) | ||||||
|
|
||||||
| # count the number of nan elements per row/column (dep. on axis) | ||||||
| Z = X.copy() | ||||||
| Z.data = np.isnan(Z.data) | ||||||
| Z.eliminate_zeros() | ||||||
| n_elements = Z.shape[axis] - Z.sum(axis) | ||||||
|
|
||||||
| # set the nans to 0, so that a normal .sum() works | ||||||
| Y = X.copy() | ||||||
| Y.data[np.isnan(Y.data)] = 0 | ||||||
| Y.eliminate_zeros() | ||||||
|
|
||||||
| # the average | ||||||
| s = Y.sum(axis, dtype="float64") # float64 for score_genes function compatibility) | ||||||
| m = s / n_elements | ||||||
|
|
||||||
| return m | ||||||
| algo_shape = X.shape | ||||||
| algo_axis = axis | ||||||
| # in CSC ans CSR we have "transposed" form of data storaging (indices is colums/rows, indptr is row/columns) | ||||||
| # as a result, algorythm for CSC is algorythm for CSR but with transposed shape (columns in CSC is equal rows in CSR) | ||||||
| # base algo for CSR, for csc we should "transpose" matrix size and use same logics | ||||||
| if isinstance(X, CSCBase): | ||||||
| algo_shape = X.shape[::-1] | ||||||
| algo_axis = int(not axis) | ||||||
| if algo_axis == 1: | ||||||
| return _get_sparce_nanmean_indptr(X.data, X.indptr, algo_shape) | ||||||
| else: | ||||||
| return _get_sparce_nanmean_indices(X.data, X.indices, algo_shape) | ||||||
|
|
||||||
|
|
||||||
| @old_positionals( | ||||||
|
|
||||||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.