Skip to content

Instantly share code, notes, and snippets.

@emdupre
Last active November 30, 2017 20:02
Show Gist options
  • Select an option

  • Save emdupre/af4d83ac44f5121e92683debd28168e5 to your computer and use it in GitHub Desktop.

Select an option

Save emdupre/af4d83ac44f5121e92683debd28168e5 to your computer and use it in GitHub Desktop.
Cleaned up makeadmask
def create_last_echo_mask(echo_list):
"""
Make a map of longest echo that a voxel can be sampled with,
with minimum value of map as X value of voxel that has median
value in the 1st echo. N.B. larger factor leads to bias to lower TEs
**Inputs**
echo_list
List of file names for all echos of interest
**Outputs**
last_echo_mask
A numpy array whose values correspond to which echos
a voxel can last be sampled with
"""
# First, load each echo and average over time
echos = []
for e in echo_list:
echos.append(np.mean(nib.load(e).get_data(), axis = -1))
# In the first echo, find the 33rd percentile and the voxel(s)
# whose average activity is equal to that value
med_val = np.percentile(echos[0][np.nonzero(echos[0])],
33, interpolation="higher")
vox = echos[0] == med_val
# For each (averaged) echo, extract the max signal in the
# identified voxels and divide it by 3-- save as a threshold
thrs = np.empty(len(echos))
for echo in echos:
np.append(thrs, np.max(echo[vox]) / 3)
# Let's stack the arrays to make this next bit easier
echo_means = np.stack(echos, axis=-1)
# Now, we want to find all voxels (in each echo) that show
# absolute signal greater than our echo-specific threshold
mthr = np.ones(echo_means.shape)
for i in range(echo_means.shape[-1]):
mthr[:, :, :, i] *= thrs[i]
voxels = np.abs(echo_means) > mthr
# We save those voxel indices out to an array
last_echo_mask = np.array(voxels, dtype=np.int).sum(-1)
return last_echo_mask
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment