Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

# 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 = "t2_noise_simulation.mat"

#Load either archived or generated plot variables
mat_contents = sio.loadmat(data_dir / data_file)

# Get the signals and parameters from Matlab

# Get matlab signals
signal_SNR10 =  mat_contents['signal_SNR10'][0]
signal_SNR50 =  mat_contents['signal_SNR50'][0]
signal_SNR90 =  mat_contents['signal_SNR90'][0]
signal_SNR130 =  mat_contents['signal_SNR130'][0]

# Get T2 constants from matlab simulation
T2_SNR10 =  mat_contents['T2_SNR10'][0]
T2_SNR50 =  mat_contents['T2_SNR50'][0]
T2_SNR90 =  mat_contents['T2_SNR90'][0]
T2_SNR130 =  mat_contents['T2_SNR130'][0]

# TE 
params =  mat_contents['params'][0]
TE_signals =  params['TE'][0][0]
TE =  params['TE'][0][0]

# Noisy data
SEdata_SNR10 =  np.squeeze(mat_contents['SEdata_SNR10'])
SEdata_SNR50 =  np.squeeze(mat_contents['SEdata_SNR50'])
SEdata_SNR90 =  np.squeeze(mat_contents['SEdata_SNR90'])
SEdata_SNR130 =  np.squeeze(mat_contents['SEdata_SNR130'])
TE_datapoints =  np.squeeze(mat_contents['EchoTimes'])
TE_datapoints =  np.squeeze(mat_contents['EchoTimes'])

## Plot
import matplotlib.pyplot as plt
import chart_studio.plotly as py
import plotly.graph_objs as go
import numpy as np
from plotly.offline import iplot

config={'showLink': False, 'displayModeBar': False}

# T2 signals with different SNRs

## SNR = 10 

SNR10 = go.Scatter(
    x = TE_signals,
    y = signal_SNR10,
    name = f'T<sub>2</sub> Fitting (T<sub>2</sub> = {T2_SNR10})',
    text = f'T<sub>2</sub> = {T2_SNR10}',
    hoverinfo = 'x+y+text',
    line=dict(color='#1f77b4', dash='solid'),
    visible = True
)

datapoints_SNR10 = go.Scatter(
    x = TE_datapoints,
    y = SEdata_SNR10,
    name = 'Data points with SNR = 10',
    hoverinfo = 'x+y',
    mode='markers', 
    marker=dict(color='red'), 
    visible=True
)

## SNR = 50

SNR50 = go.Scatter(
    x = TE,
    y = signal_SNR50,
    name = f'T<sub>2</sub> Fitting (T<sub>2</sub> = {T2_SNR50})',
    text = f'T<sub>2</sub> = {T2_SNR50}',
    hoverinfo = 'x+y+text',
    line=dict(color='#1f77b4'),
    visible = False
)

datapoints_SNR50 = go.Scatter(
    x = TE_datapoints,
    y = SEdata_SNR50,
    name = 'Data points with SNR = 50',
    hoverinfo = 'x+y',
    mode='markers', 
    marker=dict(color='red'),  
    visible=False
)

## SNR = 90

SNR90 = go.Scatter(
    x = TE_signals,
    y = signal_SNR90,
    name = f'T<sub>2</sub> Fitting (T<sub>2</sub> = {T2_SNR90})',
    text = f'T<sub>2</sub> = {T2_SNR90}',
    hoverinfo = 'x+y+text',
    line=dict(color='#1f77b4'),
    visible = False
)

datapoints_SNR90 = go.Scatter(
    x = TE_datapoints,
    y = SEdata_SNR90,
    name = 'Data points with SNR = 90',
    hoverinfo = 'x+y',
    mode='markers',  
    marker=dict(color='red'), 
    visible=False
)

## SNR = 130

SNR130 = go.Scatter(
    x = TE_signals,
    y = signal_SNR130,
    name = f'T<sub>2</sub> Fitting (T<sub>2</sub> = {T2_SNR130})',
    text = f'T<sub>2</sub> = {T2_SNR130}',
    hoverinfo = 'x+y+text',
    line=dict(color='#1f77b4'),
    visible = False
)

datapoints_SNR130 = go.Scatter(
    x = TE_datapoints,
    y = SEdata_SNR130,
    name = 'Data points with SNR = 130',
    hoverinfo = 'x+y',
    mode='markers',  
    marker=dict(color='red'), 
    visible=False
)

data = [SNR10, SNR50, SNR90, SNR130, datapoints_SNR10, datapoints_SNR50, datapoints_SNR90, datapoints_SNR130]

layout = go.Layout(
    width=600,
    height=470,
    margin=go.layout.Margin(
        l=100,
        r=50,
        b=130,
        t=20,
    ),
    annotations=[
        dict(
            x=0.2,
            y=0.96,
            showarrow=False,
            text='<b>True value : T<sub>2</sub> = 109 ms </b>',
            font=dict(
                family='Times New Roman',
                size=14,
                color = 'black',
            ),
            xref='paper',
            yref='paper'
        ),
        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'
        ),
        dict(
            x=0.15,
            y=-0.35,
            showarrow=False,
            text='SNR:',
            font=dict(
                family='Times New Roman',
                size=22
            ),
            xref='paper',
            yref='paper'
        ),
    ],
    xaxis=dict(
        range=[0,300],
        showgrid=False,
        linecolor='black',
        linewidth=2
    ),
    yaxis=dict(
        showgrid=False,
        linecolor='black',
        linewidth=2,
        range=[0, 1]
    ),
    legend=dict(
        x=0.55,
        y=0.97,
        traceorder='normal',
        font=dict(
            family='Times New Roman',
            size=12,
            color='#000'
        ),
        bordercolor='#000000',
        borderwidth=2
    ),
    updatemenus=[
        dict(
            buttons=list([
                # Display T2 decay curve and data points with SNR = 10
                dict(
                    args=[{'visible': [True, False, False, False, True, False, False, False]}],
                    label='10',
                    method='update'
                ),
                # Display T2 decay curve and data points with SNR = 50
                dict(
                    args=[{'visible': [False, True, False, False, False, True, False, False]}],
                    label='50',
                    method='update'
                ),
                # Display T2 decay curve and data points with SNR = 90
                dict(
                    args=[{'visible': [False, False, True, False, False, False, True, False]}],
                    label='90',
                    method='update'
                ),
                # Display T2 decay curve and data points with SNR = 130
                dict(
                    args=[{'visible': [False, False, False, True, False, False, False, True]}],
                    label='130',
                    method='update'
                ),
            ]),
            direction='up',
            pad={'r': 10, 't': 10},
            showactive=True,
            x=0.28,
            xanchor='left',
            y=-0.22,
            yanchor='top',
            font=dict(
            family='Times New Roman',
            size=12,
            color='#000'
            )
        ),
    ]
) 

fig = dict(data=data, layout=layout)

iplot(fig, filename = 'ir_fig_2.html', config = config)
Loading...