Skip to content

[ENH] ale subtraction scale improvements - #1002

Merged
jdkent merged 4 commits into
neurostuff:mainfrom
jdkent:enh/ALESubtraction_SCALE_improvements
Apr 3, 2026
Merged

[ENH] ale subtraction scale improvements#1002
jdkent merged 4 commits into
neurostuff:mainfrom
jdkent:enh/ALESubtraction_SCALE_improvements

Conversation

@jdkent

@jdkent jdkent commented Apr 3, 2026

Copy link
Copy Markdown
Member

Closes # .

Changes proposed in this pull request:

  • 5-10x speedup for SCALE

jdkent added 3 commits April 3, 2026 02:12
Use empirical voxelwise SCALE nulls and add voxel-level Monte Carlo FWE support.

Stream ALESubtraction voxelwise null updates to reduce storage overhead, speed shared cluster and null-distribution helpers, and deduplicate shared permutation summarystat generation in the CBMA base path.
Update the MACM and CBMA example snippets to show voxel-level Monte Carlo FWE correction for SCALE and clarify that cluster-level correction is not supported.
@sourcery-ai

sourcery-ai Bot commented Apr 3, 2026

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Refactors ALESubtraction and SCALE CBMA estimators to use streamed permutation tail counts and optimized permutation paths, adds voxel-wise Monte Carlo FWE correction for SCALE, and aligns core statistical helpers and tests with the new behavior while simplifying some histogram-based APIs and cluster-mass utilities.

Class diagram for updated ALESubtraction permutation logic

classDiagram
    direction TB

    class CBMAEstimator {
        +masker
        +kernel_transformer
        +null_distributions_
        +_compute_summarystat(data)
        +_compute_permutation_summarystat(iter_ijk, iter_df)
        +_compute_null_montecarlo_permutation(iter_ijk, iter_df, bin_edges)
        +_correct_fwe_montecarlo_permutation(iter_ijk, iter_df, vfwe_only)
    }

    class PairwiseCBMAEstimator {
        +masker
        +kernel_transformer
        +null_distributions_
    }

    CBMAEstimator <|-- PairwiseCBMAEstimator

    class ALESubtraction {
        +n_iters
        +n_cores
        +vfwe_only
        +memmap_filenames
        +null_distributions_
        +inputs_
        +_collect_ma_maps(coords_key, maps_key, return_type)
        +_compute_summarystat_est(ma_values)
        +_combine_ma_maps(ma_maps1, ma_maps2)
        +_run_permutation(i_iter, n_grp1, ma_arr)
        +_fit(dataset1, dataset2)
        +correct_fwe_montecarlo(result, voxel_thresh, n_iters, n_cores, vfwe_only)
    }

    PairwiseCBMAEstimator <|-- ALESubtraction

    class _finalize_alediff_tail_counts {
        +_finalize_alediff_tail_counts(left_counts, right_counts, n_iters)
    }

    class _collect_ale_masked_ma_maps {
        +_collect_ale_masked_ma_maps(estimator, coords_key, maps_key)
    }

    ALESubtraction --> _collect_ale_masked_ma_maps : uses
    ALESubtraction --> _finalize_alediff_tail_counts : uses
    ALESubtraction --> CBMAEstimator : uses base methods

    class ALEKernel {
        +transform(data, masker, return_type)
    }

    ALESubtraction --> ALEKernel : uses

    class collect_csr_ma_maps {
        +collect_csr_ma_maps(estimator, coords_key, maps_key)
    }

    _collect_ale_masked_ma_maps --> collect_csr_ma_maps : wraps

    class _csr_row_max {
        +_csr_row_max(ma_values)
    }

    _collect_ale_masked_ma_maps --> _csr_row_max : caches_max

    class _calculate_cluster_measures {
        +_calculate_cluster_measures(arr3d, threshold, conn, tail)
    }

    ALESubtraction --> _calculate_cluster_measures : for_cluster_FWE

    class null_to_p {
        +null_to_p(test_values, null_distribution, tail, symmetric)
    }

    class p_to_z {
        +p_to_z(p_values, tail)
    }

    ALESubtraction --> null_to_p : for_FWE
    ALESubtraction --> p_to_z : for_Zmaps

    class DEFAULT_FLOAT_DTYPE {
    }

    ALESubtraction --> DEFAULT_FLOAT_DTYPE : dtype
