# 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-03-Filtering" / "04-B1-03-Filtering"
data_file = "b1filt_fig5.mat"
#Load either archived or generated plot variables
mat_contents = sio.loadmat(data_dir / data_file)
b1_func = mat_contents["b1_func"][0]
delta_b1= mat_contents["delta_b1"][0]
gauss_b1_1d = mat_contents["gauss_b1_1d"]
median_b1_1d = mat_contents["median_b1_1d"]
spline_b1_1d = mat_contents["spline_b1_1d"]
vox_range = mat_contents["vox_range"][0]
## Plot
import matplotlib.pyplot as plt
import plotly.graph_objs as go
import numpy as np
from plotly import __version__
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
from plotly.subplots import make_subplots
config={'showLink': False, 'displayModeBar': False}
init_notebook_mode(connected=True)
# PYTHON CODE
init_notebook_mode(connected=True)
## Setup for plots
fig = make_subplots(rows=2, cols=2, vertical_spacing = 0.06,
subplot_titles=(
'<b>Unfiltered</b>',
'<b>Gaussian</b>',
'<b>Median</b>',
'<b>Spline</b>',))
position = np.arange(1,len(b1_func)+1)
b1_data = [dict(
visible = False,
x = position,
y = b1_func,
name = "True signal",
hoverinfo = "y",
showlegend=False) for ii in range(len(vox_range))]
b1_data[2]['visible'] = True
b1_data[2]['showlegend'] = True
delta_signal = [dict(
visible = False,
x = position,
y = delta_b1,
name = "Noisy signal",
hoverinfo = "y",
showlegend=False) for ii in range(len(vox_range))]
delta_signal[2]['visible'] = True
delta_signal[2]['showlegend'] = True
gauss_b1 = [dict(
visible = False,
x = position,
y = list(gauss_b1_1d[ii]),
name = "Gaussian filtered",
hoverinfo = "y",
showlegend=False) for ii in range(len(vox_range))]
gauss_b1[2]['visible'] = True
gauss_b1[2]['showlegend'] = True
median_b1 = [dict(
visible = False,
x = position,
y = list(median_b1_1d[ii]),
name = "Median filtered",
hoverinfo = "y",
showlegend=False) for ii in range(len(vox_range))]
median_b1[2]['visible'] = True
median_b1[2]['showlegend'] = True
spline_b1 = [dict(
visible = False,
x = position,
y = list(spline_b1_1d[ii]),
name = "Spline interpolation",
hoverinfo = "y",
showlegend=False) for ii in range(len(vox_range))]
spline_b1[2]['visible'] = True
spline_b1[2]['showlegend'] = True
# Add traces
for ii in range(len(vox_range)):
fig.add_trace(go.Scatter(b1_data[ii], line=dict(color="black", width=2)), row= 1, col=1)
for ii in range(len(vox_range)):
fig.add_trace(go.Scatter(delta_signal[ii], line=dict(color="grey", width=2)), row= 1, col=1)
b1_data[2]['showlegend'] = False
delta_signal[2]['showlegend'] = False
for ii in range(len(vox_range)):
fig.add_trace(go.Scatter(gauss_b1[ii], line=dict(color="red", width=3)), row= 1, col=2)
for ii in range(len(vox_range)):
fig.add_trace(go.Scatter(b1_data[ii], line=dict(color="black", width=1)), row= 1, col=2)
for ii in range(len(vox_range)):
fig.add_trace(go.Scatter(delta_signal[ii], line=dict(color="grey", width=1)), row= 1, col=2)
for ii in range(len(vox_range)):
fig.add_trace(go.Scatter(median_b1[ii], line=dict(color="blue", width=3)), row= 2, col=1)
for ii in range(len(vox_range)):
fig.add_trace(go.Scatter(b1_data[ii], line=dict(color="black", width=1)), row= 2, col=1)
for ii in range(len(vox_range)):
fig.add_trace(go.Scatter(delta_signal[ii], line=dict(color="grey", width=1)), row= 2, col=1)
for ii in range(len(vox_range)):
fig.add_trace(go.Scatter(spline_b1[ii], line=dict(color="green", width=3)), row= 2, col=2)
for ii in range(len(vox_range)):
fig.add_trace(go.Scatter(b1_data[ii], line=dict(color="black", width=1)), row= 2, col=2)
for ii in range(len(vox_range)):
fig.add_trace(go.Scatter(delta_signal[ii], line=dict(color="grey", width=1)), row= 2, col=2)
# Create and add slider
steps = []
for i in range(len(vox_range)):
step = dict(
method="update",
args=[{"visible": [False] * len(fig.data), "showlegend": [False] * len(fig.data)},], # layout attribute
label = str(i+1)
)
step["args"][0]["visible"][i] = True # Toggle i'th trace to "visible"
step["args"][0]["visible"][i+1*len(vox_range)] = True # Toggle i'th trace to "visible"
step["args"][0]["visible"][i+2*len(vox_range)] = True # Toggle i'th trace to "visible"
step["args"][0]["visible"][i+3*len(vox_range)] = True # Toggle i'th trace to "visible"
step["args"][0]["visible"][i+4*len(vox_range)] = True # Toggle i'th trace to "visible"
step["args"][0]["visible"][i+5*len(vox_range)] = True # Toggle i'th trace to "visible"
step["args"][0]["visible"][i+6*len(vox_range)] = True # Toggle i'th trace to "visible"
step["args"][0]["visible"][i+7*len(vox_range)] = True # Toggle i'th trace to "visible"
step["args"][0]["visible"][i+8*len(vox_range)] = True # Toggle i'th trace to "visible"
step["args"][0]["visible"][i+9*len(vox_range)] = True # Toggle i'th trace to "visible"
step["args"][0]["visible"][i+10*len(vox_range)] = True # Toggle i'th trace to "visible"
step["args"][0]["showlegend"][i] = True # Toggle i'th trace to "visible"
step["args"][0]["showlegend"][i+1*len(vox_range)] = True # Toggle i'th trace to "visible"
step["args"][0]["showlegend"][i+2*len(vox_range)] = True # Toggle i'th trace to "visible"
step["args"][0]["showlegend"][i+5*len(vox_range)] = True # Toggle i'th trace to "visible"
step["args"][0]["showlegend"][i+8*len(vox_range)] = True # Toggle i'th trace to "visible"
steps.append(step)
sliders = [dict(
active=2,
currentvalue={"prefix": "Filter strength: "},
pad={"t": 50},
steps=steps
)]
layout = go.Layout(
width=750,
height=750,
margin=go.layout.Margin(
l=100,
r=80,
b=100,
t=130,
),
annotations=[
dict(
x=-0.15,
y=0.50,
showarrow=False,
text='Signal',
font=dict(
family='Times New Roman',
size=22
),
textangle=-90,
xref='paper',
yref='paper'
),
],
xaxis=dict(
showgrid=True,
gridcolor='rgb(169,169,169)',
linecolor='black',
linewidth=2
),
yaxis=dict(
showgrid=True,
gridcolor='rgb(169,169,169)',
linecolor='black',
linewidth=2
),
legend=dict(
x=0.25,
y=1.3,
traceorder='normal',
font=dict(
family='Times New Roman',
size=12,
color='#000'
),
bordercolor='#000000',
borderwidth=2
),
sliders=sliders
)
fig.update_layout(layout)
iplot(fig, filename = 'fig5.html', config = config)
Loading...