Skip to article frontmatterSkip to article content
import scipy
import scipy.io as sio
from pathlib import Path
import numpy as np

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 / "06-MT-01-qMT" / "06-MT-01-qMT" 

#Percentage error

b1NormFittedData_mat = scipy.io.loadmat(data_dir / 'qMT_tutorial-ISMRM2022-main' / 'results/fitSyntheticData/b1NormFittedResults.mat')
b1NormFittedData = np.array(b1NormFittedData_mat["b1NormFittedResults"])

b0NormFittedData_mat = scipy.io.loadmat(data_dir / 'qMT_tutorial-ISMRM2022-main' / 'results/fitSyntheticData/b0NormFittedResults.mat')
b0NormFittedData = np.array(b0NormFittedData_mat["b0NormFittedResults"])

t1NormFittedData_mat = scipy.io.loadmat(data_dir / 'qMT_tutorial-ISMRM2022-main' / 'results/fitSyntheticData/t1NormFittedResults.mat')
t1NormFittedData = np.array(t1NormFittedData_mat["t1NormFittedResults"])


import matplotlib.pyplot as plt
from PIL import Image
from matplotlib.image import imread
import scipy.io
import plotly
from plotly.subplots import make_subplots
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
config={'showLink': False, 'displayModeBar': False}

# PYTHON CODE
init_notebook_mode(connected=True)

labels = ["B1 map", "B0 map", "T1 map"]
FittedParams = ["F", "kf (s<sup>-1</sup>)", "T2,f (s)", "T2,r"]

fig = make_subplots(rows=2, cols=2)

#F
trace1_b1 = go.Scatter(x=b1NormFittedData[:,0], y=b1NormFittedData[:,1],
                       name="F", mode='lines', line=dict(color="royalblue"), visible=True,
                       hovertemplate="Error (%) = %{y}<br>B1 value = %{x} <extra></extra>")
trace1_b0 = go.Scatter(x=b0NormFittedData[:,0], y=b0NormFittedData[:,1],
                       name="F", mode='lines', line=dict(color="royalblue"), visible=False,
                       hovertemplate="Error (%) = %{y}<br>B0 value = %{x} Hz<extra></extra>")
trace1_t1 = go.Scatter(x=t1NormFittedData[:,0], y=t1NormFittedData[:,1],
                       name="F", mode='lines', line=dict(color="royalblue"), visible=False,
                       hovertemplate="Error (%) = %{y}<br>T1 value = %{x} s<extra></extra>")

fig.append_trace(trace1_b1, 1, 1)
fig.append_trace(trace1_b0, 1, 1)
fig.append_trace(trace1_t1, 1, 1)

#kf
trace2_b1 = go.Scatter(x=b1NormFittedData[:,0], y=b1NormFittedData[:,2],
                       name="kf", mode='lines', line=dict(color="royalblue"), visible=True,
                       hovertemplate="Error (%) = %{y}<br>B1 value = %{x} <extra></extra>")
trace2_b0 = go.Scatter(x=b0NormFittedData[:,0], y=b0NormFittedData[:,2],
                       name="kf", mode='lines', line=dict(color="royalblue"), visible=False,
                       hovertemplate="Error (%) = %{y}<br>B0 value = %{x} Hz<extra></extra>")
trace2_t1 = go.Scatter(x=t1NormFittedData[:,0], y=t1NormFittedData[:,2],
                       name="kf", mode='lines', line=dict(color="royalblue"), visible=False,
                       hovertemplate="Error (%) = %{y}<br>T1 value = %{x} s<extra></extra>")

fig.append_trace(trace2_b1, 1, 2)
fig.append_trace(trace2_b0, 1, 2)
fig.append_trace(trace2_t1, 1, 2)

#T2f
trace3_b1 = go.Scatter(x=b1NormFittedData[:,0], y=b1NormFittedData[:,3],
                       name="kf", mode='lines', line=dict(color="royalblue"), visible=True,
                       hovertemplate="Error (%) = %{y}<br>B1 value = %{x} <extra></extra>")
trace3_b0 = go.Scatter(x=b0NormFittedData[:,0], y=b0NormFittedData[:,3],
                       name="kf", mode='lines', line=dict(color="royalblue"), visible=False,
                       hovertemplate="Error (%) = %{y}<br>B0 value = %{x} Hz<extra></extra>")
trace3_t1 = go.Scatter(x=t1NormFittedData[:,0], y=t1NormFittedData[:,3],
                       name="kf", mode='lines', line=dict(color="royalblue"), visible=False,
                       hovertemplate="Error (%) = %{y}<br>T1 value = %{x} s<extra></extra>")