Loading

Class diagram for updated SCALE estimator and Monte Carlo FWE

classDiagram
    direction TB

    class CBMAEstimator {
        +masker
        +kernel_transformer
        +null_distributions_
        +inputs_
        +_compute_summarystat(data)
        +_compute_permutation_summarystat(iter_ijk, iter_df)
        +_compute_null_montecarlo_permutation(iter_ijk, iter_df, bin_edges)
        +_correct_fwe_montecarlo_permutation(iter_ijk, iter_df, vfwe_only)
    }

    class SCALE {
        +xyz
        +n_iters
        +n_cores
        +null_distributions_
        +inputs_
        +_fit(dataset)
        +_compute_summarystat_est(data)
        +_prepare_permutations(n_iters)
        +_prepare_permutation_args(coordinates)
        +_scale_to_p(stat_values, scale_values)
        +_run_permutation(iter_idx, voxel_ijk, iter_df, permutation_args)
        +_iterate_permuted_stats(rand_idx, voxel_ijk, iter_df, permutation_args, n_cores)
        +correct_fwe_montecarlo(result, voxel_thresh, n_iters, n_cores, vfwe_only)
    }

    CBMAEstimator <|-- SCALE

    class ALEKernel {
        +sample_size
        +fwhm
        +transform(data, masker, return_type)
    }

    SCALE --> ALEKernel : optional_kernel_transformer

    class compute_ale_ma {
        +compute_ale_ma(mask_img, voxel_ijk, kernel, exp_idx, sample_sizes, use_dict)
    }

    SCALE --> compute_ale_ma : uses_for_permutations

    class get_ale_kernel {
        +get_ale_kernel(mask_img, fwhm)
    }

    SCALE --> get_ale_kernel : prepares_kernel

    class mm2vox {
        +mm2vox(xyz, affine)
    }

    SCALE --> mm2vox : xyz_to_voxel_indices

    class p_to_z {
        +p_to_z(p_values, tail)
    }

    SCALE --> p_to_z : voxelwise_Z

    class null_to_p {
        +null_to_p(test_values, null_distribution, tail, symmetric)
    }

    SCALE --> null_to_p : in_correct_fwe_montecarlo

    class DEFAULT_FLOAT_DTYPE {
    }

    SCALE --> DEFAULT_FLOAT_DTYPE : dtype

    class FWECorrector {
        +method
        +n_iters
        +n_cores
        +transform(result)
    }

    FWECorrector --> SCALE : calls_correct_fwe_montecarlo
Loading

File-Level Changes

Change Details Files
Refactor ALESubtraction permutation logic to stream tail counts, avoid storing full null matrices when possible, and simplify p-value/sign computation.
  • Introduce _finalize_alediff_tail_counts to convert streamed left/right exceedance counts into two-sided p-values and difference signs.
  • Change _run_permutation to return a single permutation difference map instead of writing into a shared memmap and update callers in _fit and correct_fwe_montecarlo to accumulate tail counts and max statistics in Python.
  • Replace iter-wise memmap-based max-stat computation with direct tracking of per-iteration absolute maxima for voxel-level FWE null distributions.
  • Remove chunked _alediff_to_p_values and scalar helper methods in favor of the new streaming-based approach while keeping reference implementations in tests for regression checking.
nimare/meta/cbma/ale.py
Rework SCALE estimator to use empirical voxel-wise permutation p-values, stream exceedance counts, and add voxel-level Monte Carlo FWE correction.
  • Remove memmap-based storage of the full permutation null matrix and the histogram_bins-based null-distribution representation from the main SCALE path.
  • Add helpers to prepare permutation inputs (_prepare_permutations, _prepare_permutation_args) including precomputed voxel indices and optional ALE kernel reuse via compute_ale_ma and get_ale_kernel.
  • Implement a new streaming permutation engine (_iterate_permuted_stats and updated _run_permutation) that yields permuted stat maps using either optimized kernel-based MA computation or the legacy DataFrame path.
  • Change _scale_to_p to operate on exceedance counts with direct empirical p-values and z-scores, and wire this into _fit via an exceedance_counts accumulator.
  • Implement correct_fwe_montecarlo for SCALE to perform voxel-level max-statistic Monte Carlo FWE correction only, storing the resulting null distribution and emitting appropriate result maps and description; explicitly reject cluster-level FWE for SCALE.
