From dcee2d888017bbeb9dfd27b504244a2e913837b6 Mon Sep 17 00:00:00 2001
From: Chris Markiewicz <effigies@gmail.com>
Date: Wed, 4 Oct 2023 08:01:45 -0400
Subject: [PATCH] FIX: Mask fieldmap before fitting spline field [backport
 gh-396]

---
 sdcflows/interfaces/bspline.py | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/sdcflows/interfaces/bspline.py b/sdcflows/interfaces/bspline.py
index 299f0b7d92..deacea304c 100644
--- a/sdcflows/interfaces/bspline.py
+++ b/sdcflows/interfaces/bspline.py
@@ -195,6 +195,7 @@ def _run_interface(self, runtime):
             center = np.mean(data[mask])
 
         data -= center
+        data[~mask] = 0
 
         # Calculate collocation matrix from (possibly resized) image and knot grids
         colmat = sparse_vstack(grid_bspline_weights(fmapnii, grid) for grid in bs_grids).T.tocsr()
@@ -210,7 +211,7 @@ def _run_interface(self, runtime):
         # Fit the model
         model = lm.Ridge(alpha=self.inputs.ridge_alpha, fit_intercept=False, solver='lsqr')
         for attempt in range(3):
-            model.fit(colmat[mask.reshape(-1), :], data[mask])
+            model.fit(colmat, data.reshape(-1))
             extreme = np.abs(model.coef_).max()
             LOGGER.debug(f"Model fit attempt {attempt}: max(|coeffs|) = {extreme}")
             # Normal values seem to be ~1e2, bad ~1e8. May want to tweak this if