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" 

# Simulations have been performed and the results have been saved in the folder results.
dataSim_model_mat = scipy.io.loadmat(data_dir / 'qMT_tutorial-ISMRM2022-main' / 'results/dataSim_model.mat')
dataRaw_model_mat = scipy.io.loadmat(data_dir / 'qMT_tutorial-ISMRM2022-main' / 'results/dataRaw_model.mat')
dataSim_model = np.array(dataSim_model_mat["dataSim_modelFit"])
dataRaw_model = np.array(dataRaw_model_mat["dataRaw_modelFit"])

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

# PYTHON CODE

init_notebook_mode(connected=True)

fitModel = ["Sled Pike RP", "Sled Pike CW", "Yarnykh", "Ramani"]

fig = go.Figure()

#Add traces (three traces per fitting model)
for ii in range(len(fitModel)):
    if ii==0:
        vis = True
    else:
        vis = False
    fig.add_trace(go.Scatter(x=dataSim_model[:,0,0], y=dataSim_model[:,1,ii],
                             name="Fitted curve (angle = 142)", mode='lines', line=dict(color="firebrick"), visible = vis,
                             hovertemplate="Fitted curve (angle = 142)<br>M<sub>z</sub> = %{y}<br>Offset = %{x} Hz<extra></extra>"))
    
    fig.add_trace(go.Scatter(x=dataSim_model[:,0,0], y=dataSim_model[:,2,ii],
                             name="Fitted curve (angle = 426)", mode='lines', line=dict(color="royalblue"), visible = vis,
                             hovertemplate="Fitted curve (angle = 426)<br>M<sub>z</sub> = %{y}<br>Offset = %{x} Hz<extra></extra>"))
    
    fig.add_trace(go.Scatter(x=dataRaw_model[:,0,0], y=dataRaw_model[:,1,ii],
                             name="Raw data", mode='markers', line=dict(color="darkslategray"), visible = vis,
                             hovertemplate="Raw data<br>M<sub>z</sub> = %{y}<br>Offset = %{x} Hz<extra></extra>"))


buttons = []
for i, label in enumerate(fitModel):
    visibility = [False] * 12
    for j in range(3):
        visibility[3*i+j] = True
    button = dict(
                label =  label,
                method = 'update',
                args = [{'visible': visibility}])
    buttons.append(button)
        
updatemenus = list([
    dict(active=0,
         x=0.88,
         y=1.1,
         buttons=buttons
    )
])

fig['layout']['updatemenus'] = updatemenus

fig.update_layout(height=450, width=580, plot_bgcolor='rgba(0,0,0,0)')
fig.update_layout(legend=dict(
        x=0.55,
        y=0.1,
        traceorder='normal',
        font=dict(
            family='Times New Roman',
            size=12,
            color='#000'
        ),
        bordercolor='#000000',
        borderwidth=2),
    annotations=[
        dict(
            x=0.35,
            y=1.1,
            showarrow=False,
            text='Fitting method: ',
            font=dict(
                family='Times New Roman',
                size=22
            ),
            xref='paper',
            yref='paper'
        ),
        dict(
            x=0.5004254919715793,
            y=-0.2,
            showarrow=False,
            text='Frequency offset \u0394 (Hz)',
            font=dict(
                family='Times New Roman',
                size=22
            ),
            xref='paper',
            yref='paper'
        ),
        dict(
            x=-0.14,
            y=0.5,
            showarrow=False,
            text='Magnetization |M<sub>z</sub>|',
            font=dict(
                family='Times New Roman',
                size=22
            ),
            textangle=-90,
            xref='paper',
            yref='paper'
        ),
    ])

fig.update_xaxes(type="log", range=[2,5], showline=True, linewidth=2, linecolor='black', dtick=1, tickvals=[100,1000,10000,100000], ticktext=["10<sup>2</sup>","10<sup>3</sup>","10<sup>4</sup>","10<sup>5</sup>"])
fig.update_yaxes(showline=True, linewidth=2, linecolor='black')

iplot(fig, filename='dropdown')
Loading...