# Prepare Python environment
import numpy as np
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 / "03-T2" / "03-T2"
data_file = "multiexpo_T2_curves.mat"
#Load either archived or generated plot variables
mat_contents = sio.loadmat(data_dir / data_file)
# Get the signals and parameters from Matlab
# Signals
signal_mono_MW = np.array(mat_contents['signal_mono_MW'][0])
signal_mono_IEW = np.array(mat_contents['signal_mono_IEW'][0])
signal_multi_MWF = np.array(mat_contents['signal_multi_MWF'][0])
# MWF from simulation
FitResult = mat_contents['FitResult']
MWF = np.round(FitResult['MWF'][0][0]/100, 2)
# TE
params = mat_contents['params']
TE = params['TE'][0][0][0]
# Initialize MWF values for interactive multi-expo curve
interactive_multiexpo_signal = MWF*signal_mono_MW + (1-MWF)*signal_mono_IEW
## Plot
import matplotlib.pyplot as plt
import chart_studio.plotly as py
import plotly.graph_objs as go
import numpy as np
from plotly import __version__
from plotly.offline import iplot
config={'showLink': False, 'displayModeBar': False}
# Mono-exponential myelin water (MW) signal
MW_T2 = go.Scatter(
x = TE,
y = signal_mono_MW,
name = 'Mono-exponential : Myelin water (MW)',
text = 'Myelin Water (MW)',
hoverinfo = 'x+y+text',
line=dict(color='#2ca02c'),
visible = True
)
# Mono-exponential intra- and extracellular water (IEW) signal
IEW_T2 = go.Scatter(
x = TE,
y = signal_mono_IEW,
name = 'Mono-exponential : Intra- and extracellular water (IEW)',
text = 'Intra- and Extracellular Water (IEW)',
hoverinfo = 'x+y+text',
line=dict(color='#ff7f0e'),
visible = True
)
# Interactive multi-exponential signal (with slider on interactive figure)
multiexpo_T2_inter = go.Scatter(
x = TE,
y = interactive_multiexpo_signal[0],
name = f'Multi-exponential : MW + IEW',
text = f'Interactive multi-expo T2',
hoverinfo = 'x+y+text',
line=dict(color='#9467bd',dash='dot'),
visible = True,
)
data = [MW_T2, IEW_T2, multiexpo_T2_inter]
# Define steps for slider
steps = []
for value_slider in np.arange(0, 1.05, 0.05): # For slider with 5% increments
interactive_multiexpo_signal = value_slider* signal_mono_MW + (1-value_slider) * signal_mono_IEW
steps.append(
dict(
method='update',
args=[
{'y': [signal_mono_MW, signal_mono_IEW, interactive_multiexpo_signal]},
{'visible': [True, True, True]},
{'name': f'{int(value_slider*100)}% MW {int((1-value_slider)*100)}% IEW'},
],
label=f'<b>{int(value_slider*100)}% MW {int((1-value_slider)*100)}% IEW</b>',
)
)
layout = go.Layout(
width=670,
height=475,
margin=go.layout.Margin(
l=100,
r=50,
b=30,
t=30,
),
sliders = [
dict(
steps=steps,
active = int(MWF[0][0] * 20),
len = 1.0,
pad = {'t':50},
)
],
annotations=[
dict(
x=0.5004254919715793,
y=-0.175,
showarrow=False,
text='Echo Time – TE (ms)',
font=dict(
family='Times New Roman',
size=22
),
xref='paper',
yref='paper'
),
dict(
x=-0.15,
y=0.50,
showarrow=False,
text='Transverse Magnetization (M<sub>xy</sub>)',
font=dict(
family='Times New Roman',
size=22
),
textangle=-90,
xref='paper',
yref='paper'
),
],
xaxis=dict(
showgrid=False,
linecolor='black',
linewidth=2,
),
yaxis=dict(
showgrid=False,
linecolor='black',
linewidth=2
),
legend=dict(
x=0.36,
y=0.97,
traceorder='normal',
font=dict(
family='Times New Roman',
size=12,
color='#000'
),
bordercolor='#000000',
borderwidth=2
)
)
fig = dict(data=data, layout=layout)
iplot(fig, filename = 'ir_fig_2.html', config = config)Loading...