# Prepare Python environment
import scipy.io as sio
from pathlib import Path
from contextlib import contextmanager
import sys, os
from pathlib import Path
@contextmanager
def suppress_stdout():
with open(os.devnull, "w") as devnull:
old_stdout = sys.stdout
sys.stdout = devnull
try:
yield
finally:
sys.stdout = old_stdout
import os
from pathlib import Path
def find_myst_yml_directories(start_dir=None):
"""
Recursively search for directories containing myst.yml file.
Args:
start_dir (str or Path): Starting directory (defaults to current directory)
Returns:
list: List of full paths to directories containing myst.yml
"""
if start_dir is None:
start_dir = Path.cwd()
else:
start_dir = Path(start_dir)
myst_dirs = []
def _search_directory(current_dir):
# Check if myst.yml exists in current directory
myst_file = current_dir / "myst.yml"
if myst_file.exists():
myst_dirs.append(str(current_dir.resolve()))
# Don't search subdirectories if we found myst.yml here
return
# Recursively search all subdirectories
for item in current_dir.iterdir():
if item.is_dir():
try:
_search_directory(item)
except (PermissionError, OSError):
# Skip directories we can't access
continue
_search_directory(start_dir)
return myst_dirs
def find_myst_yml_directories_upwards(start_dir=None):
"""
Search for myst.yml in current directory, if not found go to parent and repeat.
Args:
start_dir (str or Path): Starting directory (defaults to current directory)
Returns:
str or None: Full path of directory containing myst.yml, or None if not found
"""
if start_dir is None:
current_dir = Path.cwd()
else:
current_dir = Path(start_dir)
# Keep going up until we reach the filesystem root
while current_dir != current_dir.parent: # Stop at root
myst_file = current_dir / "myst.yml"
if myst_file.exists():
return str(current_dir.resolve())
# Move to parent directory
current_dir = current_dir.parent
return None
with suppress_stdout():
repo_path = Path(find_myst_yml_directories_upwards())
print(repo_path)
data_req_path = repo_path / "binder" / "data_requirement.json"
data_path = repo_path / "data"
dataset_path = data_path / "qmrlab-mooc"
data_dir = dataset_path / "04-B1-04-BlochSiegert" / "04-B1-04-BlochSiegert"
import nibabel as nib
import numpy as np
def load(name):
return np.asarray(nib.load(data_dir / name).get_fdata())
# One axial slice (2 x 2 x 5 mm), rows anterior to posterior: the two phase images (radians) of the
# Bloch-Siegert acquisition with the off-resonance pulse at +4 kHz and -4 kHz, and the resulting B1 map
phase_pos = load("bs_phase_pos.nii.gz")
phase_neg = load("bs_phase_neg.nii.gz")
B1map = load("b1_clt_gre_bs_cr_fermi.nii.gz")
mask = load("brain_mask_es_2x2x5.nii.gz")
## Plot
import plotly.graph_objs as go
from plotly.offline import init_notebook_mode, iplot
config={'showLink': False, 'displayModeBar': False}
init_notebook_mode(connected=True)
B1map_masked = np.where(mask > 0.5, B1map, np.nan)
yAxis = np.arange(phase_pos.shape[0])
xAxis = np.arange(phase_pos.shape[1])
# Phase: blue-white-red like the B1 map, but with its own colour bar, from -pi to pi
phase_bar = dict(x=0.43, len=0.85, y=0.54, thickness=14, title=dict(text='rad', font=dict(family='Times New Roman', size=18)), tickvals=[-np.pi, 0, np.pi], ticktext=['−π', '0', 'π'],
tickfont=dict(family='Times New Roman', size=16))
trace1 = go.Heatmap(x=xAxis, y=yAxis, z=phase_pos, zmin=-np.pi, zmax=np.pi,
colorscale='RdBu', reversescale=True, showscale=True, colorbar=phase_bar,
visible=True, name='Phase, +4 kHz', hovertemplate='phase = %{z:.2f} rad<extra></extra>')
trace2 = go.Heatmap(x=xAxis, y=yAxis, z=phase_neg, zmin=-np.pi, zmax=np.pi,
colorscale='RdBu', reversescale=True, showscale=True, colorbar=phase_bar,
visible=False, name='Phase, -4 kHz', hovertemplate='phase = %{z:.2f} rad<extra></extra>')
trace3 = go.Heatmap(x=xAxis, y=yAxis, z=B1map_masked, zmin=0.7, zmax=1.3,
colorscale='RdBu', reversescale=True, # blue = low, red = high
colorbar=dict(x=1.0, len=0.85, y=0.54, thickness=14, tickfont=dict(family='Times New Roman', size=16)),
xaxis='x2', yaxis='y2', visible=True, name='B1 values',
hovertemplate='B<sub>1</sub> = %{z:.2f}<extra></extra>')
data = [trace1, trace2, trace3]
updatemenus = list([
dict(active=0,
x=0.09,
xanchor='left',
y=-0.12,
yanchor='bottom',
direction='up',
font=dict(family='Times New Roman', size=16),
buttons=list([
dict(label='Phase, Δ = +4 kHz', method='update', args=[{'visible': [True, False, True]}]),
dict(label='Phase, Δ = −4 kHz', method='update', args=[{'visible': [False, True, True]}]),
])
)
])
axis = dict(showgrid=False, zeroline=False, showticklabels=False, ticks='')
layout = dict(
width=640,
height=430,
margin=dict(t=50, r=50, b=10, l=50),
annotations=[
dict(x=0.07, y=1.13, showarrow=False, text='Input Data', font=dict(family='Times New Roman', size=26), xref='paper', yref='paper'),
dict(x=0.74, y=1.13, showarrow=False, text='Raw B<sub>1</sub> map', font=dict(family='Times New Roman', size=26), xref='paper', yref='paper'),
dict(x=1.04, y=1.13, showarrow=False, text='B<sub>1</sub>', font=dict(family='Times New Roman', size=26), xref='paper', yref='paper'),
],
xaxis=dict(axis, domain=[0, 0.4]),
yaxis=dict(axis, autorange='reversed', scaleanchor='x', domain=[0.08, 1]),
xaxis2=dict(axis, domain=[0.55, 0.95]),
yaxis2=dict(axis, autorange='reversed', scaleanchor='x2', domain=[0.08, 1], anchor='x2'),
showlegend=False,
autosize=False,
updatemenus=updatemenus
)
fig = dict(data=data, layout=layout)
iplot(fig, filename='basic-heatmap', config=config)
Loading...
Loading...