diff --git a/_toc.yml b/_toc.yml index 3b6e8eac..81024baa 100644 --- a/_toc.yml +++ b/_toc.yml @@ -21,7 +21,6 @@ parts: - file: content/Signal_Decay - file: content/T2star_S0_Variability - file: content/TE_Dependence - - file: content/plot_approach_figures.md - caption: Practical Resources chapters: - file: content/Multi_Echo_Datasets diff --git a/content/Signal_Decay.md b/content/Signal_Decay.md index ff790c56..34a8a8df 100644 --- a/content/Signal_Decay.md +++ b/content/Signal_Decay.md @@ -12,42 +12,35 @@ kernelspec: # Signal Decay -```{important} -This chapter should differentiate itself from TE_Dependence by focusing on the application of {eq}`monoexponential_decay` -to raw signal, rather than decompositions. -``` +In this chapter, we illustrate how BOLD signal decays and how we can glean useful information from that decay rate. -```{important} -The general flow of this chapter should be: - -1. Explain the monoexponential decay equation. - 1. Mention other models of signal decay, including biexponential models, - and why they generally aren't used on multi-echo fMRI data. -2. Show signal decay in real data. - 1. Start with single-volume brain images across increasing echo times. - 2. Next, show a scatter plot of the values for a single voxel over time, separated by echo time, - to give a better sense of the scale of the decay. - 3. Line plots of the different echo times for a single voxel to show that decay is not a simple scalar. -3. Show a simulated, static decay curve. -4. Show the difference in decay curves for "active" and "inactive" states in the same voxel (i.e., different T2* values). -5. Show how single-echo data fluctuate over time, given an underlying signal. -6. Add a changing decay curve underneath the single-echo data point. -7. Overlay points for the changing T2* and S0 values as well. -8. Plot the decay curves of the same relative fluctuations, but dependent solely on S0 or T2* changes. -9. Overlay single-echo data points on the fluctuating decay curves, - to show how the two types of fluctuations cannot be dissociated using single-echo data. - 1. Plot scaled T2* against the single-echo data in a line plot. The time series will be very similar, but slightly different. - 2. Plot scaled S0 against the single-echo data. The time series will effectively be the same. - 3. Point out that we don't know the underlying T2* or S0 fluctuations, - so this just shows how very similar signal can come from T2* _or_ S0. -10. Overlay multi-echo data points on the fluctuating decay curves, to show how the differences in the patterns are much clearer. -11. Discuss the effect of noise on the multi-echo signal. Perhaps plot a single voxel's real values? -12. Point to the TE Dependence chapter. -``` +Throughout the chapter, we describe the signal with the monoexponential decay model: -In this chapter, we illustrate how BOLD signal decays and how we can glean useful information from that decay rate. +```{math} +:label: monoexponential_decay_signal +S(TE) = S_{0} e^{-TE / T_{2}^{*}} = S_{0} e^{-TE \cdot R_{2}^{*}} +``` -To do this, we will use a combination of simulated and real multi-echo data. +$S_{0}$ is the signal we would measure at $TE = 0$, before any decay has happened. +$T_{2}^{*}$ is the time constant of the decay: the longer $T_{2}^{*}$ is, the more slowly the signal fades. +$R_{2}^{*} = 1 / T_{2}^{*}$ is the same quantity expressed as a decay *rate*. +The BOLD effect works through $T_{2}^{*}$: +when local blood oxygenation increases, there is less deoxygenated hemoglobin to disturb the magnetic field, +so $T_{2}^{*}$ gets longer and the signal decays more slowly. +Many sources of noise, such as head motion and inflow, instead change $S_{0}$. + +The monoexponential model is an approximation. +A voxel contains several pools of water, such as water in tissue, in blood, in cerebrospinal fluid, and trapped between layers of myelin, +and each pool decays at its own rate. +The decay of the whole voxel is therefore better described by a sum of exponentials, +such as a biexponential model with two pools. +However, each extra pool adds parameters to estimate, +and multi-echo fMRI usually has only three to five echoes per volume, each with its own noise, +which is not enough to estimate those extra parameters reliably. +For that reason, multi-echo fMRI methods, including all of the ones in this book, use the monoexponential model. +[](T2star_S0_Variability.md) shows what happens when a monoexponential model is fit to decay that is not monoexponential. + +To illustrate this, we will use a combination of simulated and real multi-echo data. ```{code-cell} ipython3 :tags: [hide-cell] @@ -55,6 +48,7 @@ import json import os from glob import glob +import matplotlib import matplotlib.pyplot as plt import nibabel as nb import numpy as np @@ -82,9 +76,13 @@ os.makedirs(out_dir, exist_ok=True) data = load_pafin(data_path) ted_dir = os.path.join(data_path, "tedana") n_echoes = len(data['echo_times']) +# Exact echo times in milliseconds, for model fitting +tes_ms = np.array(data['echo_times']) * 1000 +# Echo times rounded to whole milliseconds, for indexing the simulated curves below data['echo_times'] = [int(np.round(te * 1000)) for te in data['echo_times']] -pal = sns.color_palette("cubehelix", n_echoes) +# Drop the last cubehelix color, which is too light to see on a white background +pal = sns.color_palette("cubehelix", n_echoes + 1)[:n_echoes] img = image.index_img(data['echo_files'][0], 0) arr = img.get_fdata() @@ -143,25 +141,34 @@ The data we use is a single resting-state run, with five echo times. :tags: [hide-cell, hide-output] plt.style.use("dark_background") -fig, axes = plt.subplots(figsize=(26, 16), nrows=len(data['echo_files'])) +fig, axes = plt.subplots(figsize=(16, 15), nrows=len(data['echo_files'])) +fig.subplots_adjust(left=0, right=0.92, top=0.97, bottom=0.01, hspace=0.15) +# Use the same intensity range for every echo, so that the decay is visible +vmax = np.max(imgs[0].get_fdata()) for i_echo, img in enumerate(imgs): - te = data['echo_times'][i_echo] - if i_echo == 0: - arr = img.get_fdata() - vmax = np.max(arr) - plotting.plot_epi( img, cut_coords=[-15, 0, 15, 30, 45], display_mode="z", annotate=False, draw_cross=False, + colorbar=False, axes=axes[i_echo], figure=fig, + vmin=0, vmax=vmax, cmap="gray", ) - axes[i_echo].set_title("TE={}ms".format(te), fontsize=20, pad=0) + axes[i_echo].set_title(f"TE = {tes_ms[i_echo]:.1f} ms", fontsize=18, pad=0) + +# One colorbar for all of the echoes +cax = fig.add_axes([0.93, 0.25, 0.012, 0.5]) +cbar = fig.colorbar( + matplotlib.cm.ScalarMappable(norm=matplotlib.colors.Normalize(0, vmax), cmap="gray"), + cax=cax, +) +cbar.set_label("Signal", fontsize=16) +cbar.ax.tick_params(labelsize=12) glue_figure("fig_brain_decay", fig, display=False) @@ -173,26 +180,33 @@ plt.style.use("default") :name: fig_brain_decay :align: center -Signal decay in the brain. +The first volume of each echo, shown as axial slices from the bottom (left) to the top (right) of the brain, +with the same intensity scale for every echo. ``` -The nature of multi-echo (ME) acquisition leads to signal decay, with high signal-to-noise ratio (SNR) at short echo times (TE) and lower SNR at longer TEs. -You may notice that the images appear darker as the signal decays with increasing TE. -Additionally, image contrast tends to increase with longer echo times. +As the echo time increases, the whole brain gets darker, because the signal has had more time to decay. +This means that later echoes have a lower signal-to-noise ratio (SNR) than earlier ones. +The decay is not the same everywhere, though. +Near the sinuses and ear canals (left two columns), the signal is almost gone by the third echo, +because $T_{2}^{*}$ is very short there. +The ventricles, on the other hand, become *brighter* than the surrounding tissue at later echoes, +because the cerebrospinal fluid that fills them has a long $T_{2}^{*}$ and decays slowly. +This difference in brightness between tissues is $T_{2}^{*}$-weighted contrast, +which reflects differences in the *average* $T_{2}^{*}$ of each tissue. +It is not the same thing as BOLD contrast, which comes from small *changes* in $T_{2}^{*}$ over time. +[](T2star_S0_Variability.md) describes why the average $T_{2}^{*}$ varies across the brain. ### Echo-specific data and echo time ```{code-cell} ipython3 :tags: [hide-cell] fig, ax = plt.subplots(figsize=(14, 6)) -values = [i[0] for i in ts] for i_echo in range(n_echoes): - rep_echo_times = np.round(np.ones(n_trs) * data['echo_times'][i_echo], decimals=5) - ax.scatter(rep_echo_times, ts[i_echo], alpha=0.05, color=pal[i_echo]) + ax.scatter(np.full(n_trs, tes_ms[i_echo]), ts[i_echo], alpha=0.05, color=pal[i_echo]) -ax.set_ylabel("BOLD signal", fontsize=16) +ax.set_ylabel("Signal", fontsize=16) ax.set_xlabel("Echo Time (ms)", fontsize=16) -ax.set_xticks(data['echo_times']) +ax.set_xticks(np.round(tes_ms, 1)) ax.tick_params(axis="both", which="major", labelsize=14) ax.set_xlim(0, 120) ax.set_ylim(0, 25000) @@ -204,14 +218,22 @@ glue_figure("fig_echo_scatter", fig, display=False) :name: fig_echo_scatter :align: center -Scatter plot of voxel's values by echo time. +The signal of a single voxel at each echo time. +Each point is one volume of the run. ``` -Here, we visualize the temporal variation of a single voxel’s signal (y-axis) across five different echo times (TE) on the x-axis. As expected, the signal magnitude decreases with increasing TE. +Here, we plot the signal of a single voxel in every volume of the run, at each of the five echo times. +As expected, the signal decreases as the echo time increases. +Notice also that the spread of the points, which reflects how much the signal fluctuates over time, +is smallest at the first echo, even though the signal is largest there. +This voxel was chosen because it has strong BOLD fluctuations, +and BOLD fluctuations have little effect at short echo times. +We will see why later in this chapter. ### The signal itself changes with echo time as well -Let us visualize the time series of one voxel acquired at different echo times. While the overall scale of the signal decreases with echo time, the actual pattern of the signal changes as well. +Let us visualize the time series of the same voxel at each echo time. +While the overall scale of the signal decreases with echo time, the pattern of the signal changes as well. ```{code-cell} ipython3 :tags: [hide-cell] @@ -219,13 +241,16 @@ fig, axes = plt.subplots(n_echoes, sharex=True, sharey=False, figsize=(14, 6)) for i_echo in range(n_echoes): axes[i_echo].plot(ts[i_echo], color=pal[i_echo]) axes[i_echo].set_ylabel( - f"{data['echo_times'][i_echo]}ms", rotation=0, va="center", ha="right", fontsize=14 + f"{tes_ms[i_echo]:.1f} ms", + rotation=0, + va="center", + ha="right", + fontsize=14, ) axes[i_echo].set_yticks([]) - axes[i_echo].set_xticks([]) -axes[-1].set_xlabel("Time", fontsize=16) -axes[-1].set_xlim(0, len(ts[i_echo]) - 1) +axes[-1].set_xlabel("Volume", fontsize=16) +axes[-1].set_xlim(0, n_trs - 1) fig.tight_layout() glue_figure("fig_echo_timeseries", fig, display=False) ``` @@ -234,42 +259,207 @@ glue_figure("fig_echo_timeseries", fig, display=False) :name: fig_echo_timeseries :align: center -Time series from a voxel for each echo. +The time series of a single voxel at each echo time. +Each time series is scaled separately, so the y-axes are not comparable. ``` -## The impact of $T_{2}^{*}$ and $S_{0}$ fluctuations on BOLD signal +The later echoes share a slow, wave-like pattern, which is the BOLD signal in this voxel. +The same pattern is much weaker at the first echo, which is dominated by small, fast fluctuations, +along with a spike in the very first volume. +Early in a run, before the magnetization has reached a steady state, the signal is brighter at every echo. +That change affects $S_{0}$ rather than $T_{2}^{*}$, so it stands out most at the first echo, +where the BOLD fluctuations are weakest. + +## Estimating $S_{0}$ and $T_{2}^{*}$ from the decay + +With several echoes, we can estimate the two parameters of {eq}`monoexponential_decay_signal` for each voxel. +Fitting an exponential curve directly is possible, but there is a simpler way. +Taking the natural logarithm of both sides of {eq}`monoexponential_decay_signal` turns the curve into a straight line: + +```{math} +:label: log_linear_model +\ln S(TE) = \ln S_{0} - R_{2}^{*} \cdot TE +``` + +So if we plot $\ln S$ against $TE$, the intercept of the line is $\ln S_{0}$ and its slope is $-R_{2}^{*}$, +and both can be estimated with ordinary least squares. +This "log-linear" fit is fast, and it is the default in `tedana` (`fittype="loglin"`). +`tedana` also offers a nonlinear fit of the exponential curve (`fittype="curvefit"`), which is slower. + +Below, we fit the model to the voxel from {numref}`fig_echo_scatter`. +We fit all of the volumes at once, so we get a single $S_{0}$ and $T_{2}^{*}$ that describe the voxel's average decay. + +```{code-cell} ipython3 +:tags: [hide-cell] +# Log-transform the data. Like tedana, we add 1 to avoid taking the log of zero. +# With signal values in the thousands, this makes no practical difference. +log_ts = np.log(np.abs(ts_1d) + 1) + +# One row per volume per echo: an intercept and the negative echo time +design = np.column_stack([np.ones(n_echoes), -tes_ms]) +design = np.repeat(design, n_trs, axis=0) +intercept, r2s_fit = np.linalg.lstsq(design, log_ts, rcond=None)[0] +s0_fit = np.exp(intercept) +t2s_fit = 1 / r2s_fit + +glue("s0_fit", float(s0_fit), display=False) +glue("t2s_fit", float(t2s_fit), display=False) + +fit_tes = np.linspace(0, 120, 241) +fig, axes = plt.subplots(1, 2, figsize=(16, 6)) + +# Panel A: log-transformed data and the fitted line +for i_echo in range(n_echoes): + axes[0].scatter( + np.full(n_trs, tes_ms[i_echo]), + np.log(np.abs(ts[i_echo]) + 1), + alpha=0.05, + color=pal[i_echo], + ) -In this section, we investigate the two factors driving changes in the signal decay pattern: $T_{2}^{*}$ and $S_{0}$. +axes[0].plot(fit_tes, intercept - r2s_fit * fit_tes, color="black", linewidth=2) +axes[0].annotate( + ( + f"intercept = $\\ln S_0$ = {intercept:.2f}\n" + f"slope = $-R_2^*$ = {-r2s_fit:.4f} ms$^{{-1}}$" + ), + xy=(0.04, 0.06), + xycoords="axes fraction", + fontsize=14, + bbox=dict(fc="white", ec="gray", lw=1), +) +axes[0].set_title("A. Log-transformed signal is linear in TE", fontsize=18, loc="left") +axes[0].set_ylabel("ln(signal)", fontsize=16) + +# Panel B: original data and the fitted exponential curve +for i_echo in range(n_echoes): + axes[1].scatter( + np.full(n_trs, tes_ms[i_echo]), + ts[i_echo], + alpha=0.05, + color=pal[i_echo], + ) + +axes[1].plot(fit_tes, s0_fit * np.exp(-fit_tes / t2s_fit), color="black", linewidth=2) +axes[1].scatter(0, s0_fit, marker="*", s=400, color="red", clip_on=False, zorder=3) +axes[1].annotate( + f"$S_0$ = {s0_fit:.0f}", + xy=(0, s0_fit), + xytext=(8, s0_fit), + fontsize=14, + va="center", +) +axes[1].plot( + [t2s_fit, t2s_fit, 0], + [0, s0_fit / np.e, s0_fit / np.e], + color="blue", + linestyle="--", +) +axes[1].annotate( + ( + f"At TE = $T_2^*$ = {t2s_fit:.1f} ms,\n" + "the signal has decayed to\n" + f"1/e (37%) of $S_0$" + ), + xy=(t2s_fit, s0_fit / np.e), + xytext=(15, s0_fit * 0.12), + fontsize=14, + arrowprops=dict(arrowstyle="->", color="blue"), +) +axes[1].set_title("B. The same fit as an exponential curve", fontsize=18, loc="left") +axes[1].set_ylabel("Signal", fontsize=16) +axes[1].set_ylim(0, np.ceil(s0_fit / 1000) * 1000 + 1000) + +for ax in axes: + ax.set_xlabel("Echo Time (ms)", fontsize=16) + ax.set_xlim(0, 120) + ax.set_xticks(np.round(tes_ms, 1)) + ax.tick_params(axis="both", which="major", labelsize=12) + +fig.tight_layout() +glue_figure("fig_decay_fit", fig, display=False) +``` + +```{figure} figures/fig_decay_fit.png +:name: fig_decay_fit +:align: center -Firstly, let us run some code to simulate the signal decay curve. +The monoexponential model fit to one voxel. +(A) After a log transform, the signal falls on a straight line, +whose intercept and slope give $S_{0}$ and $R_{2}^{*}$. +(B) The same fit, shown on the original scale. +The red star marks $S_{0}$, and the dashed blue lines mark $T_{2}^{*}$, +the echo time at which the signal has decayed to 37% of $S_{0}$. +``` + +For this voxel, the fit gives $S_{0}$ ≈ {glue:text}`s0_fit:.0f` and $T_{2}^{*}$ ≈ {glue:text}`t2s_fit:.1f` ms. +$T_{2}^{*}$ has a simple interpretation: +it is the echo time at which the signal has decayed to $1/e$, or about 37%, of $S_{0}$. +This voxel's $T_{2}^{*}$ is longer than is typical for gray matter at 3T (roughly 40-55 ms). +We chose the voxel because it has strong BOLD fluctuations, not because its decay is typical, +and [](T2star_S0_Variability.md) describes why $T_{2}^{*}$ varies so much from voxel to voxel. + +### Noise across echoes + +Every measurement also contains thermal noise, whose amplitude is roughly the same at every echo time. +Because the signal decays, the same amount of noise is a larger fraction of the signal at later echoes, +so later echoes have a lower signal-to-noise ratio. +This has a few consequences: + +- In panel A of {numref}`fig_decay_fit`, the log-transformed points spread out more at later echoes. + Part of that spread is BOLD fluctuation, which also grows with echo time as a fraction of the signal (as we will see below), + but part of it is noise. +- MRI magnitude images cannot be negative, so once the signal has decayed to the level of the noise, + the measured values level off instead of continuing to fall. + Echoes at this "noise floor" make the decay look slower than it really is. +- Fitting the decay to a single volume, with only a handful of noisy measurements, + gives much noisier estimates than fitting all of the volumes at once, as we did here. + +There are two more things to keep in mind. +First, the fit is only as good as the echoes that go into it. +In regions with strong signal dropout, such as orbitofrontal cortex, +the later echoes contain almost nothing but noise, +so `tedana` builds an *adaptive mask* that limits the fit in each voxel to the echoes with good signal +(see [](TE_Dependence.md)). +Second, the values we estimated here describe the voxel's *average* decay. +In the next section, we look at how $S_{0}$ and $T_{2}^{*}$ change from one volume to the next, +and why we need multiple echoes to tell those changes apart. + +## The impact of $T_{2}^{*}$ and $S_{0}$ fluctuations on BOLD signal + +In this section, we use simulations to investigate the two factors that drive changes in the signal decay pattern: +$T_{2}^{*}$ and $S_{0}$. +We simulate a voxel with an average $S_{0}$ of 16000 and an average $T_{2}^{*}$ of 45 ms, +a typical value for gray matter at 3T, +and a single-echo acquisition with an echo time of 30 ms, which is common for single-echo fMRI at 3T. ```{code-cell} ipython3 -# Simulate data +# The echo time of a typical single-echo scan at 3T SINGLEECHO_TE = np.array([30]) -# For a nice, smooth curve +# Echo times for a nice, smooth curve FULLCURVE_TES = np.round(np.arange(0, 121, 1), decimals=5) -n_echoes = len(FULLCURVE_TES) -pal = sns.color_palette("cubehelix", 8) +MEAN_T2S = 45 +MEAN_S0 = 16000 ``` ### Simulate $T_{2}^{*}$ and $S_{0}$ fluctuations +Next, we simulate a short run of 21 volumes, in which $T_{2}^{*}$ and $S_{0}$ fluctuate over time. +To make the fluctuations easy to see, they are much larger (10%) than real fluctuations, which are a few percent or less. + ```{code-cell} ipython3 -# Simulate data # We'll convolve with HRF just for smoothness hrf = first_level.spm_hrf(1, oversampling=1) N_VOLS = 21 SCALING_FRACTION = 0.1 # used to scale standard deviation -MEAN_T2S = 35 -MEAN_S0 = 16000 -# simulate the T2*/S0 time series -# The original time series will be a random time series from a normal distribution, -# convolved with the HRF +# Simulate the relative T2*/S0 fluctuations. +# The original time series is random noise from a normal distribution, +# convolved with the HRF. rng = np.random.default_rng(42) ts = rng.normal(loc=0, scale=1, size=(N_VOLS + 20,)) ts = signal.convolve(ts, hrf)[20 : N_VOLS + 20] @@ -280,11 +470,11 @@ t2s_ts = (ts * MEAN_T2S) + MEAN_T2S s0_ts = (ts * MEAN_S0) + MEAN_S0 ``` -#### Plot BOLD signal decay for a standard single-echo scan +#### BOLD signal decay for a standard single-echo scan ```{code-cell} ipython3 :tags: [hide-cell] -fullcurve_signal = predict_bold_signal(FULLCURVE_TES, [MEAN_S0], [30]) +fullcurve_signal = predict_bold_signal(FULLCURVE_TES, [MEAN_S0], [MEAN_T2S]) fig, ax = plt.subplots(figsize=(14, 7.5)) ax.plot( @@ -294,13 +484,13 @@ ax.plot( color="black", ) # Example for TE=30ms -x_cross = 30 -y_cross = predict_bold_signal(np.array([x_cross]), [MEAN_S0], [30])[0, 0] -ax.plot(x_cross, y_cross, marker='x', color='red', markersize=10, label='TE=30 ms') -ax.axvline(x=x_cross, ymax=y_cross[0], color='red', linestyle='--', alpha=0.3) -ax.axhline(y=y_cross, xmax=x_cross, color='red', linestyle='--', alpha=0.3) +x_cross = SINGLEECHO_TE[0] +y_cross = float(np.squeeze(predict_bold_signal(np.array([x_cross]), [MEAN_S0], [MEAN_T2S]))) +glue("singleecho_value", y_cross, display=False) +ax.plot(x_cross, y_cross, marker="x", color="red", markersize=10, label="TE = 30 ms") +ax.plot([x_cross, x_cross, 0], [0, y_cross, y_cross], color="red", linestyle="--", alpha=0.5) -ax.set_ylabel("Recorded BOLD signal", fontsize=24) +ax.set_ylabel("Signal", fontsize=24) ax.set_xlabel("Echo Time (ms)", fontsize=24) ax.set_ylim(0, np.ceil(np.max(fullcurve_signal) / 1000) * 1000) ax.set_xlim(0, np.max(FULLCURVE_TES)) @@ -313,52 +503,64 @@ glue_figure("fig_signal_decay_single-echo", fig, display=False) :name: fig_signal_decay_single-echo :align: center -BOLD signal decay for a standard single-echo scan +The signal decay curve for a voxel with $T_{2}^{*}$ = 45 ms (black), and the single value a single-echo scan with TE = 30 ms measures (red cross). ``` -At a given time point in an fMRI scan, the signal magnitude of a voxel varies depending on the echo time at which the signal is acquired. -Here, we observe how the signal decays as TE increases (black curve). -For example, if a single-echo scan is acquired at TE = 30 ms, the signal magnitude is approximately 5886 (red cross and dashed lines). +In every volume of an fMRI scan, each voxel's signal follows a decay curve like the black one, +but a single-echo scan only measures one point on that curve. +For example, if a single-echo scan is acquired at TE = 30 ms, +the signal is approximately {glue:text}`singleecho_value:.0f` (red cross and dashed lines). -### Plot BOLD signal decay and BOLD contrast +#### BOLD signal decay and BOLD contrast ```{code-cell} ipython3 :tags: [hide-cell] -fullcurve_signal_active = predict_bold_signal(FULLCURVE_TES, [MEAN_S0], [40]) -fullcurve_signal_inactive = predict_bold_signal(FULLCURVE_TES, [MEAN_S0], [20]) +# T2* is exaggerated in both directions, so that the difference is easy to see +T2S_LOW_ACTIVITY = 40 +T2S_HIGH_ACTIVITY = 50 +curve_active = np.squeeze(predict_bold_signal(FULLCURVE_TES, [MEAN_S0], [T2S_HIGH_ACTIVITY])) +curve_inactive = np.squeeze(predict_bold_signal(FULLCURVE_TES, [MEAN_S0], [T2S_LOW_ACTIVITY])) + +# The echo time at which the difference between the curves is largest +max_contrast_te = ( + np.log(T2S_HIGH_ACTIVITY / T2S_LOW_ACTIVITY) + / (1 / T2S_LOW_ACTIVITY - 1 / T2S_HIGH_ACTIVITY) +) +glue("max_contrast_te", float(max_contrast_te), display=False) fig, ax = plt.subplots(figsize=(14, 7.5)) ax.plot( FULLCURVE_TES, - fullcurve_signal_active[:, 0], - alpha=0.7, + curve_active, color="red", - label="High Activity", + label=f"High activity ($T_2^*$ = {T2S_HIGH_ACTIVITY} ms)", ) ax.plot( FULLCURVE_TES, - fullcurve_signal_inactive[:, 0], - alpha=0.7, + curve_inactive, color="blue", - label="Low Activity", + label=f"Low activity ($T_2^*$ = {T2S_LOW_ACTIVITY} ms)", ) -# vertical lines to explain how the contrast evolves -max_plot = np.ceil(np.max(fullcurve_signal) / 1000) * 1000 -# 10ms -ymin = np.round(fullcurve_signal_inactive[:, 0][10][0]/max_plot, decimals=5) -ymax = np.round(fullcurve_signal_active[:, 0][10][0]/max_plot, decimals=5) -ax.axvline(x=FULLCURVE_TES[10], ymin=ymin, ymax=ymax, color='green', linestyle='--', alpha=0.4) -# 30ms -ymin = np.round(fullcurve_signal_inactive[:, 0][30][0]/max_plot, decimals=5) -ymax = np.round(fullcurve_signal_active[:, 0][30][0]/max_plot, decimals=5) -ax.axvline(x=FULLCURVE_TES[30], ymin=ymin, ymax=ymax, color='green', linestyle='--', alpha=0.4) -# 50ms -ymin = np.round(fullcurve_signal_inactive[:, 0][50][0]/max_plot, decimals=5) -ymax = np.round(fullcurve_signal_active[:, 0][50][0]/max_plot, decimals=5) -ax.axvline(x=FULLCURVE_TES[50], ymin=ymin, ymax=ymax, color='green', linestyle='--', alpha=0.4) - -ax.set_ylabel("Recorded BOLD signal", fontsize=24) +# Vertical lines show the difference between the curves at a few echo times +for te in [15, int(np.round(max_contrast_te)), 90]: + ax.plot( + [te, te], + [curve_inactive[te], curve_active[te]], + color="green", + linewidth=3, + ) + ax.annotate( + f"{te} ms", + xy=(te, curve_active[te]), + xytext=(0, 10), + textcoords="offset points", + ha="center", + fontsize=14, + color="green", + ) + +ax.set_ylabel("Signal", fontsize=24) ax.set_xlabel("Echo Time (ms)", fontsize=24) ax.set_ylim(0, np.ceil(np.max(fullcurve_signal) / 1000) * 1000) ax.set_xlim(0, np.max(FULLCURVE_TES)) @@ -372,20 +574,30 @@ glue_figure("fig_signal_decay_contrast", fig, display=False) :name: fig_signal_decay_contrast :align: center -BOLD signal decay and BOLD contrast +Signal decay curves for a voxel at low activity (blue) and high activity (red). +The green lines show the difference between the curves at three echo times. ``` -This plot shows the signal decay for two different activity levels: one with high activity and one with low activity. -Due to differences in activity and the associated $T_{2}^{*}$ effects, the decay curve for low activity is steeper than that for high activity. -The contrast — represented by the distance between the two curves (see green dashed lines in the figure) — increases with TE, reaching a peak around TE = 30 ms, and then begins to decrease at longer echo times (e.g., >50 ms). -In practice, this means that for a given voxel, the contrast (i.e., the color difference) between low and high activity will be more visible at TE = 30 ms than at TE = 15 ms. +This plot shows the signal decay for two levels of activity. +When activity increases, blood oxygenation increases, so $T_{2}^{*}$ gets longer and the signal decays more slowly. +The difference in $T_{2}^{*}$ here (40 vs. 50 ms) is exaggerated to make it visible; +real BOLD changes in $T_{2}^{*}$ are a few percent. +The BOLD contrast is the difference between the two curves (green lines). +It is zero at TE = 0, grows as the echo time increases, +peaks at an echo time of about {glue:text}`max_contrast_te:.0f` ms, close to $T_{2}^{*}$, +and then shrinks again as both signals decay toward zero. +This is why single-echo fMRI uses an echo time that is close to the typical $T_{2}^{*}$ of gray matter. +Note that this is the *absolute* difference between the curves. +As a *fraction* of the signal, the difference keeps growing with echo time, +which becomes important in [](TE_Dependence.md). -### Plot single-echo data resulting from $S_{0}$ and $T_{2}^{*}$ fluctuations +### Single-echo data over time -Let us visualize the case of a single-echo fMRI acquisition with TE = 30ms. -The top panel shows the time series of an example voxel, while the lower panel shows the associated signal magnitude fluctuation at the specific echo time (TE = 30 ms). -This shows how fMRI data fluctuates over time. +Now let us add the fluctuations, starting with a single-echo acquisition at TE = 30 ms. +In the animation below, the bottom panel shows the signal measured at TE = 30 ms in each volume, +and the top panel shows the resulting time series. +This is what a single-echo fMRI time series is: one measurement per volume, at a single echo time. ```{code-cell} ipython3 :tags: [hide-cell] @@ -404,7 +616,7 @@ axes[0].set_xlim(0, N_VOLS - 1) axes[0].tick_params(axis="both", which="major", labelsize=14) axes[1].set_ylabel("Signal", fontsize=24) axes[1].set_xlabel("Echo Time (ms)", fontsize=24) -axes[1].set_xticks(data['echo_times']) +axes[1].set_xticks([0, 30, 60, 90, 120]) axes[1].set_ylim(0, np.ceil(np.max(fullcurve_signal) / 1000) * 1000) axes[1].set_xlim(0, np.max(FULLCURVE_TES)) axes[1].tick_params(axis="both", which="major", labelsize=14) @@ -460,13 +672,14 @@ glue("fig_single-echo", html, display=False) :name: fig_single-echo :align: center -Single-echo data resulting from $S_{0}$ and $T_{2}^{*}$ fluctuations +Single-echo data from a simulated voxel whose $S_{0}$ and $T_{2}^{*}$ fluctuate. Top: the time series measured at TE = 30 ms. Bottom: the measurement in the current volume. ``` -### Plot single-echo data and the curve resulting from $S_{0}$ and $T_{2}^{*}$ fluctuations +### Each single-echo measurement comes from a decay curve -Building on the previous figure, we visualize here how the signal of a voxel at each time point of a single-echo fMRI scan (TE=30ms) is part of a decay curve. -In other words, this shows how single-echo data is a sample from a signal decay curve. +Next, we add the full decay curve for each volume. +Each single-echo measurement is just one point on that volume's decay curve, +and the curve itself changes from volume to volume as $S_{0}$ and $T_{2}^{*}$ fluctuate. ```{code-cell} ipython3 :tags: [hide-cell] @@ -485,7 +698,7 @@ axes[0].set_xlim(0, N_VOLS - 1) axes[0].tick_params(axis="both", which="major", labelsize=14) axes[1].set_ylabel("Signal", fontsize=24) axes[1].set_xlabel("Echo Time (ms)", fontsize=24) -axes[1].set_xticks(data['echo_times']) +axes[1].set_xticks([0, 30, 60, 90, 120]) axes[1].set_ylim(0, np.ceil(np.max(fullcurve_signal) / 1000) * 1000) axes[1].set_xlim(0, np.max(FULLCURVE_TES)) axes[1].tick_params(axis="both", which="major", labelsize=14) @@ -554,21 +767,24 @@ glue("fig_signal_decay", html, display=False) :name: fig_signal_decay :align: center -Single-echo data and the curve resulting from $S_{0}$ and $T_{2}^{*}$ fluctuations +The same single-echo data, with the full decay curve of the current volume (gray). The single-echo measurement is one point on that curve. ``` -### Plot single-echo data, the curve, and the $S_{0}$ and $T_{2}^{*}$ values resulting from $S_{0}$ and $T_{2}^{*}$ fluctuations +### Where $S_{0}$ and $T_{2}^{*}$ sit on the curve -We are still in the case of a single-echo fMRI acquisition with TE=30ms. -For a given voxel, the signal magnitude $S$ is linked with $S_0$ and $T_2^{*}$ over time $t$ through the formula: +We are still looking at a single-echo acquisition with TE = 30 ms. +The decay model from the start of this chapter, written for volume $t$ and with noise added, is: ```{math} :label: monoexponential_decay_undeveloped_single_echo S(t, TE) = S_0(t) \times e^{\frac{-TE}{T_2^{*}(t)}} + noise ``` -Both factors of the product - $S_0$ and the exponential with $T_2^{*}$ - capture local fluctuations happening during MRI acquisition, but from different origins. -The figure represents how the signal of a voxel is associated with $S_0$ and $T_2^{*}$, showing how changes in fMRI data can be driven by both factors. +Both $S_{0}$ and $T_{2}^{*}$ can change from volume to volume, for different reasons, +and a change in either one changes the measured signal. +In the animation below, the red star marks $S_{0}$, where the curve meets $TE = 0$, +and the blue star marks the point on the curve at $TE = T_{2}^{*}$. +Both move as the fluctuations change the curve. ```{code-cell} ipython3 :tags: [hide-cell] @@ -638,7 +854,7 @@ axes[0].tick_params(axis="both", which="major", labelsize=14) axes[1].legend(loc="upper right", fontsize=20) axes[1].set_ylabel("Signal", fontsize=24) axes[1].set_xlabel("Echo Time (ms)", fontsize=24) -axes[1].set_xticks(data['echo_times']) +axes[1].set_xticks([0, 30, 60, 90, 120]) axes[1].set_ylim(0, np.ceil(np.max(fullcurve_signal) / 1000) * 1000) axes[1].set_xlim(0, np.max(FULLCURVE_TES)) axes[1].tick_params(axis="both", which="major", labelsize=14) @@ -701,17 +917,17 @@ glue("fig_signal_decay2", html, display=False) :name: fig_signal_decay2 :align: center -Single-echo data, the curve, and the $S_{0}$ and $T_{2}^{*}$ values resulting from $S_{0}$ and $T_{2}^{*}$ fluctuations +The same data, with $S_{0}$ (red star) and the point on the curve at $TE = T_{2}^{*}$ (blue star) marked in each volume. ``` -### Plot $S_{0}$ and $T_{2}^{*}$ fluctuations +### $S_{0}$ and $T_{2}^{*}$ fluctuations change the curve differently -Let us visualize $S_0$ and $T_2^{*}$ effects more closely. -The bottom figure shows how the $S_0$ and $T_2^{*}$ curves change compared to the original average signal decay curve. -In red, the decay curve is shown when only the $S_0$ values fluctuate (for a fixed $T_2^{*}$ for any t). -In blue, the decay curve is shown when the $T_2^{*}$ values fluctuate (for a fixed $S_0$ for any t). -The top panel represents the relative fluctuations shared by $S_0$ and $T_2^{*}$. -This shows how fluctuations in $S_0$ and $T_2^{*}$ produce different patterns in the full signal decay curves. +To see the two effects separately, we now let only one of them fluctuate at a time, using the same relative fluctuations for both. +The top panel shows the relative fluctuations over time. +In the bottom panel, the red curve is the decay curve when only $S_{0}$ fluctuates (with $T_{2}^{*}$ fixed), +and the blue curve is the decay curve when only $T_{2}^{*}$ fluctuates (with $S_{0}$ fixed). +A change in $S_{0}$ scales the whole curve up or down, including its starting point at $TE = 0$. +A change in $T_{2}^{*}$ leaves the starting point alone and changes how quickly the curve falls. ```{code-cell} ipython3 :tags: [hide-cell] @@ -767,14 +983,14 @@ ax1_t2s_line_plot = axes[1].plot( )[0] # Set constant params for figure -axes[0].set_ylabel("$S_0$/$T_{2}^{*}$", fontsize=24) +axes[0].set_ylabel("Relative change\nin $S_0$ or $T_2^*$", fontsize=18) axes[0].set_xlabel("Volume", fontsize=24) axes[0].set_xlim(0, N_VOLS - 1) axes[0].tick_params(axis="both", which="major", labelsize=14) axes[1].legend(loc="upper right", fontsize=20) axes[1].set_ylabel("Signal", fontsize=24) axes[1].set_xlabel("Echo Time (ms)", fontsize=24) -axes[1].set_xticks(data['echo_times']) +axes[1].set_xticks([0, 30, 60, 90, 120]) axes[1].set_ylim(0, np.ceil(np.max(s0based_fullcurve_signal) / 1000) * 1000) axes[1].set_xlim(0, np.max(FULLCURVE_TES)) axes[1].tick_params(axis="both", which="major", labelsize=14) @@ -815,14 +1031,16 @@ glue("fig_signal_decay3", html, display=False) :name: fig_signal_decay3 :align: center -$S_{0}$ and $T_{2}^{*}$ fluctuations +Decay curves when only $S_{0}$ fluctuates (red) or only $T_{2}^{*}$ fluctuates (blue), with the same relative fluctuations (top). The black curve is the average decay curve. ``` -### Plot $S_{0}$ and $T_{2}^{*}$ fluctuations and resulting single-echo data +### Single-echo data cannot tell the two apart -Let us visualize again the case of a single-echo acquisition. -Because the signal is acquired for only one TE (see the red and blue dot points in the figure), it is impossible to model the $S_0$- and $T_2^{*}$- driven curves! -This shows how single-echo data, on its own, cannot distinguish between $S_0$ and $T_2^{*}$ fluctuations. +Now let us measure both curves with a single-echo acquisition at TE = 30 ms (red and blue points). +The two points move up and down with the same timing, +even though they come from very different changes in the decay curve. +With only one echo, we see that the signal went up or down, +but we cannot tell whether $S_{0}$ or $T_{2}^{*}$ changed. ```{code-cell} ipython3 :tags: [hide-cell] @@ -883,14 +1101,14 @@ ax1_t2s_scatter_plot = axes[1].scatter( ) # Set constant params for figure -axes[0].set_ylabel("$S_0$/$T_{2}^{*}$", fontsize=24) +axes[0].set_ylabel("Relative change\nin $S_0$ or $T_2^*$", fontsize=18) axes[0].set_xlabel("Volume", fontsize=24) axes[0].set_xlim(0, N_VOLS - 1) axes[0].tick_params(axis="both", which="major", labelsize=14) axes[1].legend(loc="upper right", fontsize=20) axes[1].set_ylabel("Signal", fontsize=24) axes[1].set_xlabel("Echo Time (ms)", fontsize=24) -axes[1].set_xticks(data['echo_times']) +axes[1].set_xticks([0, 30, 60, 90, 120]) axes[1].set_ylim(0, np.ceil(np.max(s0based_fullcurve_signal) / 1000) * 1000) axes[1].set_xlim(0, np.max(FULLCURVE_TES)) axes[1].tick_params(axis="both", which="major", labelsize=14) @@ -947,13 +1165,76 @@ glue("fig_signal_decay4", html, display=False) :name: fig_signal_decay4 :align: center -$S_{0}$ and $T_{2}^{*}$ fluctuations and resulting single-echo data +The $S_{0}$-driven (red) and $T_{2}^{*}$-driven (blue) decay curves, measured at a single echo time (TE = 30 ms). +``` + +The same point can be made with time series. +In the figure below, the measured single-echo signal is plotted against the $T_{2}^{*}$ or $S_{0}$ fluctuations that produced it, +after scaling them to the same units. +When only $S_{0}$ fluctuates, the signal is exactly a scaled copy of $S_{0}$, +because $S$ is proportional to $S_{0}$ in {eq}`monoexponential_decay_undeveloped_single_echo`. +When only $T_{2}^{*}$ fluctuates, the signal is *almost* a scaled copy of $T_{2}^{*}$; +the small differences come from the exponential, which is not linear in $T_{2}^{*}$. +Since we never observe the underlying fluctuations in real data, +the single-echo time series alone does not tell us which of the two produced it. + +```{code-cell} ipython3 +:tags: [hide-cell] +fig, axes = plt.subplots(1, 2, figsize=(16, 4.5), sharey=True) +volumes = np.arange(N_VOLS) +for ax, (label, param_ts, signal_ts, color) in zip( + axes, + [ + ("$T_2^*$", t2s_ts, t2sbased_fullcurve_signal[SINGLEECHO_TE[0], :], "blue"), + ("$S_0$", s0_ts, s0based_fullcurve_signal[SINGLEECHO_TE[0], :], "red"), + ], +): + # Scale the parameter's fluctuations to the units of the signal + centered = param_ts - param_ts.mean() + scalar = np.linalg.lstsq(centered[:, None], signal_ts - signal_ts.mean(), rcond=None)[0] + ax.plot( + volumes, + signal_ts, + color="black", + linewidth=4, + alpha=0.4, + label=f"Signal at TE = {SINGLEECHO_TE[0]} ms", + ) + ax.plot( + volumes, + np.round(centered * scalar + signal_ts.mean(), decimals=5), + color=color, + linestyle="--", + label=f"{label} (scaled to the signal)", + ) + ax.set_title(f"Only {label} fluctuates", fontsize=16) + ax.set_xlabel("Volume", fontsize=14) + ax.set_xlim(0, N_VOLS - 1) + ax.set_xticks(np.arange(0, N_VOLS, 5)) + ax.legend(fontsize=12) + +axes[0].set_ylabel("Signal", fontsize=14) +fig.tight_layout() +glue_figure("fig_t2s_s0_bold_single-echo", fig, display=False) +``` + +```{figure} figures/fig_t2s_s0_bold_single-echo.png +:name: fig_t2s_s0_bold_single-echo +:align: center + +Single-echo signal (gray) when only $T_{2}^{*}$ (left) or only $S_{0}$ (right) fluctuates, +compared with those fluctuations scaled to the units of the signal (dashed). ``` -### Plot $S_{0}$ and $T_{2}^{*}$ fluctuations and resulting multi-echo data +### Multi-echo data can tell the two apart -Let us now visualize again the case of a multi-echo acquisition. -Because the signal is acquired at five echo times here, we can see how S0 and T2* fluctuations produce different patterns in multi-echo data. It is now possible to model the $S_0$- and $T_2^{*}$- driven curves from the signal! +Finally, let us measure the same curves at the five echo times of our real data. +Now the two kinds of fluctuation produce clearly different patterns across echoes. +When $S_{0}$ changes, the red points all move by the same *fraction* of their value, +so the change is largest at the first echo. +When $T_{2}^{*}$ changes, the blue points barely move at the first echo and move much more at later echoes. +With several echoes, we could, in principle, fit the decay curve in each volume, as we did for the real voxel above, +and tell which parameter changed. ```{code-cell} ipython3 :tags: [hide-cell] @@ -1017,7 +1298,7 @@ ax1_t2s_scatter_plot = axes[1].scatter( zorder=3, ) -axes[0].set_ylabel("$S_0$/$T_{2}^{*}$", fontsize=24) +axes[0].set_ylabel("Relative change\nin $S_0$ or $T_2^*$", fontsize=18) axes[0].set_xlabel("Volume", fontsize=24) axes[0].set_xlim(0, N_VOLS - 1) axes[0].tick_params(axis="both", which="major", labelsize=14) @@ -1081,73 +1362,22 @@ glue("fig_signal_decay5", html, display=False) :name: fig_signal_decay5 :align: center -$S_{0}$ and $T_{2}^{*}$ fluctuations and resulting multi-echo data -``` - -#### Plot $T_{2}^{*}$ against BOLD signal from single-echo data (TE=30ms) - -When the BOLD signal is driven entirely by $T_2^{*}$ fluctuations, the BOLD signal is very similar to a scaled version of those $T_2^{*}$ fluctuations, but there are small differences. -You may understand this intuitively by looking back to the equation {eq}`monoexponential_decay_undeveloped_single_echo`. You can see that if $S_0$ is fixed, the relationship between $S$ and $T_2^{*}$ is not purely linear over time. - -```{code-cell} ipython3 -:tags: [hide-cell] -fig, ax = plt.subplots(figsize=(16, 4)) - -scalar = np.linalg.lstsq( - t2s_ts[:, None], t2sbased_fullcurve_signal[SINGLEECHO_TE[0], :], rcond=None -)[0] -ax.plot( - t2sbased_fullcurve_signal[SINGLEECHO_TE[0], :], - color="orange", - label=f"BOLD signal (TE={SINGLEECHO_TE[0]}ms)", -) -ax.plot( - np.round(t2s_ts * scalar, decimals=5), - label="$T_{2}^{*}$ (scaled to signal)", - linestyle="--", -) -ax.set_xlim(0, N_VOLS - 1) -leg = ax.legend() -glue_figure("fig_t2s_bold_single-echo", fig, display=False) -``` - -```{figure} figures/fig_t2s_bold_single-echo.png -:name: fig_t2s_bold_single-echo -:align: center - -$T_{2}^{*}$ against BOLD signal from single-echo data (TE=30ms) +The $S_{0}$-driven (red) and $T_{2}^{*}$-driven (blue) decay curves, measured at five echo times. ``` -#### Plot $S_{0}$ against BOLD signal from single-echo data (TE=30ms) - -When the BOLD signal is driven entirely by $S_0$ fluctuations, the BOLD signal ends up being a scaled version of the $S_0$ fluctuations. -You may understand this intuitively by looking back to the equation {eq}`monoexponential_decay_undeveloped_single_echo`. You can see that if $T_2^{*}$ is fixed, the relationship between $S$ and $S_0$ is linear over time. -```{code-cell} ipython3 -:tags: [hide-cell] -fig, ax = plt.subplots(figsize=(16, 4)) +## Summary -scalar = np.linalg.lstsq( - s0_ts[:, None], s0based_fullcurve_signal[SINGLEECHO_TE[0], :], rcond=None -)[0] -ax.plot( - s0based_fullcurve_signal[SINGLEECHO_TE[0], :], - color="orange", - label=f"BOLD signal (TE={SINGLEECHO_TE[0]}ms)", -) -ax.plot( - np.round(s0_ts * scalar, decimals=5), - label="S0 (scaled to signal)", - linestyle="--", -) -ax.set_xlim(0, N_VOLS - 1) -leg = ax.legend() -glue_figure("fig_s0_bold_single-echo", fig, display=False) -``` +- MR signal decays with echo time following, approximately, $S(TE) = S_{0} e^{-TE / T_{2}^{*}}$. + With several echoes, we can estimate $S_{0}$ and $T_{2}^{*}$ by fitting a straight line to the log of the signal. +- The BOLD effect changes $T_{2}^{*}$, while many sources of noise change $S_{0}$. +- A single-echo scan measures one point on the decay curve in each volume, + so it cannot tell a change in $S_{0}$ from a change in $T_{2}^{*}$. +- With multiple echoes, the two kinds of change leave different fingerprints: + an $S_{0}$ change is the same fraction of the signal at every echo time, + while a $T_{2}^{*}$ change grows, as a fraction of the signal, with echo time. -```{figure} figures/fig_s0_bold_single-echo.png -:name: fig_s0_bold_single-echo -:align: center - -$S_{0}$ against BOLD signal from single-echo data (TE=30ms) -``` +In practice, the signal in a single volume is too noisy to fit the decay curve reliably. +[](TE_Dependence.md) shows how `tedana` uses these fingerprints on components of the data instead, +to separate BOLD from non-BOLD signal. +Before that, [](T2star_S0_Variability.md) looks at why the *average* $T_{2}^{*}$ and $S_{0}$ vary so much across the brain. diff --git a/content/TE_Dependence.md b/content/TE_Dependence.md index 7597caf5..f0c5bd9a 100644 --- a/content/TE_Dependence.md +++ b/content/TE_Dependence.md @@ -12,38 +12,12 @@ kernelspec: # BOLD, non-BOLD, and TE-dependence with tedana -```{important} -This chapter should differentiate itself from Signal_Decay by focusing on the application of {eq}`monoexponential_decay` -to decompositions, rather than raw signal compared between active and inactive states. - -We may want to describe adaptive masking, data whitening, the model fit metrics, and post-processing methods (e.g., MIR) -in this page as well. -``` - -```{important} -The general flow of this chapter should be: - -1. Explain the monoexponential decay equation, but primarily reference back to Signal_Decay. -2. Walk through optimal combination and adaptive masking somewhere around here. -3. Describe why multi-echo denoising can't be done directly to the raw signal and why ICA is necessary. - 1. This means talking about noise, really, and why the FIT method (volume-wise T2*/S0 estimation) - is generally considered too noisy for practical application. - 2. Walk through TEDPCA as well. -4. The TE-(in)dependence models. -5. Apply the models to a simulated component, as well as multiple real components. - 1. Show model fit for different components. -6. Compare optimally combined, denoised, and high-kappa data. -7. Describe post-processing methods, like minimum image regression and tedana's version of global signal regression. -``` - -This notebook uses simulated T2*/S0 manipulations to show how TE-dependence is leveraged to denoise multi-echo data. - -The equation for how signal is dependent on changes in S0 and T2*: - -```{math} -:label: monoexponential_decay -S(t, TE_k) = \bar{S}(TE_k) * (1 + \frac{{\Delta}{S_0}(t)}{\bar{S}_0} - {\Delta}{R_2^*}(t)*TE_k) -``` +In [](Signal_Decay.md), we saw that changes in $S_{0}$ and changes in $T_{2}^{*}$ affect multi-echo data in different ways, +and that this is what lets multi-echo data tell them apart. +This chapter turns that observation into a test. +We first work out how each kind of change depends on echo time, +then use simulations to build two models that `tedana` fits to its components, +and finally follow the same ideas through `tedana`'s processing of a real multi-echo run. ```{code-cell} ipython3 :tags: [hide-cell] @@ -51,15 +25,20 @@ import json import os from glob import glob +import matplotlib import matplotlib.pyplot as plt import nibabel as nb +import nitransforms as nit import numpy as np +import pandas as pd import seaborn as sns from book_utils import ( compute_te_dependence_statistics, glue_figure, - predict_bold_signal, + load_pafin, ) +from myst_nb import glue +from nilearn import image, masking, plotting from nilearn.glm import first_level from scipy import signal, stats @@ -71,124 +50,136 @@ out_dir = os.path.join(data_path, "te-dependence") os.makedirs(out_dir, exist_ok=True) ``` -```{code-cell} ipython3 -:tags: [hide-cell] -# Simulate data -# For a nice, smooth curve -echo_times = np.round(np.arange(0, 201, 1), decimals=5) +## How signal changes depend on echo time -n_echoes = len(echo_times) -pal = sns.color_palette("cubehelix", 8) +Recall the monoexponential decay model from [](Signal_Decay.md), now written for volume $t$: -mean_s0 = 16000 -mean_t2s = 30 +```{math} +:label: monoexponential_decay_volume +S(t, TE) = S_{0}(t) \, e^{-TE \cdot R_{2}^{*}(t)} +``` + +Let $\bar{S}_{0}$ and $\bar{R}_{2}^{*}$ be the average values of $S_{0}$ and $R_{2}^{*}$ over the run, +and let ${\Delta}S_{0}(t)$ and ${\Delta}R_{2}^{*}(t)$ be how far they are from those averages in volume $t$. +The average signal at each echo time is then $\bar{S}(TE) = \bar{S}_{0} e^{-TE \cdot \bar{R}_{2}^{*}}$. -frac = 0.2 -s02 = mean_s0 + (mean_s0 * frac) -t2s2 = mean_t2s + (mean_t2s * frac) +Real fluctuations in $S_{0}$ and $R_{2}^{*}$ are small, typically a few percent or less. +When they are small, a first-order Taylor expansion of {eq}`monoexponential_decay_volume` gives a simple, linear approximation: -mean_sig = np.round(np.squeeze(predict_bold_signal(echo_times, mean_s0, mean_t2s)), decimals=5) +```{math} +:label: monoexponential_decay +S(t, TE) \approx \bar{S}(TE) \left(1 + \frac{{\Delta}S_{0}(t)}{\bar{S}_{0}} - {\Delta}R_{2}^{*}(t) \cdot TE\right) +``` -# Signal with fluctuating S0 -sig2 = np.round(np.squeeze(predict_bold_signal(echo_times, s02, mean_t2s)), decimals=5) -d_sig2 = sig2 - mean_sig -dt_sig2 = np.round(d_sig2 / ((sig2 + mean_sig) / 2.0), decimals=5) +Subtracting $\bar{S}(TE)$ and dividing by it gives the fractional signal change at each echo time: -# Signal with fluctuating T2* -sig3 = np.round(np.squeeze(predict_bold_signal(echo_times, mean_s0, t2s2)), decimals=5) -d_sig3 = sig3 - mean_sig -dt_sig3 = np.round(d_sig3 / ((sig3 + mean_sig) / 2.0), decimals=5) +```{math} +:label: fractional_signal_change +\frac{{\Delta}S(t, TE)}{\bar{S}(TE)} \approx \frac{{\Delta}S_{0}(t)}{\bar{S}_{0}} - {\Delta}R_{2}^{*}(t) \cdot TE ``` -## Plot simulations of BOLD and non-BOLD signals as a function of echo time +This equation is the basis of multi-echo denoising. +A change in $S_{0}$ produces the *same* fractional change at every echo time. +A change in $R_{2}^{*}$, which is how the BOLD effect shows up, produces a fractional change that is zero at $TE = 0$ +and grows in proportion to the echo time. + +The figure below shows both kinds of change for a voxel with $\bar{S}_{0} = 16000$ and $\bar{T}_{2}^{*} = 45$ ms, +a typical value for gray matter at 3T. +In the left column, $S_{0}$ increases by 5%. +In the right column, $T_{2}^{*}$ increases by 5%, as it would when local blood oxygenation increases. ```{code-cell} ipython3 :tags: [hide-cell] -# change s0 -fig, axes = plt.subplots(3, 2, sharex=True, figsize=(16, 6)) -axes[0, 0].yaxis.tick_right() -axes[0, 0].set_xticklabels([]) -axes[0, 0].plot(echo_times, mean_sig, "red", label="Mean signal") -axes[0, 0].plot(echo_times, sig2, "blue", label="Timepoint's signal") -axes[0, 0].set_ylim(0) -axes[0, 0].set_title("Change in S0", fontsize=20, y=1.02) -axes[0, 0].set_ylabel( - "Signal\n$S(TE_n)$", fontsize=16, rotation=0, labelpad=40, va="center" -) -leg = axes[0, 0].legend() - -axes[1, 0].yaxis.tick_right() -axes[1, 0].set_xticklabels([]) -axes[1, 0].plot(echo_times, d_sig2, "red") -axes[1, 0].set_ylim(0) -axes[1, 0].set_ylabel( - "${\\Delta}S(TE_n)$", fontsize=16, rotation=0, labelpad=40, va="center" -) +def decay(tes, s0, t2s): + """Monoexponential decay, with echo times and T2* in milliseconds.""" + return s0 * np.exp(-tes / t2s) -# No slope, intercept at delta(S0)/mean(S0) -axes[2, 0].yaxis.tick_right() -axes[2, 0].plot(echo_times, dt_sig2, "red") -axes[2, 0].set_ylabel( - "$\\frac{{\\Delta}S(TE_n)}{\\bar{S}(TE_n)}$", - fontsize=24, - rotation=0, - labelpad=40, - va="center", -) -axes[2, 0].set_xlabel("Echo Time (ms)", fontsize=16) - -# change t2s -# max diff is between orig and new T2*, but is definitely not mean -max_diff_te = echo_times[d_sig3 == np.max(d_sig3)][0] - -axes[0, 1].yaxis.tick_right() -axes[0, 1].set_xticklabels([]) -axes[0, 1].plot(echo_times, mean_sig, "red", label="Mean signal") -axes[0, 1].plot(echo_times, sig3, "blue", label="Timepoint's signal") -axes[0, 1].set_ylim(0) -axes[0, 1].set_title("Change in T2*", fontsize=20, y=1.02) - -# Plot important echo times -axes[0, 1].axvline(mean_t2s, color="green", alpha=0.5) -axes[0, 1].axvline(max_diff_te, color="gray", alpha=0.5) -axes[0, 1].axvline(t2s2, color="orange", alpha=0.5) -leg = axes[0, 1].legend() - -axes[1, 1].yaxis.tick_right() -axes[1, 1].set_xticklabels([]) -axes[1, 1].plot(echo_times, d_sig3, "red") -axes[1, 1].set_ylim(0) - -# Plot important echo times -axes[1, 1].axvline(mean_t2s, label="T2* of mean data", color="green", alpha=0.5) -axes[1, 1].axvline( - max_diff_te, label="TE of maximized contrast", color="gray", alpha=0.5 -) -axes[1, 1].axvline(t2s2, label="T2* of timepoint's data", color="orange", alpha=0.5) -leg = axes[1, 1].legend() - -pred_slope = (dt_sig3[-1] - dt_sig3[0]) / (echo_times[-1] - echo_times[0]) -pred_int = (pred_slope * echo_times[-1]) - dt_sig3[-1] -pred_max = pred_slope * echo_times[-1] - -axes[2, 1].yaxis.tick_right() -axes[2, 1].plot(echo_times, dt_sig3, "red") -axes[2, 1].plot( - [0, echo_times[-1]], - [pred_int, pred_max], - "black", - linestyle="--", - label="Theoretical line", + +# Echo times for smooth curves +dense_tes = np.arange(0, 120.5, 0.5) +# The five echo times of the dataset used in this book, rounded to 0.1 ms +sim_tes = np.array([14.2, 38.9, 63.7, 88.4, 113.1]) + +mean_s0 = 16000 +mean_t2s = 45 +frac = 0.05 + +mean_sig = decay(dense_tes, mean_s0, mean_t2s) +s0_sig = decay(dense_tes, mean_s0 * (1 + frac), mean_t2s) +t2s_sig = decay(dense_tes, mean_s0, mean_t2s * (1 + frac)) +delta_r2s = 1 / (mean_t2s * (1 + frac)) - 1 / mean_t2s + +cases = [ + { + "title": "$S_0$ increases by 5%", + "signal": s0_sig, + "approx": np.full(dense_tes.shape, frac), + "color": "red", + }, + { + "title": "$T_2^*$ increases by 5%", + "signal": t2s_sig, + "approx": -delta_r2s * dense_tes, + "color": "blue", + }, +] + +fig, axes = plt.subplots(3, 2, sharex=True, figsize=(14, 10)) +for col, case in enumerate(cases): + delta = case["signal"] - mean_sig + + # Row 1: the signal itself + axes[0, col].plot(dense_tes, mean_sig, color="black", label="Average signal, $\\bar{S}(TE)$") + axes[0, col].plot( + dense_tes, + case["signal"], + color=case["color"], + linestyle="--", + label="Signal after the change", + ) + axes[0, col].set_title(case["title"], fontsize=18) + axes[0, col].set_ylim(0, None) + axes[0, col].legend(fontsize=11) + + # Row 2: the absolute change + axes[1, col].plot(dense_tes, delta, color=case["color"]) + axes[1, col].set_ylim(0, None) + + # Row 3: the fractional change + axes[2, col].plot( + dense_tes, + 100 * delta / mean_sig, + color=case["color"], + linewidth=5, + alpha=0.4, + label="Exact", + ) + axes[2, col].plot( + dense_tes, + 100 * case["approx"], + color="black", + linestyle="--", + label="First-order approximation", + ) + axes[2, col].set_ylim(0, 15) + axes[2, col].set_xlabel("Echo Time (ms)", fontsize=14) + axes[2, col].legend(fontsize=11, loc="upper left") + +# Mark T2* in the absolute change panel for the T2* change +axes[1, 1].axvline(mean_t2s, color="gray", linestyle=":") +axes[1, 1].annotate( + "TE = $T_2^*$", + xy=(mean_t2s, 0.1), + xycoords=("data", "axes fraction"), + xytext=(5, 0), + textcoords="offset points", + fontsize=12, ) -axes[2, 1].set_ylim(0, None) -axes[2, 1].set_xlim(0, np.max(echo_times)) -# axes[2, 1].set_xticks(echo_times) -axes[2, 1].set_xlabel("Echo Time (ms)", fontsize=16) -axes[2, 1].axvline(max_diff_te, color="gray", alpha=0.5) -axes[2, 1].axvline(mean_t2s, color="green", alpha=0.5) -axes[2, 1].axvline(t2s2, color="orange", alpha=0.5) -leg = axes[2, 1].legend() +axes[0, 0].set_ylabel("Signal", fontsize=14) +axes[1, 0].set_ylabel("Signal change,\n${\\Delta}S(TE)$", fontsize=14) +axes[2, 0].set_ylabel("Percent signal change,\n${\\Delta}S(TE) / \\bar{S}(TE)$", fontsize=14) +axes[2, 0].set_xlim(0, dense_tes.max()) fig.tight_layout() glue_figure("fig_bold_nonbold_simulations", fig, display=False) ``` @@ -197,382 +188,806 @@ glue_figure("fig_bold_nonbold_simulations", fig, display=False) :name: fig_bold_nonbold_simulations :align: center -Simulations of BOLD and non-BOLD signals as a function of echo time +How a 5% increase in $S_{0}$ (left) or $T_{2}^{*}$ (right) changes the signal at each echo time. +Top: the average signal and the signal after the change. +Middle: the absolute signal change. +Bottom: the percent signal change, computed exactly (thick line) and with the first-order approximation in {eq}`fractional_signal_change` (dashed line). ``` -## Make design matrices +There are a few things to notice in this figure. + +- **Top row:** realistic changes are small, so the curves before and after the change nearly overlap. +- **Middle row:** the absolute changes differ in shape. + The $S_{0}$ change is largest at $TE = 0$ and shrinks as the signal decays. + The $T_{2}^{*}$ change is zero at $TE = 0$, peaks near $TE = T_{2}^{*}$, and then shrinks. + This peak is why single-echo fMRI uses an echo time close to the typical $T_{2}^{*}$ of gray matter, + and why the optimal combination weights echoes by $TE \cdot e^{-TE / T_{2}^{*}}$ + (see [](01_Optimal_Combination_with_t2smap.md)). +- **Bottom row:** the percent signal change makes the difference obvious. + The $S_{0}$ change is 5% at every echo time, while the $T_{2}^{*}$ change grows in proportion to the echo time, + following a straight line through the origin. + The first-order approximation (dashed) is very close to the exact change, because the change is small. -For TEDPCA and TEDICA, we use regression to get parameter estimates (PEs; not beta values) -for component time-series against echo-specific data, and substitute those PEs for ${\bar{S}(TE_k)}$. -At some point, I would like to dig into why those parameter estimates are equivalent to ${\bar{S}(TE_k)}$ for our purposes. +## The TE-dependence and TE-independence models -## TE-independence model +In real data, we never observe ${\Delta}S_{0}$ and ${\Delta}R_{2}^{*}$ directly. +What we *can* measure is how large a given fluctuation is at each of our echo times, ${\Delta}S(TE_k)$, +where $TE_k$ is the $k$-th of our $n$ echo times. +Multiplying {eq}`fractional_signal_change` by $\bar{S}(TE_k)$ gives two candidate explanations for those measurements. + +If the fluctuation comes from a change in $S_{0}$, then ```{math} -:label: te_independence_model1 -\frac{{\Delta}S(TE_k)}{\bar{S}(TE_k)} = \frac{{\Delta}S_0}{S_0} +:label: te_independence_model +{\Delta}S(TE_k) = \bar{S}(TE_k) \cdot X_{S_0}, \qquad X_{S_0} = \frac{{\Delta}S_{0}}{\bar{S}_{0}} ``` +If the fluctuation comes from a change in $R_{2}^{*}$, then + ```{math} -:label: te_independence_model2 -{\Delta}S(TE_k) = {\bar{S}(TE_k)}\frac{{\Delta}S_0}{S_0} +:label: te_dependence_model +{\Delta}S(TE_k) = \bar{S}(TE_k) \cdot TE_k \cdot X_{R_2^*}, \qquad X_{R_2^*} = -{\Delta}R_{2}^{*} ``` -$\frac{{\Delta}S_0}{S_0}$ is a scalar (i.e., doesn't change with TE), so we ignore that, -which means we only use ${\bar{S}(TE_k)}$ (mean echo-wise signal). +The first is called the *TE-independence* (or $S_{0}$) model, because the fractional change does not depend on echo time, +and the second is called the *TE-dependence* (or $R_{2}^{*}$) model. +Each model is a regression with a single regressor and no intercept. +The regressor is known: it is built from the average signal at each echo, $\bar{S}(TE_k)$, and the echo times themselves. +The coefficient, $X_{S_0}$ or $X_{R_2^*}$, is unknown, and is estimated with least squares. -Thus, +To measure how well each model fits, `tedana` computes an F-statistic, ```{math} -:label: te_independence_model3 -{\Delta}S(TE_k) = {\bar{S}(TE_k)} * X +:label: te_model_fstat +F = \frac{\sum_k {\Delta}S(TE_k)^2 - SSE}{SSE / (n - 1)} ``` -and for TEDPCA/TEDICA, +where $SSE$ is the sum of squared residuals of the model fit. +The better the model explains the measurements, the smaller $SSE$ is and the larger $F$ is. -```{math} -:label: te_independence_model4 -PE(TE_k) = {\bar{S}(TE_k)} * X -``` +Below, we fit both models to the two simulated changes from {numref}`fig_bold_nonbold_simulations`, +measured at the five echo times of our real data, +with a small amount of random noise added to each measurement. -Lastly, we fit X to the data and evaluate model fit. +```{code-cell} ipython3 +:tags: [hide-cell] +def fit_te_models(delta_s, avg_signal, tes): + """Fit the TE-independence (S0) and TE-dependence (R2*) models. + + Parameters + ---------- + delta_s : numpy.ndarray of shape (n_echoes,) + Signal change at each echo time. + avg_signal : numpy.ndarray of shape (n_echoes,) + Average signal at each echo time. + tes : numpy.ndarray of shape (n_echoes,) + Echo times, in milliseconds. + + Returns + ------- + dict + The coefficient and F-statistic of each model. + """ + n = len(tes) + total = np.sum(delta_s ** 2) + results = {} + for name, regressor in [("S0", avg_signal), ("R2", avg_signal * tes)]: + coef = np.sum(delta_s * regressor) / np.sum(regressor ** 2) + sse = np.sum((delta_s - coef * regressor) ** 2) + results[name] = {"coef": coef, "F": (total - sse) * (n - 1) / sse} + + return results -## TE-dependence model -```{math} -:label: te_dependence_model1 -\frac{{\Delta}S(TE_k)}{\bar{S}(TE_k)} = -{\Delta}{R_2^*}*TE_k +rng = np.random.default_rng(42) +noise_sd = 20 + +fig, axes = plt.subplots(1, 2, figsize=(14, 5)) +for ax, case, name in zip(axes, cases, ["s0change", "t2schange"]): + true_delta = case["signal"] - mean_sig + sim_avg = decay(sim_tes, mean_s0, mean_t2s) + measured = np.interp(sim_tes, dense_tes, true_delta) + rng.normal(0, noise_sd, sim_tes.size) + fits = fit_te_models(measured, sim_avg, sim_tes) + glue(f"F_S0_{name}", float(fits["S0"]["F"]), display=False) + glue(f"F_R2_{name}", float(fits["R2"]["F"]), display=False) + + ax.plot(dense_tes, true_delta, color="gray", alpha=0.5, linewidth=5, label="True change") + ax.scatter(sim_tes, measured, color="black", s=60, zorder=3, label="Measured change") + ax.plot( + dense_tes, + fits["S0"]["coef"] * mean_sig, + color="red", + linestyle="--", + label=f"$S_0$ model ($F$ = {fits['S0']['F']:.0f})", + ) + ax.plot( + dense_tes, + fits["R2"]["coef"] * mean_sig * dense_tes, + color="blue", + linestyle="--", + label=f"$R_2^*$ model ($F$ = {fits['R2']['F']:.0f})", + ) + ax.set_title(case["title"], fontsize=16) + ax.set_xlabel("Echo Time (ms)", fontsize=14) + ax.set_xlim(0, dense_tes.max()) + ax.legend(fontsize=11) + +axes[0].set_ylabel("Signal change, ${\\Delta}S(TE)$", fontsize=14) +fig.tight_layout() +glue_figure("fig_te_model_fits", fig, display=False) ``` -```{math} -:label: te_dependence_model2 -{\Delta}S(TE_k) = {\bar{S}(TE_k)} * -{\Delta}{R_2^*}*TE_k +```{figure} figures/fig_te_model_fits.png +:name: fig_te_model_fits +:align: center + +The TE-independence ($S_{0}$, red) and TE-dependence ($R_{2}^{*}$, blue) models fit to a simulated change in $S_{0}$ (left) +and in $T_{2}^{*}$ (right), measured at five echo times with added noise. +The legend gives each model's F-statistic. ``` -$-{\Delta}{R_2^*}$ is a scalar, so we ignore it, -which means we only use ${\bar{S}(TE_k)}$ (mean echo-wise signal) and $TE_k$ (echo time in milliseconds). +Each model fits the change it was built for and fails on the other one. +For the $S_{0}$ change, the $S_{0}$ model has $F$ ≈ {glue:text}`F_S0_s0change:.0f` +and the $R_{2}^{*}$ model has $F$ ≈ {glue:text}`F_R2_s0change:.0f`. +For the $T_{2}^{*}$ change, the $R_{2}^{*}$ model has $F$ ≈ {glue:text}`F_R2_t2schange:.0f` +and the $S_{0}$ model has $F$ ≈ {glue:text}`F_S0_t2schange:.0f`. + +## Applying the models to components -Thus, +In real data, we cannot apply the models to each volume separately, +because each volume contains many fluctuations at once, along with thermal noise. +Instead, `tedana` applies them to components. +Each component has a time series, and regressing that time series on the data from each echo +gives a parameter estimate, $PE(TE_k)$, in each voxel. +The parameter estimate is how much the signal at $TE_k$ changes for each unit of the component, +so it plays the role of ${\Delta}S(TE_k)$ in {eq}`te_independence_model` and {eq}`te_dependence_model`: ```{math} -:label: te_dependence_model3 -{\Delta}S(TE_k) = {\bar{S}(TE_k)}*TE_k * X +:label: te_independence_model4 +PE(TE_k) = \bar{S}(TE_k) \cdot X_{S_0} ``` -and for TEDPCA/TEDICA, - ```{math} :label: te_dependence_model4 -PE(TE_k) = {\bar{S}(TE_k)}*TE_k * X +PE(TE_k) = \bar{S}(TE_k) \cdot TE_k \cdot X_{R_2^*} ``` -Lastly, we fit X to the data and evaluate model fit. +Both models are fit in every voxel, which gives a map of F-statistics for each model. +`tedana` summarizes each map with a weighted average across voxels, +giving more weight to the voxels where the component is strongest. +The summary of the $R_{2}^{*}$ model is called $\kappa$ (kappa), and the summary of the $S_{0}$ model is called $\rho$ (rho). +Components with a high $\kappa$ and a low $\rho$ look like BOLD signal, +and components with a high $\rho$ and a low $\kappa$ look like non-BOLD noise. + +To see how this works, we simulate 300 volumes of a single voxel at our five echo times. +The $T_{2}^{*}$ time series is a series of blocks of activity, convolved with a hemodynamic response function, +so it looks like a BOLD response to a task. +The $S_{0}$ time series is a slow drift with a few abrupt jumps, like the effects of head motion. +Both fluctuate by about 5%, and we add a small amount of thermal noise to the signal at each echo. ```{code-cell} ipython3 :tags: [hide-cell] -X1 = (mean_sig)[:, None] # Model 1 +hrf = first_level.spm_hrf(1, oversampling=1) +n_trs = 300 +rng = np.random.default_rng(42) + +# T2*: blocks of activity with random amplitudes, convolved with the HRF +n_chunks = 10 +scales = rng.uniform(size=n_chunks) * 3 +t2s_ts = np.hstack( + [np.hstack((np.zeros(10), np.ones(20), np.zeros(10))) * scale for scale in scales], +) +t2s_ts = signal.convolve(t2s_ts, hrf)[:n_trs] +t2s_ts *= mean_t2s * frac / np.std(t2s_ts) +t2s_ts += mean_t2s - np.mean(t2s_ts) + +# S0: a slow drift, plus a few abrupt jumps like those caused by head motion +s0_ts = signal.detrend(np.cumsum(rng.normal(size=n_trs))) +jump_vols = rng.choice(n_trs, size=4, replace=False) +s0_ts[jump_vols] += rng.choice([-1, 1], size=4) * 4 * np.std(s0_ts) +s0_ts *= mean_s0 * frac / np.std(s0_ts) +s0_ts += mean_s0 - np.mean(s0_ts) + +# Signal at each echo time, with thermal noise +multiecho_signal = decay(sim_tes[:, None], s0_ts[None, :], t2s_ts[None, :]) +multiecho_signal += rng.normal(0, noise_sd, multiecho_signal.shape) -# NOTE: T2* is unnecessary for this, since it's a scalar -X2 = ((echo_times * mean_sig) / mean_t2s)[:, None] # Model 2 +t2s_ts_z = stats.zscore(t2s_ts) +s0_ts_z = stats.zscore(s0_ts) + +fig, ax = plt.subplots(figsize=(16, 4)) +ax.plot(t2s_ts_z, label="$T_2^*$ fluctuations", color="blue") +ax.plot(s0_ts_z, label="$S_0$ fluctuations", color="red") +ax.set_xlim(0, n_trs - 1) +ax.set_xlabel("Volume", fontsize=14) +ax.set_ylabel("Fluctuation (z)", fontsize=14) +ax.legend(fontsize=12, ncol=2, loc="upper right") +fig.tight_layout() +glue_figure("fig_component_curves", fig, display=False) ``` -## Fitted curves for S0-perturbed signal +```{figure} figures/fig_component_curves.png +:name: fig_component_curves +:align: center -The predicted curve for the S0 model matches the real curve perfectly! +Simulated $T_{2}^{*}$ (blue) and $S_{0}$ (red) fluctuations, each converted to z-scores. +``` ```{code-cell} ipython3 -:tags: [hide-input] -B = d_sig2[:, None] # (E x S) -alpha = (np.abs(B) ** 2).sum(axis=0) +:tags: [hide-cell] +# Drop the last cubehelix color, which is too light to see on a white background +sim_pal = sns.color_palette("cubehelix", sim_tes.size + 1)[: sim_tes.size] +fig, axes = plt.subplots(sim_tes.size, sharex=True, figsize=(16, 6)) +for i_echo, ax in enumerate(axes): + ax.plot(multiecho_signal[i_echo, :], color=sim_pal[i_echo]) + ax.set_ylabel(f"{sim_tes[i_echo]:.1f} ms", rotation=0, va="center", ha="right", fontsize=12) + ax.set_yticks([]) + ax.grid(False) + +axes[-1].set_xlabel("Volume", fontsize=14) +axes[-1].set_xlim(0, n_trs - 1) +fig.tight_layout() +glue_figure("fig_component_curves_2", fig, display=False) +``` -# S0 Model -coeffs_S0 = (B * X1).sum(axis=0) / (X1 ** 2).sum(axis=0) -pred_S0 = X1 * np.tile(coeffs_S0, (n_echoes, 1)) -SSE_S0 = (B - pred_S0) ** 2 -SSE_S0 = SSE_S0.sum(axis=0) # (S,) prediction error map -F_S0 = (alpha - SSE_S0) * (n_echoes - 1) / (SSE_S0) -pred_S0_2 = pred_S0.copy() +```{figure} figures/fig_component_curves_2.png +:name: fig_component_curves_2 +:align: center -# R2 Model -coeffs_R2 = (B * X2).sum(axis=0) / (X2 ** 2).sum(axis=0) -pred_R2 = X2 * np.tile(coeffs_R2, (n_echoes, 1)) -SSE_R2 = (B - pred_R2) ** 2 -SSE_R2 = SSE_R2.sum(axis=0) -F_R2 = (alpha - SSE_R2) * (n_echoes - 1) / (SSE_R2) -pred_R2_2 = pred_R2.copy() +The simulated signal at each echo time. +Each time series is scaled separately. +The slow $S_{0}$ drift and abrupt $S_{0}$ jumps appear at every echo time, +while the block-shaped $T_{2}^{*}$ responses become more prominent at later echo times, +because the fractional $T_{2}^{*}$ effect grows with echo time. +``` -print("Rho: {}".format(F_S0[0])) -print("Kappa: {}".format(F_R2[0])) -print() +Now we build three components from these time series: +one that follows the $T_{2}^{*}$ fluctuations only, one that follows the $S_{0}$ fluctuations only, +and one that is an equal mixture of the two. +For each component, we regress its time series on the signal at each echo to get $PE(TE_k)$, +and then fit the two models. -# Parameter estimate * mean S0 gives delta(S0) -print("Real delta S0: {}".format(s02 - mean_s0)) -print("Delta S0 from results: {}".format(coeffs_S0[0] * mean_s0)) +```{code-cell} ipython3 +:tags: [hide-cell] +components = [ + ("Pure $T_2^*$ component", t2s_ts_z), + ("Equal mixture", stats.zscore(t2s_ts_z + s0_ts_z)), + ("Pure $S_0$ component", s0_ts_z), +] +comp_names = ["t2s", "mix", "s0"] + +fig, axes = plt.subplots(1, 3, figsize=(18, 5), sharey=True) +for ax, (title, comp), name in zip(axes, components, comp_names): + # Regress the component (plus an intercept) on the signal at each echo + comp_X = np.column_stack((comp, np.ones(n_trs))) + pes = np.linalg.lstsq(comp_X, multiecho_signal.T, rcond=None)[0][0, :] + + F_S0, F_R2, pred_S0, pred_R2 = compute_te_dependence_statistics( + multiecho_signal, + pes, + sim_tes, + ) + glue(f"kappa_{name}", float(F_R2[0]), display=False) + glue(f"rho_{name}", float(F_S0[0]), display=False) + + ax.plot( + sim_tes, + pes, + color="black", + alpha=0.4, + linewidth=6, + marker="o", + markersize=10, + label="Parameter estimates", + ) + ax.plot( + sim_tes, + pred_R2, + color="blue", + marker="o", + label=f"$R_2^*$ model ($\\kappa$ = {F_R2[0]:.0f})", + ) + ax.plot( + sim_tes, + pred_S0, + color="red", + marker="o", + label=f"$S_0$ model ($\\rho$ = {F_S0[0]:.0f})", + ) + ax.set_title(title, fontsize=16) + ax.set_xticks(sim_tes) + ax.set_xlabel("Echo Time (ms)", fontsize=14) + ax.legend(fontsize=11) + +axes[0].set_ylabel("Parameter estimate", fontsize=14) +fig.tight_layout() +glue_figure("fig_component_model_fits", fig, display=False) ``` -## Fitted curves for R2*-perturbed signal +```{figure} figures/fig_component_model_fits.png +:name: fig_component_model_fits +:align: center + +Parameter estimates (gray) and the fits of the $R_{2}^{*}$ (blue) and $S_{0}$ (red) models +for three simulated components. +``` -For some reason, the predicted curve for the R2 model doesn't match the real signal curve. -What's with this mismatch? +For the pure $T_{2}^{*}$ component, the parameter estimates follow the $R_{2}^{*}$ model closely, +and $\kappa$ ({glue:text}`kappa_t2s:.0f`) is much larger than $\rho$ ({glue:text}`rho_t2s:.0f`). +For the pure $S_{0}$ component, the opposite is true: +$\rho$ is {glue:text}`rho_s0:.0f` and $\kappa$ is {glue:text}`kappa_s0:.0f`. +For the equal mixture, neither model fits well, and $\kappa$ ({glue:text}`kappa_mix:.0f`) +and $\rho$ ({glue:text}`rho_mix:.0f`) are much closer together. +Real components often fall somewhere between these extremes, +which is why `tedana` classifies components with a decision tree that uses several metrics, not only $\kappa$ and $\rho$. -It seems like the mismatch increases as the difference between the fluctuating volume's R2 and the mean R2 increases. -The fitted curve seems to actually match the mean signal, not the perturbed signal! +The values of $\kappa$ and $\rho$ depend on the number of echoes, the noise level, and the number of voxels, +so they are only meaningful relative to other components from the same data, +not as absolute thresholds. + +## TE-dependence in real data with `tedana` + +So far, we have worked with simulated signals. +In this section, we follow the same ideas through `tedana`'s processing of the five-echo resting-state run used throughout this book, +from the raw echoes to the denoised data. +The `tedana` outputs come from [](03_Denoising_with_tedana.md). +To keep the figures readable, we focus on a single voxel: +the voxel with the highest weight on the most BOLD-like accepted component. ```{code-cell} ipython3 -:tags: [hide-input] -B = d_sig3[:, None] # (E x S) -alpha = (np.abs(B) ** 2).sum(axis=0) - -# S0 Model -coeffs_S0 = (B * X1).sum(axis=0) / (X1 ** 2).sum(axis=0) -pred_S0 = X1 * np.tile(coeffs_S0, (n_echoes, 1)) -SSE_S0 = (B - pred_S0) ** 2 -SSE_S0 = SSE_S0.sum(axis=0) # (S,) prediction error map -F_S0 = (alpha - SSE_S0) * (n_echoes - 1) / (SSE_S0) -pred_S0_3 = pred_S0.copy() - -# R2 Model -coeffs_R2 = (B * X2).sum(axis=0) / (X2 ** 2).sum(axis=0) -pred_R2 = X2 * np.tile(coeffs_R2, (n_echoes, 1)) -SSE_R2 = (B - pred_R2) ** 2 -SSE_R2 = SSE_R2.sum(axis=0) -F_R2 = (alpha - SSE_R2) * (n_echoes - 1) / (SSE_R2) -pred_R2_3 = pred_R2.copy() - -print("Rho: {}".format(F_S0[0])) -print("Kappa: {}".format(F_R2[0])) +:tags: [hide-cell] +data = load_pafin(data_path) +prefix = "sub-24053_ses-1_task-rat_dir-PA_run-01" +ted_dir = os.path.join(data_path, "tedana") +func_dir = os.path.join(data_path, "ds006185/sub-24053/ses-1/func") +anat_dir = os.path.join(data_path, "ds006185/sub-24053/ses-1/anat") + +# The echo times are stored in seconds. The figures below use milliseconds. +tes_ms = np.array(data["echo_times"]) * 1000 +n_real_echoes = len(tes_ms) +# Drop the last cubehelix color, which is too light to see on a white background +echo_pal = sns.color_palette("cubehelix", n_real_echoes + 1)[:n_real_echoes] + +# Background anatomical image, resampled onto the grid of the functional data. +# The transform moves images from the BOLD reference to the T1w image, +# so we apply its inverse to bring the T1w image into the space of the BOLD data. +xfm = nit.linear.load( + os.path.join(func_dir, f"{prefix}_from-boldref_to-T1w_mode-image_desc-coreg_xfm.txt"), + fmt="itk", +) +t1_file = os.path.join(anat_dir, f"{prefix.split('_task')[0]}_desc-preproc_T1w.nii.gz") +bg_img = nit.resampling.apply(~xfm, t1_file, reference=data["mask"]) + +# tedana's adaptive mask. tedana computes the TE-dependence metrics in voxels +# with at least three good echoes, so we use the same voxels here. +adaptive_mask_file = os.path.join(ted_dir, f"{prefix}_desc-adaptiveGoodSignal_mask.nii.gz") +mask = image.math_img("img >= 3", img=adaptive_mask_file) + + +def load_ted(desc): + """Load a tedana output as a (time or component, voxel) array.""" + return masking.apply_mask(os.path.join(ted_dir, f"{prefix}_{desc}.nii.gz"), mask) + + +def load_ted_echoes(desc): + """Load an echo-wise tedana output as a (voxel, echo, component) array.""" + files = [ + os.path.join(ted_dir, f"{prefix}_echo-{i_echo + 1}_{desc}.nii.gz") + for i_echo in range(n_real_echoes) + ] + return np.stack([masking.apply_mask(f, mask).T for f in files], axis=1) + + +def zscore_time(arr): + """Z-score each voxel's time series.""" + return (arr - arr.mean(axis=0)) / arr.std(axis=0) + + +# Echo-wise data, T2* map, and optimally combined data +echo_data = [masking.apply_mask(f, mask) for f in data["echo_files"]] +t2s_map = masking.apply_mask(os.path.join(ted_dir, f"{prefix}_T2starmap.nii.gz"), mask) +oc = load_ted("desc-optcom_bold") + +# PCA and ICA results +pca_mixing = pd.read_table(os.path.join(ted_dir, f"{prefix}_desc-PCA_mixing.tsv")).values +ica_mixing = pd.read_table(os.path.join(ted_dir, f"{prefix}_desc-ICA_mixing.tsv")).values +ica_maps = load_ted("desc-ICA_components") +ica_pes = load_ted_echoes("desc-ICA_components") +r2_preds = load_ted_echoes("desc-ICAT2ModelPredictions_components") +s0_preds = load_ted_echoes("desc-ICAS0ModelPredictions_components") +comp_tbl = pd.read_table( + os.path.join(ted_dir, f"{prefix}_desc-tedana_metrics.tsv"), + index_col="Component", +) + +# Denoised data, with and without minimum image regression +medn = load_ted("desc-denoised_bold") +mehk = load_ted("desc-optcomAccepted_bold") +medn_mir = load_ted("desc-optcomMIRDenoised_bold") +mehk_mir = load_ted("desc-optcomAcceptedMIRDenoised_bold") + +# Example components: the accepted component with the highest kappa +# and the rejected component with the highest rho +accepted = comp_tbl.loc[comp_tbl["classification"] == "accepted"] +rejected = comp_tbl.loc[comp_tbl["classification"] == "rejected"] +bold_comp = accepted["kappa"].idxmax() +nonbold_comp = rejected["rho"].idxmax() +example_comps = [bold_comp, nonbold_comp] + + +def comp_index(comp): + """Convert a component name (e.g., ICA_07) to its index.""" + return int(comp.split("_")[1]) + + +# The voxel with the highest weight on the BOLD-like component +voxel_idx = np.argmax(ica_maps[comp_index(bold_comp), :]) +voxel_ts = np.vstack([d[:, voxel_idx] for d in echo_data]) +n_vols = voxel_ts.shape[1] ``` +### The adaptive mask + +Longer echo times are more susceptible to signal dropout, +which means that certain brain regions (e.g., orbitofrontal cortex, temporal poles) only have good signal for some echoes. +To avoid using bad signal from the affected echoes when it estimates $T_{2}^{*}$ and $S_{0}$, +`tedana` generates an adaptive mask, where the value for each voxel is the number of echoes with "good" signal. +Each voxel's $T_{2}^{*}$ and $S_{0}$ are then estimated from only its first $n$ echoes, +where $n$ is the value for that voxel in the adaptive mask, +using the log-linear fit described in [](Signal_Decay.md). + ```{code-cell} ipython3 :tags: [hide-cell] -fig, axes = plt.subplots(1, 2, figsize=(16, 2.5)) - -axes[0].set_title("Change in S0", fontsize=20, y=1.02) -axes[0].plot(echo_times, d_sig2, label="${\\Delta}S(TE_k)$", linewidth=5, alpha=0.5) -axes[0].plot( - echo_times, - np.round(np.squeeze(pred_R2_2), decimals=5), - label="Predicted signal for R2* model", - linestyle="--", - color="red", +# One color per number of good echoes +mask_cmap = matplotlib.colors.ListedColormap( + sns.color_palette("viridis", n_real_echoes), ) -axes[0].plot( - echo_times, - np.round(np.squeeze(pred_S0_2), decimals=5), - label="Predicted signal for S0 model", - linestyle="--", - color="black", +mask_norm = matplotlib.colors.BoundaryNorm( + np.arange(0.5, n_real_echoes + 1), + mask_cmap.N, ) -axes[0].set_xlim(0, np.max(echo_times)) -legend = axes[0].legend() - -axes[1].set_title("Change in T2*", fontsize=20, y=1.02) -axes[1].plot(echo_times, d_sig3, label="${\\Delta}S(TE_k)$", linewidth=5, alpha=0.5) -axes[1].plot( - echo_times, - np.squeeze(pred_R2_3), - label="Predicted signal for R2* model", - linestyle="--", - color="red", + +fig = plt.figure(figsize=(16, 3.5), facecolor="black") +display = plotting.plot_stat_map( + adaptive_mask_file, + bg_img=bg_img, + display_mode="z", + cut_coords=[-30, -20, -10, 0, 10, 20, 30], + threshold=0.5, + vmin=0.5, + vmax=n_real_echoes + 0.5, + cmap=mask_cmap, + colorbar=False, + draw_cross=False, + annotate=False, + figure=fig, + axes=fig.add_axes([0, 0, 0.93, 1]), ) -axes[1].plot( - echo_times, - np.squeeze(pred_S0_3), - label="Predicted signal for S0 model", - linestyle="--", - color="black", +display.title("Number of echoes with good signal", size=16, bgcolor="white", color="black") +cax = fig.add_axes([0.945, 0.15, 0.01, 0.7]) +cbar = fig.colorbar( + matplotlib.cm.ScalarMappable(norm=mask_norm, cmap=mask_cmap), + cax=cax, + ticks=np.arange(1, n_real_echoes + 1), ) -axes[1].set_xlim(0, np.max(echo_times)) -legend = axes[1].legend() - -fig.tight_layout() -glue_figure("fig_fitted_r2_curves", fig, display=False) +cbar.ax.tick_params(labelsize=12, colors="white") +glue_figure("fig_adaptive_mask", fig, display=False) ``` -```{figure} figures/fig_fitted_r2_curves.png -:name: fig_fitted_r2_curves +```{figure} figures/fig_adaptive_mask.png +:name: fig_adaptive_mask :align: center -Fitted curves for R2*-perturbed signal +`tedana`'s adaptive mask, which counts the echoes with good signal in each voxel. +Voxels in ventral frontal and temporal cortex, near the sinuses and ear canals, +have good signal in fewer echoes than the rest of the brain. ``` -```{code-cell} ipython3 -:tags: [hide-cell] -# lstsq gives same result as model fit method by Kundu, which is great to see -x, res, rank, sing = np.linalg.lstsq(X2, B, rcond=None) -print(x[0]) -print(coeffs_R2) -``` +### Optimal combination -## Now let's apply this approach to components +Next, `tedana` combines the echoes into a single time series in each voxel, +using a weighted average in which each echo's weight is proportional to its expected BOLD sensitivity, +$TE_{n} e^{-TE_{n} / T_{2}^{*}}$. +The weights depend on the voxel's own $T_{2}^{*}$, +so echoes near the voxel's $T_{2}^{*}$ get the most weight. +[](01_Optimal_Combination_with_t2smap.md) describes the optimal combination in more detail. ```{code-cell} ipython3 :tags: [hide-cell] -# Simulate data -# We'll convolve with HRF just for smoothness -hrf = first_level.spm_hrf(1, oversampling=1) +# The T2* map is in seconds +voxel_t2s = t2s_map[voxel_idx] * 1000 +weights = tes_ms * np.exp(-tes_ms / voxel_t2s) +weights /= weights.sum() +voxel_oc = np.average(voxel_ts, axis=0, weights=weights) + +fig = plt.figure(figsize=(16, 6)) +subfigs = fig.subfigures(1, 2, width_ratios=[1, 2.5]) + +# Left: the weights +ax = subfigs[0].subplots() +te_labels = [f"{te:.1f}" for te in tes_ms] +ax.bar(te_labels, weights, color=echo_pal) +ax.set_xlabel("Echo Time (ms)", fontsize=14) +ax.set_ylabel("Weight", fontsize=14) +ax.set_title(f"Weights for $T_2^*$ = {voxel_t2s:.1f} ms", fontsize=16) + +# Right: the echo-wise and optimally combined time series +axes = subfigs[1].subplots(n_real_echoes + 1, sharex=True) +for i_echo in range(n_real_echoes): + axes[i_echo].plot(voxel_ts[i_echo], color=echo_pal[i_echo]) + axes[i_echo].set_ylabel( + f"{tes_ms[i_echo]:.1f} ms", + rotation=0, + va="center", + ha="right", + fontsize=12, + ) -n_trs = 300 +axes[-1].plot(voxel_oc, color="red") +axes[-1].set_ylabel("Optimally\ncombined", rotation=0, va="center", ha="right", fontsize=12) +axes[-1].set_xlabel("Volume", fontsize=14) +axes[-1].set_xlim(0, n_vols - 1) +for ax in axes: + ax.set_yticks([]) + ax.grid(False) -frac = 0.05 # 5% PSC -mean_t2s = 30 -t2s_std = mean_t2s * frac -mean_s0 = 16000 -s0_std = mean_s0 * frac +glue_figure("fig_optcom_voxel", fig, display=False) +``` -# simulate the T2*/S0 time series -n_chunks = 10 -rng = np.random.default_rng(42) -scales = rng.uniform(size=n_chunks) * 3 -t2s_ts = [] -for section in range(n_chunks): - ts = np.hstack((np.zeros(10), np.ones(20), np.zeros(10))) - ts *= scales[section] - t2s_ts.append(ts) +```{figure} figures/fig_optcom_voxel.png +:name: fig_optcom_voxel +:align: center -t2s_ts = np.hstack(t2s_ts)[:n_trs + 20] -t2s_ts = signal.convolve(t2s_ts, hrf)[:n_trs] -t2s_ts *= t2s_std / np.std(t2s_ts) -t2s_ts += mean_t2s - np.mean(t2s_ts) +Optimal combination in a single voxel. +Left: the weight of each echo, which peaks at the echo time closest to the voxel's $T_{2}^{*}$. +Right: the time series of each echo and the optimally combined time series (red). +Each time series is scaled separately, so the y-axes are not comparable. +``` -s0_ts = rng.integers(low=0, high=2, size=n_trs).astype(float) -s0_ts -= 0.5 -s0_ts *= rng.normal(loc=1, scale=0.25, size=n_trs) -s0_ts = np.sort(s0_ts) -first_half = s0_ts[:n_trs // 2] -second_half = s0_ts[n_trs // 2:] -s0_ts = np.zeros(n_trs) -rng.shuffle(first_half) -rng.shuffle(second_half) -s0_ts[::2] = first_half -s0_ts[1::2] = second_half -# s0_ts = signal.convolve(s0_ts, hrf)[20 : n_trs + 20] -s0_ts *= s0_std / np.std(s0_ts) -s0_ts += mean_s0 - np.mean(s0_ts) +### Why use a decomposition? -# Constant T2*/S0 time series -mean_s0_ts = np.ones(n_trs) * mean_s0 -mean_t2s_ts = np.ones(n_trs) * mean_t2s +The optimally combined data still contain both BOLD and non-BOLD fluctuations. +In principle, we could separate them by fitting $S_{0}$ and $T_{2}^{*}$ to every volume +(see [](02_Volume-wise_T2star_estimation_with_t2smap.md)), +but with only a handful of echoes per volume, thermal noise makes the volume-wise estimates very noisy. +Instead, `tedana` decomposes the optimally combined data into components, +each with a time series and a spatial map. +The TE-dependence of a component is then estimated from all of the volumes at once, +and evaluated across all of the voxels where the component is present, +which makes it far more reliable than the TE-dependence of any single volume. -# Simulate signal for each echo time -t2s_signal = predict_bold_signal(echo_times, mean_s0_ts, t2s_ts) -s0_signal = predict_bold_signal(echo_times, s0_ts, mean_t2s_ts) -multiecho_signal = predict_bold_signal(echo_times, s0_ts, t2s_ts) +#### Principal component analysis -# Normalize to get component time series -t2s_ts_z = np.round(stats.zscore(t2s_ts), decimals=5) -s0_ts_z = np.round(stats.zscore(s0_ts), decimals=5) -p = 0.5 # proportion for combination -component = (p * t2s_ts_z) + ((1 - p) * s0_ts_z) +First, the optimally combined data are decomposed with principal component analysis (PCA), +and components that look like noise are discarded. +`tedana` offers several ways to choose the components to keep, +including model-selection criteria such as the Akaike information criterion, +a decision tree based on the TE-dependence metrics described below, +and a threshold on the variance explained. -fig, ax = plt.subplots(figsize=(16, 4)) -ax.plot(t2s_ts_z, label="T2* fluctuations", color="blue") -ax.plot(s0_ts_z, label="S0 fluctuations", color="red") -ax.plot(component, label="Component", color="black", alpha=0.5, linewidth=5) -ax.set_xlim(0, n_trs - 1) -ax.set_xlabel("Time (TR)") -leg = ax.legend(fontsize=14, ncol=3) -glue_figure("fig_component_curves", fig, display=False) +```{code-cell} ipython3 +:tags: [hide-cell] +fig, axes = plt.subplots(3, sharex=True, figsize=(16, 6)) +for i_comp, ax in enumerate(axes): + ax.plot(pca_mixing[:, i_comp], color="black") + ax.set_title(f"PCA component {i_comp}", fontsize=14, loc="left") + ax.set_yticks([]) + +axes[-1].set_xlim(0, pca_mixing.shape[0] - 1) +axes[-1].set_xlabel("Volume", fontsize=14) +fig.tight_layout() +glue_figure("fig_pca_timeseries", fig, display=False) ``` -```{figure} figures/fig_component_curves.png -:name: fig_component_curves +```{figure} figures/fig_pca_timeseries.png +:name: fig_pca_timeseries :align: center -Now let's apply this approach to components +Time series of the first three PCA components. ``` +The retained components are then recombined into a dimensionally reduced version of the optimally combined data, +which keeps most of the structured signal but less of the random noise. + +#### Independent component analysis + +The dimensionally reduced data are then decomposed with independent component analysis (ICA). +The number of ICA components is set to the number of components retained by the PCA, +in order to reflect the true dimensionality of the data. +ICA produces a mixing matrix, which contains a time series for each component. +Below are the time series of two components that `tedana` classified very differently: +the accepted component with the highest $\kappa$ and the rejected component with the highest $\rho$. + ```{code-cell} ipython3 :tags: [hide-cell] -interval = int(np.floor(n_echoes / 7)) -echoes_to_plot = list(range(5, n_echoes, interval)) -fig, axes = plt.subplots( - len(echoes_to_plot), sharex=True, sharey=False, figsize=(14, 6) -) - -for i_echo, echo in enumerate(echoes_to_plot): - axes[i_echo].plot(multiecho_signal[echo, :], color=pal[i_echo]) - axes[i_echo].set_ylabel( - "{0}ms".format(echo_times[echo]), - rotation=0, - va="center", - ha="right", +fig, axes = plt.subplots(2, sharex=True, figsize=(16, 5)) +for ax, comp in zip(axes, example_comps): + row = comp_tbl.loc[comp] + ax.plot(ica_mixing[:, comp_index(comp)], color="black") + ax.set_title( + f"{comp}: $\\kappa$ = {row['kappa']:.1f}, $\\rho$ = {row['rho']:.1f} ({row['classification']})", fontsize=14, + loc="left", ) - axes[i_echo].set_yticks([]) - axes[i_echo].set_xticks([]) + ax.set_yticks([]) -axes[-1].set_xlabel("Time", fontsize=16) -axes[-1].set_xlim(0, n_trs - 1) -glue_figure("fig_component_curves_2", fig, display=False) +axes[-1].set_xlim(0, ica_mixing.shape[0] - 1) +axes[-1].set_xlabel("Volume", fontsize=14) +fig.tight_layout() +glue_figure("fig_ica_timeseries", fig, display=False) ``` -```{figure} figures/fig_component_curves_2.png -:name: fig_component_curves_2 +```{figure} figures/fig_ica_timeseries.png +:name: fig_ica_timeseries +:align: center + +Time series of a BOLD-like (accepted) component and a non-BOLD-like (rejected) ICA component. +``` + +The accepted component fluctuates slowly throughout the run, as we would expect from BOLD signal. +Most of the rejected component's variance is in the first few volumes. +This pattern is typical of the start of a run, before the magnetization has reached a steady state +and the signal is brighter at every echo. +That kind of change affects $S_{0}$ rather than $T_{2}^{*}$, which fits this component's high $\rho$. + +### Fitting the TE-(in)dependence models to components + +As in the simulation above, `tedana` regresses each component's time series on the data from each echo +and fits {eq}`te_independence_model4` and {eq}`te_dependence_model4` to the resulting parameter estimates in every voxel. +The figure below shows the parameter estimates and model predictions in a single voxel for the two example components, +in the voxel where each component has its highest weight. +For the accepted component, the parameter estimates grow with echo time and closely follow the $R_{2}^{*}$ model. +For the rejected component, they do not grow with echo time, +so the $R_{2}^{*}$ model fits them poorly and the $S_{0}$ model fits them better. +Real components are rarely as clean as the pure simulated components above: +even the accepted component is not fit perfectly by either model, +which is why $\kappa$ and $\rho$ are summarized across many voxels. + +```{code-cell} ipython3 +:tags: [hide-cell] +fig, axes = plt.subplots(1, 2, figsize=(16, 5)) +for ax, comp in zip(axes, example_comps): + idx = comp_index(comp) + comp_voxel = np.argmax(ica_maps[idx, :]) + ax.plot( + tes_ms, + ica_pes[comp_voxel, :, idx], + color="black", + alpha=0.4, + linewidth=6, + marker="o", + markersize=10, + label="Parameter estimates", + ) + ax.plot( + tes_ms, + r2_preds[comp_voxel, :, idx], + color="blue", + marker="o", + label="$R_2^*$ model ($\\kappa$)", + ) + ax.plot( + tes_ms, + s0_preds[comp_voxel, :, idx], + color="red", + marker="o", + label="$S_0$ model ($\\rho$)", + ) + ax.set_title( + f"{comp} ({comp_tbl.loc[comp, 'classification']})", + fontsize=16, + loc="left", + ) + ax.set_xticks(np.round(tes_ms, 1)) + ax.set_xlabel("Echo Time (ms)", fontsize=14) + ax.set_ylabel("Parameter estimate", fontsize=14) + ax.legend(fontsize=12) + +fig.tight_layout() +glue_figure("fig_ica_weights", fig, display=False) +``` + +```{figure} figures/fig_ica_weights.png +:name: fig_ica_weights :align: center -Now let's apply this approach to components again. +Echo-wise parameter estimates (gray) and the predictions of the $R_{2}^{*}$ (blue) and $S_{0}$ (red) models +for the accepted and rejected example components, each in the voxel where the component has its highest weight. ``` +### Component selection and multi-echo denoising + +A decision tree uses $\kappa$, $\rho$, and other metrics to classify each component as BOLD-like (accepted) or non-BOLD-like (rejected). +`tedana` then produces two main denoised datasets: + +- The {term}`MEDN` data are the optimally combined data with the rejected components regressed out. + They keep the accepted components, as well as any variance that was not explained by the ICA. +- The {term}`MEHK` data are built from the accepted components alone, + so they also lose the variance that was not explained by the ICA. + ```{code-cell} ipython3 :tags: [hide-cell] -interval = int(np.floor(n_echoes / 7)) -echoes_to_plot = list(range(5, n_echoes, interval)) -fig, ax = plt.subplots(figsize=(14, 6)) -for i_echo, echo in enumerate(echoes_to_plot): - rep_echo_times = np.ones(n_trs) * echo - ax.scatter(rep_echo_times, multiecho_signal[echo, :], alpha=0.05, color=pal[i_echo]) - -max_signal = np.max(multiecho_signal, axis=1) -min_signal = np.min(multiecho_signal, axis=1) -ax.fill_between(echo_times, max_signal, min_signal, alpha=0.2) - -ax.set_ylabel("BOLD signal", fontsize=16) -ax.set_xlabel("Echo Time (ms)", fontsize=16) -ax.set_xticks(echoes_to_plot) -ax.set_xlim(0, np.max(echo_times)) -ax.tick_params(axis="both", which="major", labelsize=14) +fig, axes = plt.subplots(3, sharex=True, sharey=True, figsize=(16, 6)) +for ax, (label, arr) in zip( + axes, + [("Optimally combined", oc), ("MEDN", medn), ("MEHK", mehk)], +): + ax.plot(zscore_time(arr)[:, voxel_idx], color="black") + ax.set_title(label, fontsize=14, loc="left") + +axes[1].set_ylabel("Signal (z)", fontsize=14) +axes[-1].set_xlim(0, n_vols - 1) +axes[-1].set_xlabel("Volume", fontsize=14) fig.tight_layout() -glue_figure("fig_component_curves_3", fig, display=False) +glue_figure("fig_medn_timeseries", fig, display=False) ``` -```{figure} figures/fig_component_curves_3.png -:name: fig_component_curves_3 +```{figure} figures/fig_medn_timeseries.png +:name: fig_medn_timeseries :align: center -Now let's apply this approach to components again. +Time series of the optimally combined, denoised (MEDN), and high-kappa (MEHK) data in our voxel. ``` +### Post-processing to remove spatially diffuse noise + +Spatial ICA looks for components whose maps are spatially independent of one another. +That works well for noise that is localized, such as motion artifacts at the edges of the brain or pulsation near large vessels, +but noise that is spread out across the whole brain, such as fluctuations related to respiration, +overlaps with every other component's map and does not separate cleanly into components of its own. +One of several post-processing strategies may be applied to the MEDN or MEHK data to remove this spatially diffuse noise. +Methods that have been used in the past include global signal regression (GSR), +{prf:ref}`minimum image regression ` (MIR), anatomical CompCor, +Go Decomposition (GODEC), and robust PCA. +`tedana` implements GSR and MIR (the `gscontrol` option), and they work at different stages of the pipeline. + +`tedana`'s version of GSR is applied *before* the decomposition, +to the optimally combined data and to each echo. +Rather than averaging the signal across the brain, as standard GSR does, +it removes slow drifts from the optimally combined data and takes the minimum of each voxel's time series, +which gives a spatial map of the global signal. +It then estimates the time course of that map by regression +and regresses the time course out of the optimally combined data and each echo. + +MIR is applied *after* the decomposition, to the MEDN and MEHK data, +and it estimates the global signal from the BOLD-like (accepted) components only. +`tedana`'s documentation notes that the benefits and drawbacks of both options are not yet clear. + ```{code-cell} ipython3 :tags: [hide-cell] -fig, ax = plt.subplots(figsize=(16, 4)) +fig, axes = plt.subplots(2, sharex=True, sharey=True, figsize=(16, 5)) +for ax, (label, before, after) in zip( + axes, + [("MEDN", medn, medn_mir), ("MEHK", mehk, mehk_mir)], +): + ax.plot( + zscore_time(before)[:, voxel_idx], + color="gray", + alpha=0.6, + linewidth=3, + label=label, + ) + ax.plot(zscore_time(after)[:, voxel_idx], color="black", label=f"{label} + MIR") + ax.legend(frameon=True, fontsize=12, loc="upper right", framealpha=1) -# Add a constant term to the array -comp_X = np.hstack((component[:, None], np.ones((component.shape[0], 1)))) -pes, _, _, _ = np.linalg.lstsq(comp_X, multiecho_signal.T, rcond=None) -pes = pes[0, :] +axes[-1].set_xlim(0, n_vols - 1) +axes[-1].set_xlabel("Volume", fontsize=14) +fig.tight_layout() +glue_figure("fig_mir_timeseries", fig, display=False) +``` -F_S0, F_R2, pred_S0, pred_R2 = compute_te_dependence_statistics( - multiecho_signal, pes, echo_times -) -ax.plot(echo_times, pred_R2, label="Predicted T2* model values", c="blue") -ax.plot(echo_times, pred_S0, label="Predicted S0 model values", c="red") -ax.plot(echo_times, pes, label="Component PEs", alpha=0.5, linewidth=5, c="black") -ax.plot(echo_times, pred_R2, label=r"$\kappa$ = {:.02f}".format(F_R2[0]), alpha=0) -ax.plot(echo_times, pred_S0, label=r"$\rho$ = {:.02f}".format(F_S0[0]), alpha=0) -ax.set_xlim(0, np.max(echo_times)) -ax.set_xlabel("Echo time (ms)") -leg = ax.legend(fontsize=14, ncol=2) -glue_figure("fig_component_curves_4", fig, display=False) -``` - -```{figure} figures/fig_component_curves_4.png -:name: fig_component_curves_4 +```{figure} figures/fig_mir_timeseries.png +:name: fig_mir_timeseries :align: center -Now let's apply this approach to components again. +Time series of the MEDN and MEHK data in our voxel, before (gray) and after (black) {prf:ref}`minimum image regression `. ``` +MIR estimates the global noise from the minimum, over time, of each voxel's BOLD-like signal. +This minimum image of the BOLD-like data tends to look like a $T_{1}$-weighted image, +so the global fluctuation that MIR removes is called the "$T_{1}$-like effect." +The steps of minimum image regression are as follows. + ```{prf:algorithm} Minimum image regression :label: minimum-image-regression @@ -584,9 +999,9 @@ where $v$ is the number of voxels in the brain mask and $t$ is the number of tim - $\mathbf{M}$ is the mixing matrix from the ICA decomposition, of shape $c \times t$, where $c$ is the number of components. - $W$ is the set of indices of all components in $\mathbf{M}$: $W = \{1, 2, 3, ..., c\}$ - $N$ is the set of indices of all non-ignored components (i.e., all accepted or BOLD-like, and rejected or non-BOLD components) in - $\mathbf{M}$: $N \in \mathbb{N}^k \text{ s.t } 1 \leq k \leq c, N \subseteq W$ + $\mathbf{M}$: $N \in \mathbb{N}^k \text{ s.t. } 1 \leq k \leq c, N \subseteq W$ - $A$ is the set of indices of all accepted (i.e., BOLD-like) components in $\mathbf{M}$: - $A \in \mathbb{N}^l \text{ s.t } 1 \leq l \leq k, A \subseteq N$ + $A \in \mathbb{N}^l \text{ s.t. } 1 \leq l \leq k, A \subseteq N$ **Outputs** @@ -624,8 +1039,8 @@ where $v$ is the number of voxels in the brain mask and $t$ is the number of tim 5. We can likewise construct the normalized time series of BOLD-like components ($\mathbf{P} \in \mathbb{R}^{v \times t}$) by multiplying similarly reduced parameter estimate and mixing matrices composed of only the columns and rows, respectively, that are associated with the accepted components indexed in $A$. - The resulting time series matrix is similar to the time series matrix referred to elsewhere in the manuscript as - multi-echo high-Kappa (MEHK), with the exception that the component time series have been normalized prior to reconstruction. + The resulting time series matrix is similar to the {term}`MEHK` data described above, + except that the component time series have been normalized prior to reconstruction. $$ \mathbf{P} = \mathbf{B}_A \mathbf{M}_A, \enspace \mathbf{B}_A \in \mathbb{R}^{v \times |A|}, @@ -660,7 +1075,7 @@ where $v$ is the number of voxels in the brain mask and $t$ is the number of tim the T1-like effect ($\mathbf{E} \in \mathbb{R}^{v \times t}$). $$ - \mathbf{P} = \mathbf{g} \otimes \mathbf{s} + \mathbf{E} + \mathbf{P} = \mathbf{s} \otimes \mathbf{g} + \mathbf{E} $$ 9. The time series matrix of BOLD-like components without the T1-like effect (MEHK+MIR, $\mathbf{H} \in \mathbb{R}^{v \times t}$), @@ -697,15 +1112,15 @@ where $v$ is the number of voxels in the brain mask and $t$ is the number of tim }_{t} $$ -11. The T1c-corrected ICA mixing matrix is then derived by regressing the global signal time series $\mathbf{g}$ from - each component's time series. Let $\mathbf{Q}$ be the associated parameter estimate matrix - ($\mathbf{Q} \in \mathbb{R}^{c \times t}$). +11. The ICA mixing matrix without the T1-like effect is then derived by regressing the global signal time series $\mathbf{g}$ from + each component's time series. Let $\mathbf{r}$ be the vector of parameter estimates from these regressions + ($\mathbf{r} \in \mathbb{R}^{c}$). $$ - \mathbf{M} = \mathbf{Q}\mathbf{g} + \mathbf{K} + \mathbf{M} = \mathbf{r} \otimes \mathbf{g} + \mathbf{K} $$ $$ - \mathbf{K} = \mathbf{M} - \mathbf{Q}\mathbf{g} + \mathbf{K} = \mathbf{M} - \mathbf{r} \otimes \mathbf{g} $$ ``` diff --git a/content/plot_approach_figures.md b/content/plot_approach_figures.md deleted file mode 100644 index 16c3eb88..00000000 --- a/content/plot_approach_figures.md +++ /dev/null @@ -1,820 +0,0 @@ ---- -jupytext: - text_representation: - extension: .md - format_name: myst - jupytext_version: 1.18.1 -kernelspec: - display_name: Python 3 - language: python - name: python3 ---- - -# Generate tedana walkthrough figures - -```{important} -The contents of this chapter will be moved into TE_Dependence and, to a lesser extent, Signal_Decay, -and this chapter will be removed. -``` - -```{code-cell} ipython3 -:tags: [hide-cell] -import json -import os -from glob import glob - -import matplotlib.pyplot as plt -import nibabel as nb -import nitransforms as nit -import numpy as np -import pandas as pd -import seaborn as sns -from book_utils import glue_figure, load_pafin -from nilearn import image, masking, plotting -from tedana.utils import make_adaptive_mask - -data_path = os.path.abspath('../data') - -ted_dir = os.path.join(data_path, "tedana") -``` - -## Load data -```{code-cell} ipython3 -:tags: [hide-cell] -data = load_pafin(data_path) -# The echo times are stored in seconds. The figures below use milliseconds. -echo_times = np.array(data['echo_times']) * 1000 - -# Background anatomical image, resampled onto the grid of the functional data. -# The transform moves images from the BOLD reference to the T1w image, -# so we apply its inverse to bring the T1w image into the space of the BOLD data. -func_dir = os.path.join(data_path, "ds006185/sub-24053/ses-1/func/") -anat_dir = os.path.join(data_path, "ds006185/sub-24053/ses-1/anat/") -xfm = os.path.join( - func_dir, - "sub-24053_ses-1_task-rat_dir-PA_run-01_from-boldref_to-T1w_mode-image_desc-coreg_xfm.txt", -) -xfm = nit.linear.load(xfm, fmt="itk") -t1_file = os.path.join(anat_dir, "sub-24053_ses-1_desc-preproc_T1w.nii.gz") -bg_img = nit.resampling.apply(~xfm, t1_file, reference=data['mask']) - -# Tedana outputs -adaptive_mask_file = os.path.join( - ted_dir, - "sub-24053_ses-1_task-rat_dir-PA_run-01_desc-adaptiveGoodSignal_mask.nii.gz", -) -mask = image.math_img("img >= 3", img=adaptive_mask_file) - -# Optimally combined data -oc = masking.apply_mask( - os.path.join(ted_dir, "sub-24053_ses-1_task-rat_dir-PA_run-01_desc-optcom_bold.nii.gz"), - mask, -) -oc_z = (oc - np.mean(oc, axis=0)) / np.std(oc, axis=0) - -# Results from MEPCA -mepca_mmix = pd.read_table( - os.path.join(ted_dir, "sub-24053_ses-1_task-rat_dir-PA_run-01_desc-PCA_mixing.tsv"), -).values -oc_red = masking.apply_mask( - os.path.join( - ted_dir, "sub-24053_ses-1_task-rat_dir-PA_run-01_desc-optcom_whitened_bold.nii.gz" - ), - mask, -) - -# Results from MEICA -meica_mmix = pd.read_table( - os.path.join(ted_dir, "sub-24053_ses-1_task-rat_dir-PA_run-01_desc-ICA_mixing.tsv"), -).values -norm_weights = masking.apply_mask( - os.path.join( - ted_dir, - "sub-24053_ses-1_task-rat_dir-PA_run-01_desc-ICAAveragingWeights_components.nii.gz", - ), - mask, -) -meica_beta_files = sorted( - glob( - os.path.join( - ted_dir, - "sub-24053_ses-1_task-rat_dir-PA_run-01_echo-*_desc-ICA_components.nii.gz", - ), - ), -) -meica_betas = np.dstack([masking.apply_mask(f, mask).T for f in meica_beta_files]) -meica_betas = np.swapaxes(meica_betas, 1, 2) - -r2_pred_beta_files = sorted( - glob( - os.path.join( - ted_dir, - "sub-24053_ses-1_task-rat_dir-PA_run-01_echo-*_desc-ICAT2ModelPredictions_components.nii.gz", - ), - ), -) -r2_pred_betas = np.dstack([masking.apply_mask(f, mask).T for f in r2_pred_beta_files]) -r2_pred_betas = np.swapaxes(r2_pred_betas, 1, 2) -s0_pred_beta_files = sorted( - glob( - os.path.join( - ted_dir, - "sub-24053_ses-1_task-rat_dir-PA_run-01_echo-*_desc-ICAS0ModelPredictions_components.nii.gz", - ), - ), -) -s0_pred_betas = np.dstack([masking.apply_mask(f, mask).T for f in s0_pred_beta_files]) -s0_pred_betas = np.swapaxes(s0_pred_betas, 1, 2) - -# Component parameter estimates -betas_file = os.path.join( - ted_dir, "sub-24053_ses-1_task-rat_dir-PA_run-01_desc-ICA_components.nii.gz" -) -beta_maps = masking.apply_mask(betas_file, mask) - -# Multi-echo denoised data -dn_data = masking.apply_mask( - os.path.join( - ted_dir, "sub-24053_ses-1_task-rat_dir-PA_run-01_desc-denoised_bold.nii.gz" - ), - mask, -) -hk_data = masking.apply_mask( - os.path.join( - ted_dir, "sub-24053_ses-1_task-rat_dir-PA_run-01_desc-optcomAccepted_bold.nii.gz" - ), - mask, -) - -# Post-processed data -dn_t1c_data = masking.apply_mask( - os.path.join( - ted_dir, "sub-24053_ses-1_task-rat_dir-PA_run-01_desc-optcomMIRDenoised_bold.nii.gz" - ), - mask, -) -hk_t1c_data = masking.apply_mask( - os.path.join( - ted_dir, "sub-24053_ses-1_task-rat_dir-PA_run-01_desc-optcomAcceptedMIRDenoised_bold.nii.gz" - ), - mask, -) - -# Component table -comp_tbl = pd.read_table( - os.path.join(ted_dir, "sub-24053_ses-1_task-rat_dir-PA_run-01_desc-tedana_metrics.tsv"), - index_col="Component", -) - -# Get voxel index for voxel most related to component with highest kappa value -acc_comp_tbl = comp_tbl.loc[comp_tbl["classification"] == "accepted"] -high_kappa_comp = acc_comp_tbl.sort_values(by="kappa", ascending=False).index.values[0] -high_kappa_comp_val = int(high_kappa_comp.split("_")[1]) -voxel_idx = np.where( - beta_maps[high_kappa_comp_val, :] == np.max(beta_maps[high_kappa_comp_val, :]) -)[0][0] - -rej_comp_tbl = comp_tbl.loc[comp_tbl["classification"] == "rejected"] -low_kappa_comp = rej_comp_tbl.sort_values(by="rho", ascending=False).index.values[0] - -# load data -arr = [masking.apply_mask(f, mask) for f in data['echo_files']] -ts = [d[:, voxel_idx] for d in arr] -ts_1d = np.hstack(ts) - -n_echoes = len(echo_times) -n_trs = arr[0].shape[0] - -pal = sns.color_palette("cubehelix", n_echoes) -``` - -```{code-cell} ipython3 -:tags: [hide-cell] -# Prepare data for model -log_data = np.log(np.abs(ts_1d) + 1) -# log_data = np.log(ts_1d) # in a perfect world... -x = np.column_stack([np.ones(n_echoes), -1 * echo_times]) -X = np.repeat(x, n_trs, axis=0) # T * E - -# Model fit -betas = np.linalg.lstsq(X, log_data, rcond=None)[0] -s0 = np.exp(betas[0]) -r2s = betas[1] -t2s = 1.0 / r2s - -# Values for plots -# Values from log-linear model -log_x = np.arange(-1000, 0, 0.01) -log_y = betas[0] + log_x * betas[1] - -# Values from monoexponential decay model -mono_x = np.arange(0, 1000, 0.01) -mono_y = np.exp(-1 * betas[1] * mono_x) * s0 - -# Get weights for optimal combination -alpha = echo_times * np.exp(-echo_times / t2s) -alpha = alpha / np.sum(alpha) # unnecessary but good for bar plot below - -# Combine data across echoes -oc_manual = np.average(np.vstack(ts), axis=0, weights=alpha) -``` - -### Echo-specific timeseries - -```{code-cell} ipython3 -:tags: [hide-cell] -fig, axes = plt.subplots(n_echoes, sharex=True, sharey=False, figsize=(14, 6)) -for i_echo in range(n_echoes): - axes[i_echo].plot(ts[i_echo], color=pal[i_echo]) - axes[i_echo].set_ylabel( - f"{echo_times[i_echo]:.1f}ms", rotation=0, va="center", ha="right", fontsize=14 - ) - axes[i_echo].set_yticks([]) - axes[i_echo].set_xticks([]) - -axes[-1].set_xlabel("Time", fontsize=16) -axes[-1].set_xlim(0, len(ts[i_echo]) - 1) -fig.tight_layout() -glue_figure("fig_echo_timeseries2", fig, display=False) -``` - -```{figure} figures/fig_echo_timeseries2.png -:name: fig_echo_timeseries2 -:align: center - -Time series from a voxel for each echo. -``` - -### Echo-specific data and echo time - -```{code-cell} ipython3 -:tags: [hide-cell] -fig, ax = plt.subplots(figsize=(14, 6)) -values = [i[0] for i in ts] -for i_echo in range(n_echoes): - rep_echo_times = np.ones(n_trs) * echo_times[i_echo] - ax.scatter(rep_echo_times, ts[i_echo], alpha=0.05, color=pal[i_echo]) - -ax.set_ylabel("BOLD signal", fontsize=16) -ax.set_xlabel("Echo Time (ms)", fontsize=16) -ax.set_xticks(echo_times) -ax.tick_params(axis="both", which="major", labelsize=14) -ax.set_xlim(0, 120) -ax.set_ylim(0, 24000) -fig.tight_layout() -glue_figure("fig_echo_scatter2", fig, display=False) -``` - -```{figure} figures/fig_echo_scatter2.png -:name: fig_echo_scatter2 -:align: center - -Scatter plot of a voxel's values by echo time. -``` - -### Adaptive mask -Longer echo times are more susceptible to signal dropout, which means that certain brain regions -(e.g., orbitofrontal cortex, temporal poles) will only have good signal for some echoes. -In order to avoid using bad signal from affected echoes in calculating $T_{2}^*$ and $S_{0}$ for a given voxel, -`tedana` generates an adaptive mask, where the value for each voxel is the number of echoes with "good" signal. -When $T_{2}^*$ and $S_{0}$ are calculated below, each voxel's values are only calculated from the first $n$ echoes, -where $n$ is the value for that voxel in the adaptive mask. - -```{code-cell} ipython3 -:tags: [hide-cell] -adaptive_mask_img = nb.load(adaptive_mask_file) - -fig, ax = plt.subplots(figsize=(10, 4)) -palette = sns.color_palette("BuGn_r", 10) -plotting.plot_stat_map( - adaptive_mask_img, - vmax=n_echoes, - # alpha=0.5, - threshold=1.0, - draw_cross=False, - colorbar=True, - cmap="Blues", - annotate=False, - bg_img=bg_img, - figure=fig, - axes=ax, -) -glue_figure("fig_adaptive_mask", fig, display=False) -``` - -```{figure} figures/fig_adaptive_mask.png -:name: fig_adaptive_mask -:align: center - -Adaptive mask. -``` - -### Log-linear transformation - -```{code-cell} ipython3 -:tags: [hide-cell] -fig, ax = plt.subplots(figsize=(14, 6)) -for i_echo in range(n_echoes): - rep_echo_times = -1 * np.ones(n_trs) * echo_times[i_echo] - log_echo_data = np.log((np.abs(ts[i_echo]) + 1)) - ax.scatter(rep_echo_times, log_echo_data, alpha=0.05, color=pal[i_echo]) - -ax.set_ylabel("log(BOLD signal)", fontsize=16) -ax.set_xlabel("Negative Echo Time (ms)", fontsize=16) -ax.set_xticks(-1 * echo_times) -ax.set_xlim(-120, 0) -ax.set_ylim(np.floor(log_data.min()), np.ceil(log_data.max())) -ax.tick_params(axis="both", which="major", labelsize=14) - -fig.tight_layout() -glue_figure("fig_loglin_scatter", fig, display=False) -``` - -```{figure} figures/fig_loglin_scatter.png -:name: fig_loglin_scatter -:align: center - -Scatter plot of a voxel's signal for each echo, after log-linear transformation. -``` - -### Log-linear model -Let $S$ be the BOLD signal for a given echo. - -Let $TE$ be the echo time in milliseconds. - -```{math} -:label: log_linear_model -\log_{e}(\left|\begin{pmatrix} -S(TE_{1}) \\ -S(TE_{2}) \\ -\vdots \\ -S(TE_{n})\end{pmatrix}\right| -+ -\begin{pmatrix} -1 \\ -1 \\ -\vdots \\ -1\end{pmatrix} -) = B_{1} -\begin{pmatrix} --TE_{1} \\ --TE_{2} \\ -\vdots \\ --TE_{n}\end{pmatrix} + -\begin{pmatrix} -B_{0} \\ -B_{0} \\ -\vdots \\ -B_{0}\end{pmatrix} -``` - -```{code-cell} ipython3 -:tags: [hide-cell] -fig, ax = plt.subplots(figsize=(14, 6)) -for i_echo in range(n_echoes): - rep_echo_times = -1 * np.ones(n_trs) * echo_times[i_echo] - log_echo_data = np.log((np.abs(ts[i_echo]) + 1)) - ax.scatter(rep_echo_times, log_echo_data, alpha=0.05, color=pal[i_echo]) - -ax.plot(log_x, log_y) - -ax.set_ylabel("log(BOLD signal)", fontsize=16) -ax.set_xlabel("Negative Echo Time (ms)", fontsize=16) -ax.set_xticks(-1 * echo_times) -ax.set_xlim(-120, 0) -ax.set_ylim(np.floor(log_data.min()), np.ceil(log_data.max())) -ax.tick_params(axis="both", which="major", labelsize=14) - -ax.annotate( - "$B_0$: {0:.02f}\n$B_1$: {1:.02f}".format(betas[0], betas[1]), - xy=(0.02, 0.08), - xycoords="axes fraction", - fontsize=16, - bbox=dict(fc="white", ec="black", lw=1), -) - -fig.tight_layout() -glue_figure("fig_loglin_scatter_with_line", fig, display=False) -``` - -```{figure} figures/fig_loglin_scatter_with_line.png -:name: fig_loglin_scatter_with_line -:align: center - -Scatter plot of a voxel's signal for each echo, after log-linear transformation, with fitted line. -``` - -## Monoexponential decay model -Calculation of $S_{0}$ and $T_{2}^{*}$ - -```{math} -:label: monoexponential_decay_s0 -S_{0} = e^{B_{0}} -``` - -```{math} -:label: monoexponential_decay_t2s -T_{2}^{*} = \frac{1}{B_{1}} -``` - -```{code-cell} ipython3 -:tags: [hide-cell] -fig, ax = plt.subplots(figsize=(14, 6)) -for i_echo in range(n_echoes): - rep_echo_times = np.ones(n_trs) * echo_times[i_echo] - ax.scatter(rep_echo_times, ts[i_echo], alpha=0.05, color=pal[i_echo]) - -ax.plot(mono_x, mono_y) - -ax.set_ylabel("BOLD signal", fontsize=16) -ax.set_xlabel("Echo Time (ms)", fontsize=16) -ax.set_xticks(echo_times) -ax.set_xlim(0, 120) -ax.set_ylim(0, 24000) -ax.tick_params(axis="both", which="major", labelsize=14) -ax.annotate( - "$S_0$: {0:.02f}\n$T_2^*$: {1:.02f}".format(s0, t2s), - xy=(86.5, 13500), - fontsize=16, - bbox=dict(fc="white", ec="black", lw=1), -) - -fig.tight_layout() -glue_figure("fig_loglin_scatter_with_t2s", fig, display=False) -``` - -```{figure} figures/fig_loglin_scatter_with_t2s.png -:name: fig_loglin_scatter_with_t2s -:align: center - -Scatter plot of a voxel's signal for each echo, with the fitted monoexponential decay curve and the S0 and T2* estimates. -``` - -### T2* - -```{code-cell} ipython3 -:tags: [hide-cell] -fig, ax = plt.subplots(figsize=(14, 6)) -for i_echo in range(n_echoes): - rep_echo_times = np.ones(n_trs) * echo_times[i_echo] - ax.scatter(rep_echo_times, ts[i_echo], alpha=0.05, color=pal[i_echo]) - -ax.plot(mono_x, mono_y) - -ax.axvline(t2s, 0, 1, label="$T_2^*$", color="black", linestyle="--", alpha=0.5) -ax.set_ylabel("BOLD signal", fontsize=16) -ax.set_xlabel("Echo Time (ms)", fontsize=16) -ax.set_xticks(np.hstack((echo_times, [np.round(t2s, 1)]))) -ax.set_xlim(0, 120) -ax.set_ylim(0, 24000) -ax.tick_params(axis="both", which="major", labelsize=14) -ax.xaxis.get_major_ticks()[-1].set_pad(20) - -legend = ax.legend(frameon=True, fontsize=16) - -fig.tight_layout() -glue_figure("fig_scatter_with_t2s", fig, display=False) -``` - -```{figure} figures/fig_scatter_with_t2s.png -:name: fig_scatter_with_t2s -:align: center - -Scatter plot of a voxel's signal for each echo with T2* estimate. -``` -### Optimal combination weights - -```{code-cell} ipython3 -:tags: [hide-cell] -fig, ax = plt.subplots() -te_labels = np.round(echo_times, 1) -sns.barplot(x=te_labels, y=alpha, hue=te_labels, ax=ax, palette=pal, legend=False) -ax.set_ylabel("Weight", fontsize=16) -ax.set_xlabel("Echo Time (ms)", fontsize=16) -ax.tick_params(axis="both", which="major", labelsize=14) -fig.tight_layout() -glue_figure("fig_optcom_weights", fig, display=False) -``` - -```{figure} figures/fig_optcom_weights.png -:name: fig_optcom_weights -:align: center - -Averaging weights for optimal combination. -``` - -### Optimally combined timeseries - -```{code-cell} ipython3 -:tags: [hide-cell] -fig, ax = plt.subplots(figsize=(14, 6)) -for i_echo in range(n_echoes): - rep_echo_times = np.ones(n_trs) * echo_times[i_echo] - ax.scatter(rep_echo_times, ts[i_echo], alpha=0.05, color=pal[i_echo]) - -ax.plot(mono_x, mono_y) - -# Optimal combination -rep_t2s = np.ones(n_trs) * t2s -ax.scatter( - rep_t2s, oc_manual, alpha=0.9, color="red", label="Optimally\ncombined\ndata" -) - -ax.axvline(t2s, 0, 20000, label="$T_2^*$", color="black", linestyle="--", alpha=0.5) -ax.set_ylabel("BOLD signal", fontsize=16) -ax.set_xlabel("Echo Time (ms)", fontsize=16) -ax.set_xticks(np.hstack((echo_times, [np.round(t2s, 1)]))) -ax.set_xlim(0, 120) -ax.set_ylim(0, 24000) -ax.tick_params(axis="both", which="major", labelsize=14) -ax.xaxis.get_major_ticks()[-1].set_pad(20) - -legend = ax.legend(frameon=True, fontsize=16) - -fig.tight_layout() -glue_figure("fig_scatter_with_optcom", fig, display=False) -``` - -```{figure} figures/fig_scatter_with_optcom.png -:name: fig_scatter_with_optcom -:align: center - -Scatter plot of a voxel's signal for each echo with optimally combined signal as well. -``` - -### Optimally combined timeseries - -```{code-cell} ipython3 -:tags: [hide-cell] -fig, axes = plt.subplots(n_echoes + 1, sharex=True, sharey=False, figsize=(14, 6)) -for i_echo in range(n_echoes): - axes[i_echo].plot(ts[i_echo], color=pal[i_echo]) - axes[i_echo].set_ylabel( - f"{echo_times[i_echo]:.1f}ms", rotation=0, va="center", ha="right", fontsize=14 - ) - axes[i_echo].set_yticks([]) - axes[i_echo].set_xticks([]) - -axes[-1].plot(oc_manual, color="red") -axes[-1].set_ylabel( - "Optimally\ncombined\ndata", rotation=0, va="center", ha="right", fontsize=14 -) -axes[-1].set_xlabel("Time", fontsize=16) -axes[-1].set_yticks([]) -axes[-1].set_xticks([]) -axes[-1].set_xlim(0, len(ts[i_echo]) - 1) -ax.tick_params(axis="both", which="major", labelsize=14) -fig.tight_layout() -glue_figure("fig_echo_timeseries_with_optcom", fig, display=False) -``` - -```{figure} figures/fig_echo_timeseries_with_optcom.png -:name: fig_echo_timeseries_with_optcom -:align: center - -Echo-wise time series for a voxel, including the optimally combined time series. -``` - -### Multi-Echo Principal Components Analysis -Optimally combined data are decomposed with PCA. -The PCA components are selected according to one of multiple possible approaches. -Two possible approaches are a decision tree and a threshold using the percentage of variance explained by each component. - -```{code-cell} ipython3 -:tags: [hide-cell] -fig, axes = plt.subplots(3, sharex=True, figsize=(14, 6)) -axes[-1].set_xlim(0, mepca_mmix.shape[0] - 1) -axes[-1].set_xticks([]) -axes[-1].set_xlabel("Time", fontsize=16) - -for comp_to_plot in [0, 1, 2]: - axes[comp_to_plot].plot(mepca_mmix[:, comp_to_plot]) - axes[comp_to_plot].set_title(f"PCA Component {comp_to_plot}", fontsize=16) - axes[comp_to_plot].tick_params(axis="both", which="major", labelsize=12) - -fig.tight_layout() -glue_figure("fig_pca_timeseries", fig, display=False) -``` - -```{figure} figures/fig_pca_timeseries.png -:name: fig_pca_timeseries -:align: center - -Time series of three PCA components. -``` - -## Data Whitening -The selected components from the PCA are recombined to produce a whitened version of the optimally combined data. - -```{code-cell} ipython3 -:tags: [hide-cell] -fig, ax = plt.subplots(figsize=(14, 6)) -ax.plot(oc_red[:, voxel_idx], label="Dimensionally reduced timeseries", zorder=1.0) -ax.plot( - oc_z[:, voxel_idx], label="Original timeseries", alpha=0.5, zorder=0.0, linewidth=3 -) -legend = ax.legend(frameon=True, fontsize=16, loc="upper right", framealpha=1) -ax.set_xlim(0, oc_z.shape[0] - 1) -ax.set_xticks([]) -ax.set_xlabel("Time", fontsize=16) -ax.tick_params(axis="both", which="major", labelsize=14) -glue_figure("fig_optcom_reduced_timeseries", fig, display=False) -``` - -```{figure} figures/fig_optcom_reduced_timeseries.png -:name: fig_optcom_reduced_timeseries -:align: center - -Time series of optimally combined data from a voxel, before and after dimensionality reduction with PCA. -``` - -### Multi-Echo Independent Components Analysis -The whitened optimally combined data are then decomposed with ICA. -The number of ICA components is limited to the number of retained components from the PCA, -in order to reflect the true dimensionality of the data. -ICA produces a mixing matrix (i.e., timeseries for each component). - -```{code-cell} ipython3 -:tags: [hide-cell] -fig, axes = plt.subplots(3, sharex=True, figsize=(14, 6)) - -comps_to_plot = [high_kappa_comp, low_kappa_comp, "ICA_00"] - -for i_comp, comp_to_plot in enumerate(comps_to_plot): - idx = int(comp_to_plot.split("_")[1]) - k = comp_tbl.loc[comp_to_plot, "kappa"] - r = comp_tbl.loc[comp_to_plot, "rho"] - c = comp_tbl.loc[comp_to_plot, "classification"] - axes[i_comp].plot(meica_mmix[:, idx]) - axes[i_comp].set_title( - "ICA Component {0}; $\\kappa$ = {1:.02f}; $\\rho$ = {2:.02f}; {3}".format( - comp_to_plot, k, r, c - ), - fontsize=16, - ) - -axes[0].set_xlim(0, meica_mmix.shape[0] - 1) -axes[2].set_xticks([]) -axes[2].set_xlabel("Time", fontsize=16) -axes[0].tick_params(axis="both", which="major", labelsize=12) -axes[1].tick_params(axis="both", which="major", labelsize=12) -axes[2].tick_params(axis="both", which="major", labelsize=12) -fig.tight_layout() -glue_figure("fig_ica_timeseries", fig, display=False) -``` - -```{figure} figures/fig_ica_timeseries.png -:name: fig_ica_timeseries -:align: center - -Time series of three ICA components. -``` - -## $R_2^*$ and $S_0$ Model Fit -Linear regression is used to fit the component timeseries to each voxel in each echo from the original, echo-specific data. -This results in echo- and voxel-specific betas for each of the components. -TE-dependence ($R_2^*$) and TE-independence ($S_0$) models can then be fit to these betas. - -These models allow calculation of F-statistics for the $R_2^*$ and $S_0$ models (referred to as $\kappa$ and $\rho$, respectively). - -Note that the values here are for a single voxel (the highest-weighted one for the component), -but $\kappa$ and $\rho$ are averaged across voxels. - -```{code-cell} ipython3 -:tags: [hide-cell] -fig, axes = plt.subplots(3, sharex=True, figsize=(14, 9)) -axes[-1].set_xticks(echo_times) -axes[-1].tick_params(axis="both", which="major", labelsize=12) -axes[-1].set_xlabel("Echo Time (ms)", fontsize=16) - -# Only generate plots for a few components -for i_comp, comp in enumerate(comps_to_plot): - comp_idx = int(comp.split("_")[1]) - comp_voxel_idx = np.where(beta_maps[comp_idx, :] == np.max(beta_maps[comp_idx, :]))[0][0] - - # Use weight map to average as fitmodels_direct does - comp_weights = meica_betas[comp_voxel_idx, :, comp_idx] - r2_pred_weights = r2_pred_betas[comp_voxel_idx, :, comp_idx] - s0_pred_weights = s0_pred_betas[comp_voxel_idx, :, comp_idx] - - axes[i_comp].plot( - echo_times, - comp_weights, - c="black", - alpha=0.5, - linewidth=5, - label="Component PEs", - ) - axes[i_comp].plot( - echo_times, r2_pred_weights, c="blue", label="Predicted T2* model values" - ) - axes[i_comp].plot( - echo_times, s0_pred_weights, c="red", label="Predicted S0 model values" - ) - - # Set y-axis limits - temp = np.hstack((comp_weights, s0_pred_weights, r2_pred_weights)) - lim = np.mean(temp) * 0.05 - axes[i_comp].set_ylim(np.floor(np.min(temp)) - lim, np.ceil(np.max(temp)) + lim) - legend = axes[i_comp].legend(frameon=True, fontsize=14, ncol=3) - axes[i_comp].set_title(f"ICA Component {comp}", fontsize=16) - -fig.tight_layout() -glue_figure("fig_ica_weights", fig, display=False) -``` - -```{figure} figures/fig_ica_weights.png -:name: fig_ica_weights -:align: center - -Echo-wise model weights for three ICA components. -``` - -## ICA Component Selection and Multi-Echo Denoising -A decision tree is applied to $\kappa$, $\rho$, and other metrics in order to classify ICA components as TE-dependent (BOLD signal), -TE-independent (non-BOLD noise), or neither (to be ignored). - -The ICA components are fitted to the original (not whitened) optimally combined data with linear regression, -which is used to weight the components for construction of the denoised data. -The residuals from this regression will thus include the variance that was not included in the PCA-whitened optimally combined data. - -The {term}`MEDN` dataset is constructed from the accepted (BOLD) and ignored components, -as well as the residual variance not explained by the ICA. -The {term}`MEHK` dataset is constructed just from the accepted (BOLD) components. -This means that ignored components and residual variance not explained by the ICA are not included in the resulting dataset. - -```{code-cell} ipython3 -:tags: [hide-cell] -dn_data_z = (dn_data - np.mean(dn_data, axis=0)) / np.std(dn_data, axis=0) -hk_data_z = (hk_data - np.mean(hk_data, axis=0)) / np.std(hk_data, axis=0) - -fig, axes = plt.subplots(3, sharex=True, figsize=(14, 6)) -axes[0].plot(oc_z[:, voxel_idx], label="Optimally combined") -axes[0].set_title("Optimally combined", fontsize=16) - -axes[1].plot(dn_data_z[:, voxel_idx], label="ME-DN") -axes[1].set_title("ME-DN", fontsize=16) - -axes[2].plot(hk_data_z[:, voxel_idx]) -axes[2].set_title("ME-HK", fontsize=16) -axes[0].set_xlim(0, oc_z.shape[0] - 1) -axes[2].set_xticks([]) -axes[2].set_xlabel("Time", fontsize=16) -axes[0].tick_params(axis="both", which="major", labelsize=12) -axes[1].tick_params(axis="both", which="major", labelsize=12) -axes[2].tick_params(axis="both", which="major", labelsize=12) -fig.tight_layout() - -glue_figure("fig_medn_timeseries", fig, display=False) -``` - -```{figure} figures/fig_medn_timeseries.png -:name: fig_medn_timeseries -:align: center - -Time series for optimally combined, denoised, and high-kappa data for a single voxel. -``` - -## Post-processing to remove spatially diffuse noise -Due to the constraints of ICA, MEICA is able to identify and remove spatially localized noise components, -but it cannot identify components that are spread out throughout the whole brain. - -One of several post-processing strategies may be applied to the ME-DN or ME-HK datasets in order to remove spatially diffuse -(ostensibly respiration-related) noise. -Methods which have been employed in the past include global signal regression (GSR), -{prf:ref}`Minimum Image Regression `, anatomical CompCor, Go Decomposition (GODEC), and robust PCA. - -```{code-cell} ipython3 -:tags: [hide-cell] -dn_t1c_data_z = (dn_t1c_data - np.mean(dn_t1c_data, axis=0)) / np.std( - dn_t1c_data, axis=0 -) -hk_t1c_data_z = (hk_t1c_data - np.mean(hk_t1c_data, axis=0)) / np.std( - hk_t1c_data, axis=0 -) - -fig, axes = plt.subplots(2, sharex=True, figsize=(14, 6)) -axes[0].plot(dn_t1c_data_z[:, voxel_idx], label="ME-DN T1c") -axes[0].plot(dn_data_z[:, voxel_idx], label="ME-DN", alpha=0.5, linewidth=3, zorder=0.0) -axes[0].set_title("ME-DN", fontsize=16) -legend = axes[0].legend(frameon=True, loc="upper right") - -axes[1].plot(hk_t1c_data_z[:, voxel_idx], label="ME-HK T1c") -axes[1].plot(hk_data_z[:, voxel_idx], label="ME-HK", alpha=0.5, linewidth=3, zorder=0.0) -axes[1].set_title("ME-HK", fontsize=16) -legend = axes[1].legend(frameon=True) -axes[0].set_xlim(0, oc_z.shape[0] - 1) -axes[1].set_xticks([]) -axes[1].set_xlabel("Time", fontsize=16) -axes[0].tick_params(axis="both", which="major", labelsize=12) -axes[1].tick_params(axis="both", which="major", labelsize=12) -fig.tight_layout() -glue_figure("fig_mir_timeseries", fig, display=False) -``` - -```{figure} figures/fig_mir_timeseries.png -:name: fig_mir_timeseries -:align: center - -Time series from a voxel before and after {prf:ref}`minimum image regression `. -```