nimare/meta/cbma/ale.py
examples/02_meta-analyses/07_macm.py
examples/02_meta-analyses/01_plot_cbma.py
Optimize cluster-measure computation and permutation helpers shared across CBMA estimators.
  • Rewrite _calculate_cluster_measures to factor positive and negative cluster handling through a shared _max_cluster_stats routine using precomputed mass_values and ndimage.sum, while preserving behavior for upper and two-sided tails.
  • Factor out shared permutation summary-statistic computation into _compute_permutation_summarystat and reuse it in both _compute_null_montecarlo_permutation and _correct_fwe_montecarlo_permutation.
  • Minor cleanup in _apply_liberal_mask by removing dead commented warning code.
nimare/meta/utils.py
nimare/meta/cbma/base.py
Tighten and extend statistical utilities and tests to validate new streaming and optimized paths for ALESubtraction and SCALE.
  • Add reference implementations for cluster measures, ALE subtraction p-values, and SCALE p-values (both matrix-based and streamed-count variants) and use them to assert equivalence with the optimized implementations.
  • Add tests for ALESubtraction streamed tail counts vs. chunked null evaluation and for SCALE exceedance-count p-values vs. permutation-matrix p-values.
  • Add tests ensuring SCALE’s optimized permutation path matches the legacy DataFrame path and that SCALE rejects cluster-level Monte Carlo FWE correction while supporting voxel-level Monte Carlo FWE via FWECorrector.
  • Slightly optimize nullhist_to_p in the voxelwise_null branch by vectorizing assignment over indices.
nimare/tests/test_meta_ale.py
nimare/stats.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="nimare/meta/cbma/ale.py" line_range="1272-1277" />
<code_context>
             require_masked_csr(ma_values) if sp_sparse.isspmatrix(ma_values) else ma_values
         )

+    def _prepare_permutations(self, n_iters):
+        """Prepare shared SCALE permutation inputs."""
+        iter_df = self.inputs_["coordinates"].copy()
+        voxel_ijk = mm2vox(self.xyz, self.masker.mask_img.affine).astype(np.int32, copy=False)
+        permutation_args = self._prepare_permutation_args(iter_df)
+        rand_idx = np.random.choice(voxel_ijk.shape[0], size=(iter_df.shape[0], n_iters))
+        return iter_df, voxel_ijk, permutation_args, rand_idx
+
</code_context>
<issue_to_address>
**suggestion:** Clarify and/or rename `rand_idx` and `iter_idx` to avoid confusion between voxel indices and iteration indices.

In `_prepare_permutations`, `rand_idx` is shaped `(n_rows, n_iters)` and stores indices into `voxel_ijk`. Later, `_iterate_permuted_stats` passes `rand_idx[:, i_iter]` as `iter_idx` to `_run_permutation`, whose docstring calls it a "permutation index". Since these are voxel index arrays rather than scalar iteration indices, the current naming/docstring is misleading. Consider renaming (e.g., `voxel_idx_for_iter`) or updating the docstring to clearly indicate they are voxel indices.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread nimare/meta/cbma/ale.py Outdated
@jdkent
jdkent merged commit 4a6b76e into neurostuff:main Apr 3, 2026
25 checks passed
@codecov

codecov Bot commented Apr 3, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 80.95238% with 24 lines in your changes missing coverage. Please review.
✅ Project coverage is 85.38%. Comparing base (c4adf47) to head (057fff4).
⚠️ Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
nimare/meta/cbma/ale.py 77.57% 24 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1002      +/-   ##
==========================================
- Coverage   85.53%   85.38%   -0.15%     
==========================================
  Files          52       52              
  Lines        9255     9256       +1     
==========================================
- Hits         7916     7903      -13     
- Misses       1339     1353      +14     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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.

1 participant