fig.append_trace(trace3_b1, 2, 1)
fig.append_trace(trace3_b0, 2, 1)
fig.append_trace(trace3_t1, 2, 1)

#T2r
trace4_b1 = go.Scatter(x=b1NormFittedData[:,0], y=b1NormFittedData[:,4],
                       name="kf", mode='lines', line=dict(color="royalblue"), visible=True,
                       hovertemplate="Error (%) = %{y}<br>B1 value = %{x} <extra></extra>")
trace4_b0 = go.Scatter(x=b0NormFittedData[:,0], y=b0NormFittedData[:,4],
                       name="kf", mode='lines', line=dict(color="royalblue"), visible=False,
                       hovertemplate="Error (%) = %{y}<br>B0 value = %{x} Hz<extra></extra>")
trace4_t1 = go.Scatter(x=t1NormFittedData[:,0], y=t1NormFittedData[:,4],
                       name="kf", mode='lines', line=dict(color="royalblue"), visible=False,
                       hovertemplate="Error (%) = %{y}<br>T1 value = %{x} s<extra></extra>")

fig.append_trace(trace4_b1, 2, 2)
fig.append_trace(trace4_b0, 2, 2)
fig.append_trace(trace4_t1, 2, 2)

buttons = []
for i, label in enumerate(labels):
    visibility = [i==j for j in range(len(labels))]
    button = dict(
                label =  label,
                method = 'update',
                args = [{'visible': visibility}])
    buttons.append(button)
        
updatemenus = list([
    dict(active=0,
         x=0.65,
         y=1.1,
         buttons=buttons
    )
])

fig['layout']['showlegend'] = False
fig['layout']['updatemenus'] = updatemenus

fig.update_xaxes(title_text='Input map', title_font=dict(family='Times New Roman', size=18),
                 row=1, col=1, showline=True, linewidth=2, linecolor='black')
fig.update_xaxes(title_text='Input map', title_font=dict(family='Times New Roman', size=18),
                 row=1, col=2, showline=True, linewidth=2, linecolor='black')
fig.update_xaxes(title_text='Input map', title_font=dict(family='Times New Roman', size=18),
                 row=2, col=1, showline=True, linewidth=2, linecolor='black')
fig.update_xaxes(title_text='Input map', title_font=dict(family='Times New Roman', size=18),
                 row=2, col=2, showline=True, linewidth=2, linecolor='black')
fig.update_yaxes(range=[-100,100], row=1, col=1, showline=True, linewidth=2, linecolor='black')
fig.update_yaxes(range=[-100,100], row=1, col=2, showline=True, linewidth=2, linecolor='black')
fig.update_yaxes(range=[-100,100], row=2, col=1, showline=True, linewidth=2, linecolor='black')
fig.update_yaxes(range=[-100,100], row=2, col=2, showline=True, linewidth=2, linecolor='black')

fig.update_layout(height=500, width=600, plot_bgcolor='rgba(0,0,0,0)')
fig.update_layout(annotations=[
    dict(
        x=0.20,
        y=1.1,
        showarrow=False,
        text='Input map: ',
        font=dict(
            family='Times New Roman',
            size=22
            ),
        xref='paper',
        yref='paper'
        ),
    dict(
        x=-0.1,
        y=0.90,
        showarrow=False,
        text='% Error in ' + FittedParams[0],
        font=dict(
            family='Times New Roman',
            size=18
            ),
        textangle=-90,
        xref='paper',
        yref='paper'
        ),
    dict(
        x=0.48,
        y=0.98,
        showarrow=False,
        text='% Error in ' + FittedParams[1],
        font=dict(
            family='Times New Roman',
            size=18
            ),
        textangle=-90,
        xref='paper',
        yref='paper'
        ),
    dict(
        x=-0.1,
        y=0.03,
        showarrow=False,
        text='% Error in ' + FittedParams[2],
        font=dict(
            family='Times New Roman',
            size=18
            ),
        textangle=-90,
        xref='paper',
        yref='paper'
        ),
    dict(
        x=0.48,
        y=0.07,
        showarrow=False,
        text='% Error in ' + FittedParams[3],
        font=dict(
            family='Times New Roman',
            size=18
            ),
        textangle=-90,
        xref='paper',
        yref='paper'
        )
])
fig.update_layout(plot_bgcolor='rgba(0,0,0,0)',
                 margin=go.layout.Margin(
                     l=120,
                     r=40,
                     b=60,
                     t=50,
                     )
                 )
fig.update_layout()

iplot(fig, filename='basic-line', config=config)
Loading...