Spaces:
Runtime error

kIQT / src /streamlit_app.py
Tdanyim's picture
Update src/streamlit_app.py
b007431 verified
Raw History Blame Contribute Delete
104 kB
# # (01) EDA # from pathlib import Path # import numpy as np # import pandas as pd # import matplotlib.pyplot as plt # import streamlit as st # # --------------------------------------------------- # # Page config # # --------------------------------------------------- # st.set_page_config( # page_title="MRI Reconstruction - EDA", # layout="wide" # ) # # --------------------------------------------------- # # Intro text (always visible) # # --------------------------------------------------- # st.title("MRI Reconstruction App") # st.subheader("Interactive Exploratory Data Analysis (EDA)") # st.write( # "Use the sidebar to explore the available HF and LF sample pairs, " # "inspect their dimensions, and visualise them side by side." # ) # # --------------------------------------------------- # # Resolve project paths # # --------------------------------------------------- # ROOT_DIR = Path(__file__).resolve().parent.parent # HF_DIR = ROOT_DIR / "data" / "HF" # LF_DIR = ROOT_DIR / "data" / "LF" # # --------------------------------------------------- # # Helper functions # # --------------------------------------------------- # @st.cache_data # def get_paired_files(hf_dir: Path, lf_dir: Path) -> pd.DataFrame: # hf_files = sorted([f for f in hf_dir.glob("*.npy")]) # lf_files = sorted([f for f in lf_dir.glob("*.npy")]) # hf_map = {f.name: f for f in hf_files} # lf_map = {f.name: f for f in lf_files} # common_names = sorted(set(hf_map.keys()) & set(lf_map.keys())) # return pd.DataFrame({ # "sample_name": common_names, # "gdtFiles": [str(hf_map[name]) for name in common_names], # "imgFiles": [str(lf_map[name]) for name in common_names], # }) # @st.cache_data # def load_npy_file(file_path: str) -> np.ndarray: # return np.load(file_path) # def array_summary(arr: np.ndarray) -> dict: # return { # "shape": arr.shape, # "ndim": arr.ndim, # "dtype": str(arr.dtype), # "min": float(np.min(arr)), # "max": float(np.max(arr)), # "mean": float(np.mean(arr)), # } # def get_display_slice(arr: np.ndarray, slice_idx: int | None = None) -> np.ndarray: # if arr.ndim == 2: # return arr # if arr.ndim == 3: # return arr[slice_idx if slice_idx is not None else 0] # raise ValueError(f"Unsupported array shape for display: {arr.shape}") # def plot_side_by_side(lf_img: np.ndarray, hf_img: np.ndarray, lf_title="LF Image", hf_title="HF Image"): # fig, axes = plt.subplots(1, 2, figsize=(12, 5)) # axes[0].imshow(lf_img, cmap="gray") # axes[0].set_title(lf_title) # axes[0].axis("off") # axes[1].imshow(hf_img, cmap="gray") # axes[1].set_title(hf_title) # axes[1].axis("off") # plt.tight_layout() # return fig # # --------------------------------------------------- # # Validate folders and load paired data # # --------------------------------------------------- # if not HF_DIR.exists(): # st.error(f"HF directory not found: {HF_DIR}") # st.stop() # if not LF_DIR.exists(): # st.error(f"LF directory not found: {LF_DIR}") # st.stop() # ts_df = get_paired_files(HF_DIR, LF_DIR) # if ts_df.empty: # st.warning("No matching .npy file pairs found in data/HF and data/LF.") # st.stop() # # --------------------------------------------------- # # Sidebar controls (collapsible) # # --------------------------------------------------- # with st.sidebar.expander("EDA Controls", expanded=False): # selected_name = st.selectbox( # "Choose sample file", # ts_df["sample_name"].tolist(), # index=0 # ) # show_stats = st.checkbox("Show array statistics", value=False) # show_visualisation = st.checkbox("Display visualisation", value=False) # # Optional: keep dataframe outside expander if you still want it # show_dataframe = st.sidebar.checkbox("Show dataframe", value=False) # # --------------------------------------------------- # # Load selected sample once # # --------------------------------------------------- # selected_row = ts_df[ts_df["sample_name"] == selected_name].iloc[0] # img_path = selected_row["imgFiles"] # LF # gdt_path = selected_row["gdtFiles"] # HF # imgTs = load_npy_file(img_path) # gdtTs = load_npy_file(gdt_path) # # --------------------------------------------------- # # Build visible sections dynamically # # --------------------------------------------------- # tab_names = [] # tab_keys = [] # if show_dataframe: # tab_names.append("Dataset") # tab_keys.append("dataframe") # if show_stats: # tab_names.append("Statistics") # tab_keys.append("stats") # if show_visualisation: # tab_names.append("Visualisation") # tab_keys.append("viz") # # --------------------------------------------------- # # If nothing is checked, keep the main panel empty # # --------------------------------------------------- # if not tab_names: # st.empty() # else: # tabs = st.tabs(tab_names) # for tab, key in zip(tabs, tab_keys): # with tab: # if key == "dataframe": # st.markdown("### Available Dataset") # st.dataframe(ts_df, use_container_width=True) # elif key == "stats": # st.markdown("### Selected Sample Statistics") # col1, col2 = st.columns(2) # img_stats = array_summary(imgTs) # gdt_stats = array_summary(gdtTs) # with col1: # st.markdown("#### LF Image") # st.write(f"**File:** `{selected_name}`") # st.write(f"**Shape:** {img_stats['shape']}") # st.write(f"**Dimensions:** {img_stats['ndim']}D") # st.write(f"**Dtype:** {img_stats['dtype']}") # st.write(f"**Min:** {img_stats['min']:.6f}") # st.write(f"**Max:** {img_stats['max']:.6f}") # st.write(f"**Mean:** {img_stats['mean']:.6f}") # with col2: # st.markdown("#### HF Ground Truth") # st.write(f"**File:** `{selected_name}`") # st.write(f"**Shape:** {gdt_stats['shape']}") # st.write(f"**Dimensions:** {gdt_stats['ndim']}D") # st.write(f"**Dtype:** {gdt_stats['dtype']}") # st.write(f"**Min:** {gdt_stats['min']:.6f}") # st.write(f"**Max:** {gdt_stats['max']:.6f}") # st.write(f"**Mean:** {gdt_stats['mean']:.6f}") # elif key == "viz": # st.markdown("### Image Visualisation") # if imgTs.ndim == 2 and gdtTs.ndim == 2: # img_show = imgTs # gdt_show = gdtTs # elif imgTs.ndim == 3 and gdtTs.ndim == 3: # max_slice = min(imgTs.shape[0], gdtTs.shape[0]) - 1 # slice_idx = st.slider( # "Choose slice index", # min_value=0, # max_value=max_slice, # value=0, # key="slice_slider" # ) # img_show = get_display_slice(imgTs, slice_idx) # gdt_show = get_display_slice(gdtTs, slice_idx) # st.info(f"Displaying slice index: {slice_idx}") # else: # st.error("LF and HF arrays do not have compatible dimensions for joint display.") # st.stop() # fig = plot_side_by_side( # img_show, # gdt_show, # lf_title=f"LF: {selected_name}", # hf_title=f"HF: {selected_name}" # ) # st.pyplot(fig) # # # (02) Data Preprocessing # from pathlib import Path # import numpy as np # import pandas as pd # import matplotlib.pyplot as plt # import streamlit as st # import torch # import torch.nn.functional as F # from scipy.io import loadmat # # --------------------------------------------------- # # Page config # # --------------------------------------------------- # st.set_page_config( # page_title="MRI Reconstruction - EDA + Preprocessing", # layout="wide" # ) # # --------------------------------------------------- # # Intro text # # --------------------------------------------------- # st.title("MRI Reconstruction App") # st.subheader("Interactive Exploratory Data Analysis (EDA) + Preprocessing") # st.write( # "Use the sidebar to explore HF/LF sample pairs, inspect their properties, " # "and apply preprocessing to visualise full and undersampled k-space/image domains." # ) # # --------------------------------------------------- # # Resolve project paths # # --------------------------------------------------- # ROOT_DIR = Path(__file__).resolve().parent.parent # HF_DIR = ROOT_DIR / "data" / "HF" # LF_DIR = ROOT_DIR / "data" / "LF" # MASK_FILE = ROOT_DIR / "mask" / "prs" / "mask_30.mat" # # --------------------------------------------------- # # Helper functions for EDA # # --------------------------------------------------- # @st.cache_data # def get_paired_files(hf_dir: Path, lf_dir: Path) -> pd.DataFrame: # hf_files = sorted([f for f in hf_dir.glob("*.npy")]) # lf_files = sorted([f for f in lf_dir.glob("*.npy")]) # hf_map = {f.name: f for f in hf_files} # lf_map = {f.name: f for f in lf_files} # common_names = sorted(set(hf_map.keys()) & set(lf_map.keys())) # return pd.DataFrame({ # "sample_name": common_names, # "gdtFiles": [str(hf_map[name]) for name in common_names], # HF # "imgFiles": [str(lf_map[name]) for name in common_names], # LF # }) # @st.cache_data # def load_npy_file(file_path: str) -> np.ndarray: # return np.load(file_path) # def array_summary(arr: np.ndarray) -> dict: # return { # "shape": arr.shape, # "ndim": arr.ndim, # "dtype": str(arr.dtype), # "min": float(np.min(arr)), # "max": float(np.max(arr)), # "mean": float(np.mean(arr)), # } # def get_display_slice(arr: np.ndarray, slice_idx: int | None = None) -> np.ndarray: # if arr.ndim == 2: # return arr # if arr.ndim == 3: # return arr[slice_idx if slice_idx is not None else 0] # raise ValueError(f"Unsupported array shape for display: {arr.shape}") # def plot_side_by_side(lf_img: np.ndarray, hf_img: np.ndarray, lf_title="LF Image", hf_title="HF Image"): # fig, axes = plt.subplots(1, 2, figsize=(12, 5)) # axes[0].imshow(lf_img, cmap="gray") # axes[0].set_title(lf_title) # axes[0].axis("off") # axes[1].imshow(hf_img, cmap="gray") # axes[1].set_title(hf_title) # axes[1].axis("off") # plt.tight_layout() # return fig # # --------------------------------------------------- # # Preprocessing functions # # --------------------------------------------------- # def resizeImage( # img_np: np.ndarray, # target_size=(256, 256), # mode="bicubic", # antialias=True, # device="cpu" # ): # """ # Resize a 2D NumPy image to the target size using torch interpolation. # """ # # Early return if already correct size # if img_np.shape[-2:] == target_size: # return img_np.astype(np.float32) # # Convert NumPy -> Torch tensor # tensor = torch.from_numpy(img_np.astype(np.float32)).to(device) # # Add batch and channel dimensions: (H, W) -> (1, 1, H, W) # tensor = tensor.unsqueeze(0).unsqueeze(0) # # Resize # tensor = F.interpolate( # tensor, # size=target_size, # mode=mode, # align_corners=False if mode in ["bilinear", "bicubic"] else None, # antialias=antialias # ) # # Remove batch and channel dimensions: (1, 1, H, W) -> (H, W) # tensor = tensor.squeeze(0).squeeze(0) # return tensor.cpu().numpy() # def fft2c(image): # """ # Convert image -> centered 2D k-space. # """ # return np.fft.fftshift( # np.fft.fft2(np.fft.ifftshift(image, axes=(-2, -1))), # axes=(-2, -1) # ) # def ifft2c(kspace): # """ # Convert centered 2D k-space -> image magnitude. # """ # return np.abs( # np.fft.ifftshift( # np.fft.ifft2(np.fft.fftshift(kspace, axes=(-2, -1))), # axes=(-2, -1) # ) # ) # @st.cache_data # def load_mask(mask_file: str) -> np.ndarray: # """ # Load the undersampling mask once and cache it. # """ # mask_data = loadmat(mask_file) # mask_matrix = mask_data["mask_matrix"] # mask_matrix = np.fft.ifftshift(mask_matrix).astype(np.float32) # return mask_matrix # def und2DMask(slice_kspace, maskFile): # """ # Apply undersampling mask to one 2D k-space slice. # """ # undersamplingMask = load_mask(str(maskFile)) # udkspace = undersamplingMask * slice_kspace # return udkspace, undersamplingMask # def ch2ksp(c): # """ # Convert 2-channel representation to complex k-space. # Not yet used in preprocessing visualisation, but kept for later stages. # """ # return c[0, :, :] + 1j * c[1, :, :] # def preprocess_single_pair(hr_array: np.ndarray, lr_array: np.ndarray, mask_file: Path, target_size=(256, 256)): # """ # Preprocess one selected HF/LF pair. # Handles: # - 2D arrays: process single image # - 3D arrays: process slice-by-slice # Returns a dictionary of processed lists ready for visualisation. # """ # HR_images = [] # full_HR_kspace = [] # ud_HR_kspace = [] # mag_HR_images = [] # LR_images = [] # full_LR_kspace = [] # ud_LR_kspace = [] # mag_LR_images = [] # # If 2D, wrap into a list so we can reuse the same processing loop # if hr_array.ndim == 2 and lr_array.ndim == 2: # hr_slices = [hr_array] # lr_slices = [lr_array] # # If 3D, process slice-by-slice # elif hr_array.ndim == 3 and lr_array.ndim == 3: # num_slices = min(hr_array.shape[0], lr_array.shape[0]) # hr_slices = [hr_array[i] for i in range(num_slices)] # lr_slices = [lr_array[i] for i in range(num_slices)] # else: # raise ValueError("HF and LF arrays must both be 2D or both be 3D with matching slice structure.") # # Process each slice # for HRimage, LRimage in zip(hr_slices, lr_slices): # # Resize both HF and LF images # HRimage = resizeImage(HRimage, target_size=target_size) # LRimage = resizeImage(LRimage, target_size=target_size) # # Full k-space # full_HRkspace = fft2c(HRimage) # full_LRkspace = fft2c(LRimage) # # Undersampled k-space # ud_HRkspace, _ = und2DMask(full_HRkspace, mask_file) # ud_LRkspace, _ = und2DMask(full_LRkspace, mask_file) # # Reconstructed image magnitude from undersampled k-space # recon_HRimage = ifft2c(ud_HRkspace) # recon_LRimage = ifft2c(ud_LRkspace) # mag_HRimage = np.abs(recon_HRimage) # mag_LRimage = np.abs(recon_LRimage) # # Store outputs # HR_images.append(HRimage) # full_HR_kspace.append(full_HRkspace) # ud_HR_kspace.append(ud_HRkspace) # mag_HR_images.append(mag_HRimage) # LR_images.append(LRimage) # full_LR_kspace.append(full_LRkspace) # ud_LR_kspace.append(ud_LRkspace) # mag_LR_images.append(mag_LRimage) # return { # "HR_images": HR_images, # "full_HR_kspace": full_HR_kspace, # "ud_HR_kspace": ud_HR_kspace, # "mag_HR_images": mag_HR_images, # "LR_images": LR_images, # "full_LR_kspace": full_LR_kspace, # "ud_LR_kspace": ud_LR_kspace, # "mag_LR_images": mag_LR_images, # "num_samples": len(HR_images), # "target_size": target_size, # } # def plot_preprocessing_hr(sample_idx: int, processed: dict): # """ # Plot full and undersampled k-space/image for HR sample. # """ # sample_fsHRkspace = processed["full_HR_kspace"][sample_idx] # sample_udHRkspace = processed["ud_HR_kspace"][sample_idx] # sample_fsHRimg = processed["HR_images"][sample_idx] # sample_udHRimg = processed["mag_HR_images"][sample_idx] # fig, axes = plt.subplots(1, 4, figsize=(16, 4)) # axes[0].imshow(np.log(np.abs(sample_fsHRkspace) + 1e-9), cmap="gray") # axes[0].set_title("fsHR k-space") # axes[0].axis("off") # axes[1].imshow(sample_fsHRimg, cmap="gray") # axes[1].set_title("fsHR Image") # axes[1].axis("off") # axes[2].imshow(np.log(np.abs(sample_udHRkspace) + 1e-9), cmap="gray") # axes[2].set_title("udHR k-space") # axes[2].axis("off") # axes[3].imshow(sample_udHRimg, cmap="gray") # axes[3].set_title("udHR Image") # axes[3].axis("off") # plt.tight_layout() # return fig # def plot_preprocessing_lr(sample_idx: int, processed: dict): # """ # Plot full and undersampled k-space/image for LR sample. # """ # sample_fsLRkspace = processed["full_LR_kspace"][sample_idx] # sample_udLRkspace = processed["ud_LR_kspace"][sample_idx] # sample_fsLRimg = processed["LR_images"][sample_idx] # sample_udLRimg = processed["mag_LR_images"][sample_idx] # fig, axes = plt.subplots(1, 4, figsize=(16, 4)) # axes[0].imshow(np.log(np.abs(sample_fsLRkspace) + 1e-9), cmap="gray") # axes[0].set_title("fsLR k-space") # axes[0].axis("off") # axes[1].imshow(sample_fsLRimg, cmap="gray") # axes[1].set_title("fsLR Image") # axes[1].axis("off") # axes[2].imshow(np.log(np.abs(sample_udLRkspace) + 1e-9), cmap="gray") # axes[2].set_title("udLR k-space") # axes[2].axis("off") # axes[3].imshow(sample_udLRimg, cmap="gray") # axes[3].set_title("udLR Image") # axes[3].axis("off") # plt.tight_layout() # return fig # # --------------------------------------------------- # # Validate folders # # --------------------------------------------------- # if not HF_DIR.exists(): # st.error(f"HF directory not found: {HF_DIR}") # st.stop() # if not LF_DIR.exists(): # st.error(f"LF directory not found: {LF_DIR}") # st.stop() # if not MASK_FILE.exists(): # st.error(f"Mask file not found: {MASK_FILE}") # st.stop() # # --------------------------------------------------- # # Load paired dataset # # --------------------------------------------------- # ts_df = get_paired_files(HF_DIR, LF_DIR) # if ts_df.empty: # st.warning("No matching .npy file pairs found in data/HF and data/LF.") # st.stop() # # --------------------------------------------------- # # Sidebar controls - EDA # # --------------------------------------------------- # with st.sidebar.expander("EDA Controls", expanded=False): # selected_name = st.selectbox( # "Choose sample file", # ts_df["sample_name"].tolist(), # index=0 # ) # show_stats = st.checkbox("Show array statistics", value=False) # show_visualisation = st.checkbox("Display EDA visualisation", value=False) # show_dataframe = st.sidebar.checkbox("Show dataframe", value=False) # # --------------------------------------------------- # # Sidebar controls - Preprocessing # # --------------------------------------------------- # with st.sidebar.expander("Preprocessing Controls", expanded=False): # st.markdown("Apply preprocessing to the currently selected HF/LF pair.") # target_height = st.number_input("Target height", min_value=32, max_value=1024, value=256, step=32) # target_width = st.number_input("Target width", min_value=32, max_value=1024, value=256, step=32) # apply_preprocessing = st.button("Apply preprocessing") # show_preprocessing_viz = st.checkbox("Display preprocessing visualisation", value=False) # # --------------------------------------------------- # # Load selected sample from EDA # # --------------------------------------------------- # selected_row = ts_df[ts_df["sample_name"] == selected_name].iloc[0] # img_path = selected_row["imgFiles"] # LF # gdt_path = selected_row["gdtFiles"] # HF # imgTs = load_npy_file(img_path) # gdtTs = load_npy_file(gdt_path) # # --------------------------------------------------- # # Initialise session state keys # # --------------------------------------------------- # if "preprocessed_data" not in st.session_state: # st.session_state["preprocessed_data"] = None # if "preprocessed_sample_name" not in st.session_state: # st.session_state["preprocessed_sample_name"] = None # # --------------------------------------------------- # # Run preprocessing only when the button is clicked # # --------------------------------------------------- # if apply_preprocessing: # try: # with st.spinner("Applying preprocessing..."): # processed = preprocess_single_pair( # hr_array=gdtTs, # HF # lr_array=imgTs, # LF # mask_file=MASK_FILE, # target_size=(int(target_height), int(target_width)) # ) # st.session_state["preprocessed_data"] = processed # st.session_state["preprocessed_sample_name"] = selected_name # st.success(f"Preprocessing completed for sample: {selected_name}") # except Exception as e: # st.error(f"Preprocessing failed: {e}") # # --------------------------------------------------- # # Build visible sections dynamically # # --------------------------------------------------- # tab_names = [] # tab_keys = [] # if show_dataframe: # tab_names.append("Dataset") # tab_keys.append("dataframe") # if show_stats: # tab_names.append("Statistics") # tab_keys.append("stats") # if show_visualisation: # tab_names.append("EDA Visualisation") # tab_keys.append("eda_viz") # if show_preprocessing_viz: # tab_names.append("Preprocessing Visualisation") # tab_keys.append("prep_viz") # # --------------------------------------------------- # # If nothing is checked, keep the main panel empty # # --------------------------------------------------- # if not tab_names: # st.empty() # else: # tabs = st.tabs(tab_names) # for tab, key in zip(tabs, tab_keys): # with tab: # # --------------------------------------- # # Dataset tab # # --------------------------------------- # if key == "dataframe": # st.markdown("### Available Dataset") # st.dataframe(ts_df, use_container_width=True) # # --------------------------------------- # # Statistics tab # # --------------------------------------- # elif key == "stats": # st.markdown("### Selected Sample Statistics") # col1, col2 = st.columns(2) # img_stats = array_summary(imgTs) # gdt_stats = array_summary(gdtTs) # with col1: # st.markdown("#### LF Image") # st.write(f"**File:** `{selected_name}`") # st.write(f"**Shape:** {img_stats['shape']}") # st.write(f"**Dimensions:** {img_stats['ndim']}D") # st.write(f"**Dtype:** {img_stats['dtype']}") # st.write(f"**Min:** {img_stats['min']:.6f}") # st.write(f"**Max:** {img_stats['max']:.6f}") # st.write(f"**Mean:** {img_stats['mean']:.6f}") # with col2: # st.markdown("#### HF Ground Truth") # st.write(f"**File:** `{selected_name}`") # st.write(f"**Shape:** {gdt_stats['shape']}") # st.write(f"**Dimensions:** {gdt_stats['ndim']}D") # st.write(f"**Dtype:** {gdt_stats['dtype']}") # st.write(f"**Min:** {gdt_stats['min']:.6f}") # st.write(f"**Max:** {gdt_stats['max']:.6f}") # st.write(f"**Mean:** {gdt_stats['mean']:.6f}") # # --------------------------------------- # # EDA Visualisation tab # # --------------------------------------- # elif key == "eda_viz": # st.markdown("### EDA Image Visualisation") # if imgTs.ndim == 2 and gdtTs.ndim == 2: # img_show = imgTs # gdt_show = gdtTs # elif imgTs.ndim == 3 and gdtTs.ndim == 3: # max_slice = min(imgTs.shape[0], gdtTs.shape[0]) - 1 # slice_idx = st.slider( # "Choose slice index", # min_value=0, # max_value=max_slice, # value=0, # key="eda_slice_slider" # ) # img_show = get_display_slice(imgTs, slice_idx) # gdt_show = get_display_slice(gdtTs, slice_idx) # st.info(f"Displaying EDA slice index: {slice_idx}") # else: # st.error("LF and HF arrays do not have compatible dimensions for joint display.") # st.stop() # fig = plot_side_by_side( # img_show, # gdt_show, # lf_title=f"LF: {selected_name}", # hf_title=f"HF: {selected_name}" # ) # st.pyplot(fig) # # --------------------------------------- # # Preprocessing Visualisation tab # # --------------------------------------- # elif key == "prep_viz": # st.markdown("### Preprocessing Visualisation") # processed = st.session_state.get("preprocessed_data") # processed_sample_name = st.session_state.get("preprocessed_sample_name") # # Guard: user requested preprocessing visualisation but has not run preprocessing yet # if processed is None: # st.warning("Please click 'Apply preprocessing' in the sidebar first.") # st.stop() # # Guard: selected sample changed after preprocessing # if processed_sample_name != selected_name: # st.warning( # "The currently displayed preprocessing result belongs to a different selected file. " # "Please click 'Apply preprocessing' again for the newly selected sample." # ) # st.stop() # num_samples = processed["num_samples"] # # For 2D data there is only one processed sample # if num_samples == 1: # sample_idx = 0 # st.info("This sample is 2D, so only one processed image is available.") # # For 3D data let the user choose the slice/sample index # else: # sample_idx = st.slider( # "Choose preprocessing sample index", # min_value=0, # max_value=num_samples - 1, # value=0, # key="prep_sample_slider" # ) # st.info(f"Displaying preprocessing sample index: {sample_idx}") # # Show dimensions of current processed outputs # sample_udHRkspace = processed["ud_HR_kspace"][sample_idx] # sample_fsHRkspace = processed["full_HR_kspace"][sample_idx] # sample_udLRkspace = processed["ud_LR_kspace"][sample_idx] # sample_fsLRkspace = processed["full_LR_kspace"][sample_idx] # sample_udHRimg = processed["mag_HR_images"][sample_idx] # sample_fsHRimg = processed["HR_images"][sample_idx] # sample_udLRimg = processed["mag_LR_images"][sample_idx] # sample_fsLRimg = processed["LR_images"][sample_idx] # st.markdown("#### Processed Sample Shapes") # col1, col2 = st.columns(2) # # with col1: # # st.write(f"**udHRkspace:** {sample_udHRkspace.shape}") # # st.write(f"**fsHRkspace:** {sample_fsHRkspace.shape}") # # st.write(f"**udHRimg:** {sample_udHRimg.shape}") # # st.write(f"**fsHRimg:** {sample_fsHRimg.shape}") # # with col2: # # st.write(f"**udLRkspace:** {sample_udLRkspace.shape}") # # st.write(f"**fsLRkspace:** {sample_fsLRkspace.shape}") # # st.write(f"**udLRimg:** {sample_udLRimg.shape}") # # st.write(f"**fsLRimg:** {sample_fsLRimg.shape}") # # Plot HR row # st.markdown("#### HR Domain Visualisation") # fig_hr = plot_preprocessing_hr(sample_idx, processed) # st.pyplot(fig_hr) # # Plot LR row # st.markdown("#### LR Domain Visualisation") # fig_lr = plot_preprocessing_lr(sample_idx, processed) # st.pyplot(fig_lr) # # # # (03) Model Prediction # from pathlib import Path # import numpy as np # import pandas as pd # import matplotlib.pyplot as plt # import streamlit as st # import torch # import torch.nn as nn # import torch.nn.functional as F # from scipy.io import loadmat # from skimage.metrics import structural_similarity as ssim # from skimage.metrics import peak_signal_noise_ratio as psnr # # --------------------------------------------------- # # Page config # # --------------------------------------------------- # st.set_page_config( # page_title="MRI Reconstruction - EDA + Preprocessing + Prediction", # layout="wide" # ) # # --------------------------------------------------- # # Intro text # # --------------------------------------------------- # st.title("MRI Reconstruction App") # st.subheader("Interactive Exploratory Data Analysis (EDA) + Preprocessing + Prediction") # st.write( # "Use the sidebar to explore HF/LF sample pairs, inspect their properties, " # "apply preprocessing, and run model prediction with visualisation and metrics." # ) # # --------------------------------------------------- # # Resolve project paths # # --------------------------------------------------- # ROOT_DIR = Path(__file__).resolve().parent.parent # HF_DIR = ROOT_DIR / "data" / "HF" # LF_DIR = ROOT_DIR / "data" / "LF" # MASK_FILE = ROOT_DIR / "mask" / "prs" / "mask_30.mat" # WEIGHT_FILE = ROOT_DIR / "weight" / "udksp30Unet_weight.pth" # # --------------------------------------------------- # # Device setup # # --------------------------------------------------- # device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # # --------------------------------------------------- # # Helper functions for EDA # # --------------------------------------------------- # @st.cache_data # def get_paired_files(hf_dir: Path, lf_dir: Path) -> pd.DataFrame: # hf_files = sorted([f for f in hf_dir.glob("*.npy")]) # lf_files = sorted([f for f in lf_dir.glob("*.npy")]) # hf_map = {f.name: f for f in hf_files} # lf_map = {f.name: f for f in lf_files} # common_names = sorted(set(hf_map.keys()) & set(lf_map.keys())) # return pd.DataFrame({ # "sample_name": common_names, # "gdtFiles": [str(hf_map[name]) for name in common_names], # HF # "imgFiles": [str(lf_map[name]) for name in common_names], # LF # }) # @st.cache_data # def load_npy_file(file_path: str) -> np.ndarray: # return np.load(file_path) # def array_summary(arr: np.ndarray) -> dict: # return { # "shape": arr.shape, # "ndim": arr.ndim, # "dtype": str(arr.dtype), # "min": float(np.min(arr)), # "max": float(np.max(arr)), # "mean": float(np.mean(arr)), # } # def get_display_slice(arr: np.ndarray, slice_idx: int | None = None) -> np.ndarray: # if arr.ndim == 2: # return arr # if arr.ndim == 3: # return arr[slice_idx if slice_idx is not None else 0] # raise ValueError(f"Unsupported array shape for display: {arr.shape}") # def plot_side_by_side(lf_img: np.ndarray, hf_img: np.ndarray, lf_title="LF Image", hf_title="HF Image"): # fig, axes = plt.subplots(1, 2, figsize=(12, 5)) # axes[0].imshow(lf_img, cmap="gray") # axes[0].set_title(lf_title) # axes[0].axis("off") # axes[1].imshow(hf_img, cmap="gray") # axes[1].set_title(hf_title) # axes[1].axis("off") # plt.tight_layout() # return fig # # --------------------------------------------------- # # Preprocessing functions # # --------------------------------------------------- # def resizeImage( # img_np: np.ndarray, # target_size=(256, 256), # mode="bicubic", # antialias=True, # device="cpu" # ): # """ # Resize a 2D NumPy image to the target size using torch interpolation. # """ # if img_np.shape[-2:] == target_size: # return img_np.astype(np.float32) # tensor = torch.from_numpy(img_np.astype(np.float32)).to(device) # tensor = tensor.unsqueeze(0).unsqueeze(0) # tensor = F.interpolate( # tensor, # size=target_size, # mode=mode, # align_corners=False if mode in ["bilinear", "bicubic"] else None, # antialias=antialias # ) # tensor = tensor.squeeze(0).squeeze(0) # return tensor.cpu().numpy() # def fft2c(image): # """ # Convert image -> centered 2D k-space. # """ # return np.fft.fftshift( # np.fft.fft2(np.fft.ifftshift(image, axes=(-2, -1))), # axes=(-2, -1) # ) # def ifft2c(kspace): # """ # Convert centered 2D k-space -> image magnitude. # """ # return np.abs( # np.fft.ifftshift( # np.fft.ifft2(np.fft.fftshift(kspace, axes=(-2, -1))), # axes=(-2, -1) # ) # ) # @st.cache_data # def load_mask(mask_file: str) -> np.ndarray: # """ # Load the undersampling mask once and cache it. # """ # mask_data = loadmat(mask_file) # mask_matrix = mask_data["mask_matrix"] # mask_matrix = np.fft.ifftshift(mask_matrix).astype(np.float32) # return mask_matrix # def und2DMask(slice_kspace, maskFile): # """ # Apply undersampling mask to one 2D k-space slice. # """ # undersamplingMask = load_mask(str(maskFile)) # udkspace = undersamplingMask * slice_kspace # return udkspace, undersamplingMask # def ch2ksp(c): # """ # Convert 2-channel representation to complex k-space. # """ # return c[0, :, :] + 1j * c[1, :, :] # def preprocess_single_pair(hr_array: np.ndarray, lr_array: np.ndarray, mask_file: Path, target_size=(256, 256)): # """ # Preprocess one selected HF/LF pair. # Handles: # - 2D arrays: process single image # - 3D arrays: process slice-by-slice # """ # HR_images = [] # full_HR_kspace = [] # ud_HR_kspace = [] # mag_HR_images = [] # LR_images = [] # full_LR_kspace = [] # ud_LR_kspace = [] # mag_LR_images = [] # if hr_array.ndim == 2 and lr_array.ndim == 2: # hr_slices = [hr_array] # lr_slices = [lr_array] # elif hr_array.ndim == 3 and lr_array.ndim == 3: # num_slices = min(hr_array.shape[0], lr_array.shape[0]) # hr_slices = [hr_array[i] for i in range(num_slices)] # lr_slices = [lr_array[i] for i in range(num_slices)] # else: # raise ValueError("HF and LF arrays must both be 2D or both be 3D with matching slice structure.") # for HRimage, LRimage in zip(hr_slices, lr_slices): # HRimage = resizeImage(HRimage, target_size=target_size) # LRimage = resizeImage(LRimage, target_size=target_size) # full_HRkspace = fft2c(HRimage) # full_LRkspace = fft2c(LRimage) # ud_HRkspace, _ = und2DMask(full_HRkspace, mask_file) # ud_LRkspace, _ = und2DMask(full_LRkspace, mask_file) # recon_HRimage = ifft2c(ud_HRkspace) # recon_LRimage = ifft2c(ud_LRkspace) # mag_HRimage = np.abs(recon_HRimage) # mag_LRimage = np.abs(recon_LRimage) # HR_images.append(HRimage) # full_HR_kspace.append(full_HRkspace) # ud_HR_kspace.append(ud_HRkspace) # mag_HR_images.append(mag_HRimage) # LR_images.append(LRimage) # full_LR_kspace.append(full_LRkspace) # ud_LR_kspace.append(ud_LRkspace) # mag_LR_images.append(mag_LRimage) # return { # "HR_images": HR_images, # "full_HR_kspace": full_HR_kspace, # "ud_HR_kspace": ud_HR_kspace, # "mag_HR_images": mag_HR_images, # "LR_images": LR_images, # "full_LR_kspace": full_LR_kspace, # "ud_LR_kspace": ud_LR_kspace, # "mag_LR_images": mag_LR_images, # "num_samples": len(HR_images), # "target_size": target_size, # } # def plot_preprocessing_hr(sample_idx: int, processed: dict): # sample_fsHRkspace = processed["full_HR_kspace"][sample_idx] # sample_udHRkspace = processed["ud_HR_kspace"][sample_idx] # sample_fsHRimg = processed["HR_images"][sample_idx] # sample_udHRimg = processed["mag_HR_images"][sample_idx] # fig, axes = plt.subplots(1, 4, figsize=(16, 4)) # axes[0].imshow(np.log(np.abs(sample_fsHRkspace) + 1e-9), cmap="gray") # axes[0].set_title("fsHR k-space") # axes[0].axis("off") # axes[1].imshow(sample_fsHRimg, cmap="gray") # axes[1].set_title("fsHR Image") # axes[1].axis("off") # axes[2].imshow(np.log(np.abs(sample_udHRkspace) + 1e-9), cmap="gray") # axes[2].set_title("udHR k-space") # axes[2].axis("off") # axes[3].imshow(sample_udHRimg, cmap="gray") # axes[3].set_title("udHR Image") # axes[3].axis("off") # plt.tight_layout() # return fig # def plot_preprocessing_lr(sample_idx: int, processed: dict): # sample_fsLRkspace = processed["full_LR_kspace"][sample_idx] # sample_udLRkspace = processed["ud_LR_kspace"][sample_idx] # sample_fsLRimg = processed["LR_images"][sample_idx] # sample_udLRimg = processed["mag_LR_images"][sample_idx] # fig, axes = plt.subplots(1, 4, figsize=(16, 4)) # axes[0].imshow(np.log(np.abs(sample_fsLRkspace) + 1e-9), cmap="gray") # axes[0].set_title("fsLR k-space") # axes[0].axis("off") # axes[1].imshow(sample_fsLRimg, cmap="gray") # axes[1].set_title("fsLR Image") # axes[1].axis("off") # axes[2].imshow(np.log(np.abs(sample_udLRkspace) + 1e-9), cmap="gray") # axes[2].set_title("udLR k-space") # axes[2].axis("off") # axes[3].imshow(sample_udLRimg, cmap="gray") # axes[3].set_title("udLR Image") # axes[3].axis("off") # plt.tight_layout() # return fig # # --------------------------------------------------- # # Model setup # # --------------------------------------------------- # class UNetBlock(nn.Module): # """ # Basic convolutional block in the U-Net with two convolutions + ReLU # """ # def __init__(self, in_channels, out_channels, kernel_size=3, padding=1): # super(UNetBlock, self).__init__() # self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size, padding=padding) # self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size, padding=padding) # self.relu = nn.ReLU(inplace=True) # def forward(self, x): # x = self.relu(self.conv1(x)) # x = self.relu(self.conv2(x)) # return x # class KSpaceUNet(nn.Module): # """ # Modified U-Net with 3 encoder-decoder layers for k-space/image reconstruction # """ # def __init__(self, input_channels=2, output_channels=2, num_filters=64): # super(KSpaceUNet, self).__init__() # self.enc1 = UNetBlock(input_channels, num_filters) # self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2) # self.enc2 = UNetBlock(num_filters, num_filters * 2) # self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2) # self.enc3 = UNetBlock(num_filters * 2, num_filters * 4) # self.pool3 = nn.MaxPool2d(kernel_size=2, stride=2) # self.bottleneck = UNetBlock(num_filters * 4, num_filters * 8) # self.up3 = nn.ConvTranspose2d(num_filters * 8, num_filters * 4, kernel_size=2, stride=2) # self.dec3 = UNetBlock(num_filters * 8, num_filters * 4) # self.up2 = nn.ConvTranspose2d(num_filters * 4, num_filters * 2, kernel_size=2, stride=2) # self.dec2 = UNetBlock(num_filters * 4, num_filters * 2) # self.up1 = nn.ConvTranspose2d(num_filters * 2, num_filters, kernel_size=2, stride=2) # self.dec1 = UNetBlock(num_filters * 2, num_filters) # self.final_conv = nn.Conv2d(num_filters, output_channels, kernel_size=1) # def forward(self, x): # e1 = self.enc1(x) # p1 = self.pool1(e1) # e2 = self.enc2(p1) # p2 = self.pool2(e2) # e3 = self.enc3(p2) # p3 = self.pool3(e3) # b = self.bottleneck(p3) # u3 = self.up3(b) # d3 = self.dec3(torch.cat([u3, e3], dim=1)) # u2 = self.up2(d3) # d2 = self.dec2(torch.cat([u2, e2], dim=1)) # u1 = self.up1(d2) # d1 = self.dec1(torch.cat([u1, e1], dim=1)) # return self.final_conv(d1) # @st.cache_resource # def load_model(weight_file: str, model_device: str = "cpu"): # """ # Load the PyTorch model once and cache it for reuse. # """ # model = KSpaceUNet().to(model_device) # checkpoint = torch.load(weight_file, map_location=model_device) # model.load_state_dict(checkpoint) # model.eval() # return model # def safe_data_range(arr: np.ndarray) -> float: # """ # Avoid zero data_range issues in SSIM/PSNR calculations. # """ # dr = float(np.ptp(np.abs(arr))) # return dr if dr > 0 else 1e-9 # def predict_single_processed_sample(model, processed: dict, sample_idx: int, batch_size: int = 2, model_device: str = "cpu"): # """ # Run model prediction on one processed sample index. # Uses the same logic/style as your notebook code as closely as possible. # """ # # --------------------------------------------------- # # Pull the already preprocessed arrays for the selected sample index # # --------------------------------------------------- # ud_Imgkspace = processed["ud_LR_kspace"][sample_idx] # full_Gdtkspace = processed["full_HR_kspace"][sample_idx] # # --------------------------------------------------- # # Convert k-space data to NumPy arrays # # --------------------------------------------------- # udLRkspace_Ts = np.array(ud_Imgkspace) # fsHRkspace_Ts = np.array(full_Gdtkspace) # # --------------------------------------------------- # # Reshape to (N, H, W) # # For a single selected sample, N becomes 1 # # --------------------------------------------------- # target_h, target_w = processed["target_size"] # udLRkspace_Ts = udLRkspace_Ts.reshape(-1, target_h, target_w) # fsHRkspace_Ts = fsHRkspace_Ts.reshape(-1, target_h, target_w) # # --------------------------------------------------- # # Split into real and imaginary components # # Kept consistent with your provided notebook logic # # --------------------------------------------------- # X_tstCpx = udLRkspace_Ts[:, :, :] + 1j * udLRkspace_Ts[:, :, :] # y_tstCpx = fsHRkspace_Ts[:, :, :] + 1j * fsHRkspace_Ts[:, :, :] # # --------------------------------------------------- # # Apply IFFT and store real/imaginary parts separately # # Note: your ifft2c returns magnitude, so imag will typically be zero. # # This block is intentionally kept close to your original logic. # # --------------------------------------------------- # X_tst1_real = np.array([np.real(ifft2c(slice_)) for slice_ in X_tstCpx]) # X_tst1_imag = np.array([np.imag(ifft2c(slice_)) for slice_ in X_tstCpx]) # y_tst1_real = np.array([np.real(ifft2c(slice_)) for slice_ in y_tstCpx]) # y_tst1_imag = np.array([np.imag(ifft2c(slice_)) for slice_ in y_tstCpx]) # # --------------------------------------------------- # # Stack real and imaginary parts as separate channels # # Shape becomes (N, 2, H, W) # # --------------------------------------------------- # X_tst1 = np.stack([X_tst1_real, X_tst1_imag], axis=1) # y_tst1 = np.stack([y_tst1_real, y_tst1_imag], axis=1) # # --------------------------------------------------- # # Convert to torch tensors # # --------------------------------------------------- # X_test = torch.tensor(X_tst1, dtype=torch.float32).to(model_device) # y_test = torch.tensor(y_tst1, dtype=torch.float32).to(model_device) # # --------------------------------------------------- # # Mini-batch inference # # --------------------------------------------------- # y_pred_batches = [] # for batch_start in range(0, X_test.shape[0], batch_size): # batch_end = min(batch_start + batch_size, X_test.shape[0]) # X_test_batch = X_test[batch_start:batch_end] # with torch.no_grad(): # y_pred_tensor_batch = model(X_test_batch) # y_pred_batches.append(y_pred_tensor_batch.cpu().numpy()) # predKsp = np.concatenate(y_pred_batches, axis=0).squeeze() # pred_kspace = np.sqrt(predKsp[0, :, :]**2 + predKsp[1, :, :]**2) # # --------------------------------------------------- # # Convert tensors to NumPy for metric computation # # --------------------------------------------------- # y_test_np = y_test.squeeze().cpu().numpy() # y_test_np = np.sqrt(y_test_np[0, :, :]**2 + y_test_np[1, :, :]**2) # X_test_np = X_test.squeeze().cpu().numpy() # X_test_np = np.sqrt(X_test_np[0, :, :]**2 + X_test_np[1, :, :]**2) # # --------------------------------------------------- # # Build images for plotting # # --------------------------------------------------- # M_Imgimg = ud_Imgkspace # M_Tgtimg = full_Gdtkspace # M_Prdimg = fft2c(pred_kspace) # # --------------------------------------------------- # # Metrics # # --------------------------------------------------- # ssimLR = ssim(np.abs(y_test_np), np.abs(X_test_np), data_range=safe_data_range(X_test_np)) # psnrLR = psnr(np.abs(y_test_np), np.abs(X_test_np), data_range=safe_data_range(X_test_np)) # ssimRec = ssim(np.abs(y_test_np), np.abs(pred_kspace), data_range=safe_data_range(pred_kspace)) # psnrRec = psnr(np.abs(y_test_np), np.abs(pred_kspace), data_range=safe_data_range(pred_kspace)) # return { # "M_Imgimg": M_Imgimg, # undersampled LR k-space # "M_Tgtimg": M_Tgtimg, # full HR k-space # "M_Prdimg": M_Prdimg, # predicted k-space # "X_test": X_test_np, # undersampled LR image # "y_test": y_test_np, # full HR image # "pred_kspace": pred_kspace, # predicted image # "ssimLR": float(ssimLR), # "psnrLR": float(psnrLR), # "ssimRec": float(ssimRec), # "psnrRec": float(psnrRec), # "sample_idx": sample_idx, # } # def plot_prediction_results(pred_result: dict): # """ # Plot prediction outputs in the same 2x4 style as your notebook. # """ # fig = plt.figure(figsize=(20, 8)) # # Top row: k-space # plt.subplot(2, 4, 1) # plt.imshow(np.log(np.abs(pred_result["M_Imgimg"]) + 1e-9), cmap="gray") # plt.title("udLR k-space") # plt.axis("off") # plt.subplot(2, 4, 2) # plt.imshow(np.log(np.abs(pred_result["M_Tgtimg"]) + 1e-9), cmap="gray") # plt.title("fsHR k-space") # plt.axis("off") # plt.subplot(2, 4, 3) # plt.imshow(np.log(np.abs(pred_result["M_Prdimg"]) + 1e-9), cmap="gray") # plt.title("IQT k-space") # plt.axis("off") # # Bottom row: image domain # plt.subplot(2, 4, 5) # plt.imshow(np.abs(pred_result["X_test"]), cmap="gray") # plt.title( # f"udLR Img\nSSIM: {pred_result['ssimLR']:.4f}, PSNR: {pred_result['psnrLR']:.2f} dB" # ) # plt.axis("off") # plt.subplot(2, 4, 6) # plt.imshow(np.abs(pred_result["y_test"]), cmap="gray") # plt.title("fsHR Img") # plt.axis("off") # plt.subplot(2, 4, 7) # plt.imshow(np.abs(pred_result["pred_kspace"]), cmap="gray") # plt.title( # f"IQT Img\nSSIM: {pred_result['ssimRec']:.4f}, PSNR: {pred_result['psnrRec']:.2f} dB" # ) # plt.axis("off") # plt.tight_layout() # return fig # # --------------------------------------------------- # # Validate folders/files # # --------------------------------------------------- # if not HF_DIR.exists(): # st.error(f"HF directory not found: {HF_DIR}") # st.stop() # if not LF_DIR.exists(): # st.error(f"LF directory not found: {LF_DIR}") # st.stop() # if not MASK_FILE.exists(): # st.error(f"Mask file not found: {MASK_FILE}") # st.stop() # if not WEIGHT_FILE.exists(): # st.error(f"Weight file not found: {WEIGHT_FILE}") # st.stop() # # --------------------------------------------------- # # Load paired dataset # # --------------------------------------------------- # ts_df = get_paired_files(HF_DIR, LF_DIR) # if ts_df.empty: # st.warning("No matching .npy file pairs found in data/HF and data/LF.") # st.stop() # # --------------------------------------------------- # # Sidebar controls - EDA # # --------------------------------------------------- # with st.sidebar.expander("EDA Controls", expanded=False): # selected_name = st.selectbox( # "Choose sample file", # ts_df["sample_name"].tolist(), # index=0 # ) # show_stats = st.checkbox("Show array statistics", value=False) # show_visualisation = st.checkbox("Display EDA visualisation", value=False) # show_dataframe = st.sidebar.checkbox("Show dataframe", value=False) # # --------------------------------------------------- # # Sidebar controls - Preprocessing # # --------------------------------------------------- # with st.sidebar.expander("Preprocessing Controls", expanded=False): # st.markdown("Apply preprocessing to the currently selected HF/LF pair.") # target_height = st.number_input("Target height", min_value=32, max_value=1024, value=256, step=32) # target_width = st.number_input("Target width", min_value=32, max_value=1024, value=256, step=32) # apply_preprocessing = st.button("Apply preprocessing") # show_preprocessing_viz = st.checkbox("Display preprocessing visualisation", value=False) # # --------------------------------------------------- # # Sidebar controls - Prediction # # --------------------------------------------------- # with st.sidebar.expander("Prediction Controls", expanded=False): # st.markdown("Run model prediction on the preprocessed selected sample.") # batch_size = st.number_input("Batch size", min_value=1, max_value=32, value=2, step=1) # predict_now = st.button("Predict") # show_prediction_viz = st.checkbox("Display prediction visualisation", value=False) # # --------------------------------------------------- # # Load selected sample from EDA # # --------------------------------------------------- # selected_row = ts_df[ts_df["sample_name"] == selected_name].iloc[0] # img_path = selected_row["imgFiles"] # LF # gdt_path = selected_row["gdtFiles"] # HF # imgTs = load_npy_file(img_path) # gdtTs = load_npy_file(gdt_path) # # --------------------------------------------------- # # Initialise session state # # --------------------------------------------------- # if "preprocessed_data" not in st.session_state: # st.session_state["preprocessed_data"] = None # if "preprocessed_sample_name" not in st.session_state: # st.session_state["preprocessed_sample_name"] = None # if "prediction_result" not in st.session_state: # st.session_state["prediction_result"] = None # if "prediction_sample_name" not in st.session_state: # st.session_state["prediction_sample_name"] = None # if "prediction_sample_idx" not in st.session_state: # st.session_state["prediction_sample_idx"] = None # # --------------------------------------------------- # # Run preprocessing # # --------------------------------------------------- # if apply_preprocessing: # try: # with st.spinner("Applying preprocessing..."): # processed = preprocess_single_pair( # hr_array=gdtTs, # lr_array=imgTs, # mask_file=MASK_FILE, # target_size=(int(target_height), int(target_width)) # ) # st.session_state["preprocessed_data"] = processed # st.session_state["preprocessed_sample_name"] = selected_name # # Clear older prediction when preprocessing changes # st.session_state["prediction_result"] = None # st.session_state["prediction_sample_name"] = None # st.session_state["prediction_sample_idx"] = None # st.success(f"Preprocessing completed for sample: {selected_name}") # except Exception as e: # st.error(f"Preprocessing failed: {e}") # # --------------------------------------------------- # # Prediction helper: choose sample index before predict # # --------------------------------------------------- # processed_for_prediction = st.session_state.get("preprocessed_data") # processed_sample_name = st.session_state.get("preprocessed_sample_name") # prediction_sample_idx = 0 # if processed_for_prediction is not None and processed_sample_name == selected_name: # if processed_for_prediction["num_samples"] > 1: # prediction_sample_idx = st.sidebar.slider( # "Prediction sample index", # min_value=0, # max_value=processed_for_prediction["num_samples"] - 1, # value=0, # key="prediction_sample_index_slider" # ) # # --------------------------------------------------- # # Run prediction only when button is clicked # # --------------------------------------------------- # if predict_now: # processed = st.session_state.get("preprocessed_data") # processed_name = st.session_state.get("preprocessed_sample_name") # if processed is None: # st.error("Please apply preprocessing first before running prediction.") # elif processed_name != selected_name: # st.error("The selected file has changed. Please apply preprocessing again before prediction.") # else: # try: # with st.spinner("Loading model and running prediction..."): # model = load_model(str(WEIGHT_FILE), model_device=str(device)) # pred_result = predict_single_processed_sample( # model=model, # processed=processed, # sample_idx=prediction_sample_idx, # batch_size=int(batch_size), # model_device=str(device) # ) # st.session_state["prediction_result"] = pred_result # st.session_state["prediction_sample_name"] = selected_name # st.session_state["prediction_sample_idx"] = prediction_sample_idx # st.success( # f"Prediction completed for sample: {selected_name} " # f"(index: {prediction_sample_idx})" # ) # except Exception as e: # st.error(f"Prediction failed: {e}") # # --------------------------------------------------- # # Build visible tabs dynamically # # --------------------------------------------------- # tab_names = [] # tab_keys = [] # if show_dataframe: # tab_names.append("Dataset") # tab_keys.append("dataframe") # if show_stats: # tab_names.append("Statistics") # tab_keys.append("stats") # if show_visualisation: # tab_names.append("EDA Visualisation") # tab_keys.append("eda_viz") # if show_preprocessing_viz: # tab_names.append("Preprocessing Visualisation") # tab_keys.append("prep_viz") # if show_prediction_viz: # tab_names.append("Prediction Visualisation") # tab_keys.append("pred_viz") # # --------------------------------------------------- # # Main display # # --------------------------------------------------- # if not tab_names: # st.empty() # else: # tabs = st.tabs(tab_names) # for tab, key in zip(tabs, tab_keys): # with tab: # # --------------------------------------- # # Dataset tab # # --------------------------------------- # if key == "dataframe": # st.markdown("### Available Dataset") # st.dataframe(ts_df, use_container_width=True) # # --------------------------------------- # # Statistics tab # # --------------------------------------- # elif key == "stats": # st.markdown("### Selected Sample Statistics") # col1, col2 = st.columns(2) # img_stats = array_summary(imgTs) # gdt_stats = array_summary(gdtTs) # with col1: # st.markdown("#### LF Image") # st.write(f"**File:** `{selected_name}`") # st.write(f"**Shape:** {img_stats['shape']}") # st.write(f"**Dimensions:** {img_stats['ndim']}D") # st.write(f"**Dtype:** {img_stats['dtype']}") # st.write(f"**Min:** {img_stats['min']:.6f}") # st.write(f"**Max:** {img_stats['max']:.6f}") # st.write(f"**Mean:** {img_stats['mean']:.6f}") # with col2: # st.markdown("#### HF Ground Truth") # st.write(f"**File:** `{selected_name}`") # st.write(f"**Shape:** {gdt_stats['shape']}") # st.write(f"**Dimensions:** {gdt_stats['ndim']}D") # st.write(f"**Dtype:** {gdt_stats['dtype']}") # st.write(f"**Min:** {gdt_stats['min']:.6f}") # st.write(f"**Max:** {gdt_stats['max']:.6f}") # st.write(f"**Mean:** {gdt_stats['mean']:.6f}") # # --------------------------------------- # # EDA Visualisation tab # # --------------------------------------- # elif key == "eda_viz": # st.markdown("### EDA Image Visualisation") # if imgTs.ndim == 2 and gdtTs.ndim == 2: # img_show = imgTs # gdt_show = gdtTs # elif imgTs.ndim == 3 and gdtTs.ndim == 3: # max_slice = min(imgTs.shape[0], gdtTs.shape[0]) - 1 # slice_idx = st.slider( # "Choose slice index", # min_value=0, # max_value=max_slice, # value=0, # key="eda_slice_slider" # ) # img_show = get_display_slice(imgTs, slice_idx) # gdt_show = get_display_slice(gdtTs, slice_idx) # st.info(f"Displaying EDA slice index: {slice_idx}") # else: # st.error("LF and HF arrays do not have compatible dimensions for joint display.") # st.stop() # fig = plot_side_by_side( # img_show, # gdt_show, # lf_title=f"LF: {selected_name}", # hf_title=f"HF: {selected_name}" # ) # st.pyplot(fig) # # --------------------------------------- # # Preprocessing Visualisation tab # # --------------------------------------- # elif key == "prep_viz": # st.markdown("### Preprocessing Visualisation") # processed = st.session_state.get("preprocessed_data") # processed_sample_name = st.session_state.get("preprocessed_sample_name") # if processed is None: # st.warning("Please click 'Apply preprocessing' in the sidebar first.") # st.stop() # if processed_sample_name != selected_name: # st.warning( # "The currently displayed preprocessing result belongs to a different selected file. " # "Please click 'Apply preprocessing' again for the newly selected sample." # ) # st.stop() # num_samples = processed["num_samples"] # if num_samples == 1: # sample_idx = 0 # st.info("This sample is 2D, so only one processed image is available.") # else: # sample_idx = st.slider( # "Choose preprocessing sample index", # min_value=0, # max_value=num_samples - 1, # value=0, # key="prep_sample_slider" # ) # st.info(f"Displaying preprocessing sample index: {sample_idx}") # sample_udHRkspace = processed["ud_HR_kspace"][sample_idx] # sample_fsHRkspace = processed["full_HR_kspace"][sample_idx] # sample_udLRkspace = processed["ud_LR_kspace"][sample_idx] # sample_fsLRkspace = processed["full_LR_kspace"][sample_idx] # sample_udHRimg = processed["mag_HR_images"][sample_idx] # sample_fsHRimg = processed["HR_images"][sample_idx] # sample_udLRimg = processed["mag_LR_images"][sample_idx] # sample_fsLRimg = processed["LR_images"][sample_idx] # st.markdown("#### Processed Sample Shapes") # col1, col2 = st.columns(2) # # with col1: # # st.write(f"**udHRkspace:** {sample_udHRkspace.shape}") # # st.write(f"**fsHRkspace:** {sample_fsHRkspace.shape}") # # st.write(f"**udHRimg:** {sample_udHRimg.shape}") # # st.write(f"**fsHRimg:** {sample_fsHRimg.shape}") # # with col2: # # st.write(f"**udLRkspace:** {sample_udLRkspace.shape}") # # st.write(f"**fsLRkspace:** {sample_fsLRkspace.shape}") # # st.write(f"**udLRimg:** {sample_udLRimg.shape}") # # st.write(f"**fsLRimg:** {sample_fsLRimg.shape}") # st.markdown("#### HR Domain Visualisation") # fig_hr = plot_preprocessing_hr(sample_idx, processed) # st.pyplot(fig_hr) # st.markdown("#### LR Domain Visualisation") # fig_lr = plot_preprocessing_lr(sample_idx, processed) # st.pyplot(fig_lr) # # --------------------------------------- # # Prediction Visualisation tab # # --------------------------------------- # elif key == "pred_viz": # st.markdown("### Prediction Visualisation") # pred_result = st.session_state.get("prediction_result") # pred_sample_name = st.session_state.get("prediction_sample_name") # pred_sample_idx = st.session_state.get("prediction_sample_idx") # if pred_result is None: # st.warning("Please click 'Predict' in the sidebar first.") # st.stop() # if pred_sample_name != selected_name: # st.warning( # "The currently displayed prediction belongs to a different selected file. " # "Please run preprocessing and prediction again for the newly selected sample." # ) # st.stop() # st.markdown("#### Prediction Metrics") # m1, m2, m3, m4 = st.columns(4) # with m1: # st.metric("LR SSIM", f"{pred_result['ssimLR']:.4f}") # with m2: # st.metric("LR PSNR", f"{pred_result['psnrLR']:.2f} dB") # with m3: # st.metric("Recon SSIM", f"{pred_result['ssimRec']:.4f}") # with m4: # st.metric("Recon PSNR", f"{pred_result['psnrRec']:.2f} dB") # st.info(f"Prediction shown for sample index: {pred_sample_idx}") # fig_pred = plot_prediction_results(pred_result) # st.pyplot(fig_pred) # (04) Full Implementation from pathlib import Path import numpy as np import pandas as pd import matplotlib.pyplot as plt import streamlit as st import torch import torch.nn as nn import torch.nn.functional as F from scipy.io import loadmat from skimage.metrics import structural_similarity as ssim from skimage.metrics import peak_signal_noise_ratio as psnr # --------------------------------------------------- # Page config # --------------------------------------------------- st.set_page_config( page_title="MRI Reconstruction Studio", page_icon="🧠", layout="wide" ) # --------------------------------------------------- # Custom CSS Styling # --------------------------------------------------- CUSTOM_CSS = """ <style> /* Main app background */ .stApp { background: linear-gradient(135deg, #f8fbff 0%, #eef6ff 45%, #ffffff 100%); } /* Main container */ .block-container { padding-top: 1.5rem; padding-bottom: 2rem; max-width: 1250px; } /* Sidebar */ [data-testid="stSidebar"] { background: linear-gradient(180deg, #0f172a 0%, #1e293b 100%); } [data-testid="stSidebar"] * { color: #f8fafc !important; } /* Hero */ .hero-box { background: linear-gradient(135deg, #0ea5e9, #2563eb); padding: 1.4rem 1.6rem; border-radius: 20px; color: white; box-shadow: 0 12px 30px rgba(37, 99, 235, 0.18); margin-bottom: 1rem; } .hero-title { font-size: 2rem; font-weight: 800; margin-bottom: 0.3rem; } .hero-subtitle { font-size: 1rem; opacity: 0.96; line-height: 1.5; } /* Section title */ .section-title { font-size: 1.15rem; font-weight: 700; color: #0f172a; margin-top: 0.5rem; margin-bottom: 0.75rem; } /* Cards */ .soft-card { background: #ffffff; border: 1px solid rgba(148, 163, 184, 0.20); border-radius: 18px; padding: 1rem 1rem; box-shadow: 0 10px 28px rgba(15, 23, 42, 0.06); margin-bottom: 1rem; } /* Stat cards */ .stat-card { background: linear-gradient(180deg, #ffffff 0%, #f8fbff 100%); border: 1px solid rgba(148, 163, 184, 0.24); border-radius: 16px; padding: 0.9rem 1rem; box-shadow: 0 8px 18px rgba(15, 23, 42, 0.05); margin-bottom: 0.8rem; } .stat-label { font-size: 0.82rem; color: #475569; margin-bottom: 0.2rem; } .stat-value { font-size: 1.05rem; font-weight: 700; color: #0f172a; } /* Metric cards */ .metric-box { background: linear-gradient(135deg, #ffffff 0%, #f8fbff 100%); border: 1px solid rgba(59, 130, 246, 0.15); border-radius: 18px; padding: 0.95rem 1rem; box-shadow: 0 8px 24px rgba(15, 23, 42, 0.05); text-align: center; } .metric-title { font-size: 0.8rem; color: #475569; margin-bottom: 0.25rem; } .metric-value { font-size: 1.2rem; font-weight: 800; color: #1d4ed8; } /* Badge pills */ .badge { display: inline-block; background: #e0f2fe; color: #075985; padding: 0.35rem 0.7rem; border-radius: 999px; font-size: 0.82rem; font-weight: 600; margin-right: 0.4rem; margin-bottom: 0.4rem; } /* Tabs */ .stTabs [data-baseweb="tab-list"] { gap: 8px; } .stTabs [data-baseweb="tab"] { background: #eaf2ff; border-radius: 999px; padding: 0.35rem 1rem; color: #0f172a; font-weight: 600; } .stTabs [aria-selected="true"] { background: linear-gradient(135deg, #2563eb, #0ea5e9) !important; color: white !important; } /* Buttons */ .stButton > button { border-radius: 999px; font-weight: 700; border: none; padding: 0.55rem 1rem; box-shadow: 0 8px 18px rgba(37, 99, 235, 0.15); } /* Expanders */ details { border-radius: 14px; overflow: hidden; } details summary { font-weight: 700 !important; } /* Dataframe */ [data-testid="stDataFrame"] { border-radius: 16px; overflow: hidden; } /* Plot wrapper */ .plot-card { background: #ffffff; border: 1px solid rgba(148, 163, 184, 0.20); border-radius: 18px; padding: 0.7rem; box-shadow: 0 10px 24px rgba(15, 23, 42, 0.05); margin-top: 0.6rem; margin-bottom: 1rem; } </style> """ st.markdown(CUSTOM_CSS, unsafe_allow_html=True) # --------------------------------------------------- # Hero section # --------------------------------------------------- st.markdown( """ <div class="hero-box"> <div class="hero-title">🧠 MRI Reconstruction Studio</div> <div class="hero-subtitle"> Explore paired HF/LF MRI samples, run preprocessing, generate predictions, and inspect reconstruction quality through interactive visualisations and metrics. </div> </div> """, unsafe_allow_html=True ) st.markdown( """ <span class="badge">πŸ“‚ EDA</span> <span class="badge">βš™οΈ Preprocessing</span> <span class="badge">πŸ€– Prediction</span> <span class="badge">πŸ“Š Metrics</span> """, unsafe_allow_html=True ) # --------------------------------------------------- # Resolve project paths # --------------------------------------------------- ROOT_DIR = Path(__file__).resolve().parent.parent HF_DIR = ROOT_DIR / "data" / "HF" LF_DIR = ROOT_DIR / "data" / "LF" MASK_FILE = ROOT_DIR / "mask" / "prs" / "mask_30.mat" WEIGHT_FILE = ROOT_DIR / "weight" / "udksp30Unet_weight.pth" # --------------------------------------------------- # Device setup # --------------------------------------------------- device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # --------------------------------------------------- # UI helper functions # --------------------------------------------------- def section_title(text: str): st.markdown(f'<div class="section-title">{text}</div>', unsafe_allow_html=True) def stat_card(label: str, value: str): st.markdown( f""" <div class="stat-card"> <div class="stat-label">{label}</div> <div class="stat-value">{value}</div> </div> """, unsafe_allow_html=True ) def metric_card(title: str, value: str): st.markdown( f""" <div class="metric-box"> <div class="metric-title">{title}</div> <div class="metric-value">{value}</div> </div> """, unsafe_allow_html=True ) def open_card(): st.markdown('<div class="soft-card">', unsafe_allow_html=True) def close_card(): st.markdown('</div>', unsafe_allow_html=True) def plot_wrapper_start(): st.markdown('<div class="plot-card">', unsafe_allow_html=True) def plot_wrapper_end(): st.markdown('</div>', unsafe_allow_html=True) # --------------------------------------------------- # Helper functions for EDA # --------------------------------------------------- @st.cache_data def get_paired_files(hf_dir: Path, lf_dir: Path) -> pd.DataFrame: hf_files = sorted([f for f in hf_dir.glob("*.npy")]) lf_files = sorted([f for f in lf_dir.glob("*.npy")]) hf_map = {f.name: f for f in hf_files} lf_map = {f.name: f for f in lf_files} common_names = sorted(set(hf_map.keys()) & set(lf_map.keys())) return pd.DataFrame({ "sample_name": common_names, "gdtFiles": [str(hf_map[name]) for name in common_names], # HF "imgFiles": [str(lf_map[name]) for name in common_names], # LF }) @st.cache_data def load_npy_file(file_path: str) -> np.ndarray: return np.load(file_path) def array_summary(arr: np.ndarray) -> dict: return { "shape": arr.shape, "ndim": arr.ndim, "dtype": str(arr.dtype), "min": float(np.min(arr)), "max": float(np.max(arr)), "mean": float(np.mean(arr)), } def get_display_slice(arr: np.ndarray, slice_idx: int | None = None) -> np.ndarray: if arr.ndim == 2: return arr if arr.ndim == 3: return arr[slice_idx if slice_idx is not None else 0] raise ValueError(f"Unsupported array shape for display: {arr.shape}") def plot_side_by_side(lf_img: np.ndarray, hf_img: np.ndarray, lf_title="LF Image", hf_title="HF Image"): fig, axes = plt.subplots(1, 2, figsize=(12, 5)) axes[0].imshow(lf_img, cmap="gray") axes[0].set_title(lf_title) axes[0].axis("off") axes[1].imshow(hf_img, cmap="gray") axes[1].set_title(hf_title) axes[1].axis("off") plt.tight_layout() return fig # --------------------------------------------------- # Preprocessing functions # --------------------------------------------------- def resizeImage( img_np: np.ndarray, target_size=(256, 256), mode="bicubic", antialias=True, device="cpu" ): """ Resize a 2D NumPy image to the target size using torch interpolation. """ if img_np.shape[-2:] == target_size: return img_np.astype(np.float32) tensor = torch.from_numpy(img_np.astype(np.float32)).to(device) tensor = tensor.unsqueeze(0).unsqueeze(0) tensor = F.interpolate( tensor, size=target_size, mode=mode, align_corners=False if mode in ["bilinear", "bicubic"] else None, antialias=antialias ) tensor = tensor.squeeze(0).squeeze(0) return tensor.cpu().numpy() def fft2c(image): """ Convert image -> centered 2D k-space. """ return np.fft.fftshift( np.fft.fft2(np.fft.ifftshift(image, axes=(-2, -1))), axes=(-2, -1) ) def ifft2c(kspace): """ Convert centered 2D k-space -> image magnitude. """ return np.abs( np.fft.ifftshift( np.fft.ifft2(np.fft.fftshift(kspace, axes=(-2, -1))), axes=(-2, -1) ) ) @st.cache_data def load_mask(mask_file: str) -> np.ndarray: """ Load the undersampling mask once and cache it. """ mask_data = loadmat(mask_file) mask_matrix = mask_data["mask_matrix"] mask_matrix = np.fft.ifftshift(mask_matrix).astype(np.float32) return mask_matrix def und2DMask(slice_kspace, maskFile): """ Apply undersampling mask to one 2D k-space slice. """ undersamplingMask = load_mask(str(maskFile)) udkspace = undersamplingMask * slice_kspace return udkspace, undersamplingMask def ch2ksp(c): """ Convert 2-channel representation to complex k-space. """ return c[0, :, :] + 1j * c[1, :, :] def preprocess_single_pair(hr_array: np.ndarray, lr_array: np.ndarray, mask_file: Path, target_size=(256, 256)): """ Preprocess one selected HF/LF pair. Handles: - 2D arrays: process single image - 3D arrays: process slice-by-slice """ HR_images = [] full_HR_kspace = [] ud_HR_kspace = [] mag_HR_images = [] LR_images = [] full_LR_kspace = [] ud_LR_kspace = [] mag_LR_images = [] if hr_array.ndim == 2 and lr_array.ndim == 2: hr_slices = [hr_array] lr_slices = [lr_array] elif hr_array.ndim == 3 and lr_array.ndim == 3: num_slices = min(hr_array.shape[0], lr_array.shape[0]) hr_slices = [hr_array[i] for i in range(num_slices)] lr_slices = [lr_array[i] for i in range(num_slices)] else: raise ValueError("HF and LF arrays must both be 2D or both be 3D with matching slice structure.") for HRimage, LRimage in zip(hr_slices, lr_slices): HRimage = resizeImage(HRimage, target_size=target_size) LRimage = resizeImage(LRimage, target_size=target_size) full_HRkspace = fft2c(HRimage) full_LRkspace = fft2c(LRimage) ud_HRkspace, _ = und2DMask(full_HRkspace, mask_file) ud_LRkspace, _ = und2DMask(full_LRkspace, mask_file) recon_HRimage = ifft2c(ud_HRkspace) recon_LRimage = ifft2c(ud_LRkspace) mag_HRimage = np.abs(recon_HRimage) mag_LRimage = np.abs(recon_LRimage) HR_images.append(HRimage) full_HR_kspace.append(full_HRkspace) ud_HR_kspace.append(ud_HRkspace) mag_HR_images.append(mag_HRimage) LR_images.append(LRimage) full_LR_kspace.append(full_LRkspace) ud_LR_kspace.append(ud_LRkspace) mag_LR_images.append(mag_LRimage) return { "HR_images": HR_images, "full_HR_kspace": full_HR_kspace, "ud_HR_kspace": ud_HR_kspace, "mag_HR_images": mag_HR_images, "LR_images": LR_images, "full_LR_kspace": full_LR_kspace, "ud_LR_kspace": ud_LR_kspace, "mag_LR_images": mag_LR_images, "num_samples": len(HR_images), "target_size": target_size, } def plot_preprocessing_hr(sample_idx: int, processed: dict): sample_fsHRkspace = processed["full_HR_kspace"][sample_idx] sample_udHRkspace = processed["ud_HR_kspace"][sample_idx] sample_fsHRimg = processed["HR_images"][sample_idx] sample_udHRimg = processed["mag_HR_images"][sample_idx] fig, axes = plt.subplots(1, 4, figsize=(16, 4)) axes[0].imshow(np.log(np.abs(sample_fsHRkspace) + 1e-9), cmap="gray") axes[0].set_title("fsHR k-space") axes[0].axis("off") axes[1].imshow(sample_fsHRimg, cmap="gray") axes[1].set_title("fsHR Image") axes[1].axis("off") axes[2].imshow(np.log(np.abs(sample_udHRkspace) + 1e-9), cmap="gray") axes[2].set_title("udHR k-space") axes[2].axis("off") axes[3].imshow(sample_udHRimg, cmap="gray") axes[3].set_title("udHR Image") axes[3].axis("off") plt.tight_layout() return fig def plot_preprocessing_lr(sample_idx: int, processed: dict): sample_fsLRkspace = processed["full_LR_kspace"][sample_idx] sample_udLRkspace = processed["ud_LR_kspace"][sample_idx] sample_fsLRimg = processed["LR_images"][sample_idx] sample_udLRimg = processed["mag_LR_images"][sample_idx] fig, axes = plt.subplots(1, 4, figsize=(16, 4)) axes[0].imshow(np.log(np.abs(sample_fsLRkspace) + 1e-9), cmap="gray") axes[0].set_title("fsLR k-space") axes[0].axis("off") axes[1].imshow(sample_fsLRimg, cmap="gray") axes[1].set_title("fsLR Image") axes[1].axis("off") axes[2].imshow(np.log(np.abs(sample_udLRkspace) + 1e-9), cmap="gray") axes[2].set_title("udLR k-space") axes[2].axis("off") axes[3].imshow(sample_udLRimg, cmap="gray") axes[3].set_title("udLR Image") axes[3].axis("off") plt.tight_layout() return fig # --------------------------------------------------- # Model setup # --------------------------------------------------- class UNetBlock(nn.Module): """ Basic convolutional block in the U-Net with two convolutions + ReLU """ def __init__(self, in_channels, out_channels, kernel_size=3, padding=1): super(UNetBlock, self).__init__() self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size, padding=padding) self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size, padding=padding) self.relu = nn.ReLU(inplace=True) def forward(self, x): x = self.relu(self.conv1(x)) x = self.relu(self.conv2(x)) return x class KSpaceUNet(nn.Module): """ Modified U-Net with 3 encoder-decoder layers for k-space/image reconstruction """ def __init__(self, input_channels=2, output_channels=2, num_filters=64): super(KSpaceUNet, self).__init__() self.enc1 = UNetBlock(input_channels, num_filters) self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2) self.enc2 = UNetBlock(num_filters, num_filters * 2) self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2) self.enc3 = UNetBlock(num_filters * 2, num_filters * 4) self.pool3 = nn.MaxPool2d(kernel_size=2, stride=2) self.bottleneck = UNetBlock(num_filters * 4, num_filters * 8) self.up3 = nn.ConvTranspose2d(num_filters * 8, num_filters * 4, kernel_size=2, stride=2) self.dec3 = UNetBlock(num_filters * 8, num_filters * 4) self.up2 = nn.ConvTranspose2d(num_filters * 4, num_filters * 2, kernel_size=2, stride=2) self.dec2 = UNetBlock(num_filters * 4, num_filters * 2) self.up1 = nn.ConvTranspose2d(num_filters * 2, num_filters, kernel_size=2, stride=2) self.dec1 = UNetBlock(num_filters * 2, num_filters) self.final_conv = nn.Conv2d(num_filters, output_channels, kernel_size=1) def forward(self, x): e1 = self.enc1(x) p1 = self.pool1(e1) e2 = self.enc2(p1) p2 = self.pool2(e2) e3 = self.enc3(p2) p3 = self.pool3(e3) b = self.bottleneck(p3) u3 = self.up3(b) d3 = self.dec3(torch.cat([u3, e3], dim=1)) u2 = self.up2(d3) d2 = self.dec2(torch.cat([u2, e2], dim=1)) u1 = self.up1(d2) d1 = self.dec1(torch.cat([u1, e1], dim=1)) return self.final_conv(d1) @st.cache_resource def load_model(weight_file: str, model_device: str = "cpu"): """ Load the PyTorch model once and cache it for reuse. """ model = KSpaceUNet().to(model_device) checkpoint = torch.load(weight_file, map_location=model_device) model.load_state_dict(checkpoint) model.eval() return model def safe_data_range(arr: np.ndarray) -> float: """ Avoid zero data_range issues in SSIM/PSNR calculations. """ dr = float(np.ptp(np.abs(arr))) return dr if dr > 0 else 1e-9 def predict_single_processed_sample(model, processed: dict, sample_idx: int, batch_size: int = 2, model_device: str = "cpu"): """ Run model prediction on one processed sample index. """ ud_Imgkspace = processed["ud_LR_kspace"][sample_idx] full_Gdtkspace = processed["full_HR_kspace"][sample_idx] udLRkspace_Ts = np.array(ud_Imgkspace) fsHRkspace_Ts = np.array(full_Gdtkspace) target_h, target_w = processed["target_size"] udLRkspace_Ts = udLRkspace_Ts.reshape(-1, target_h, target_w) fsHRkspace_Ts = fsHRkspace_Ts.reshape(-1, target_h, target_w) X_tstCpx = udLRkspace_Ts[:, :, :] + 1j * udLRkspace_Ts[:, :, :] y_tstCpx = fsHRkspace_Ts[:, :, :] + 1j * fsHRkspace_Ts[:, :, :] X_tst1_real = np.array([np.real(ifft2c(slice_)) for slice_ in X_tstCpx]) X_tst1_imag = np.array([np.imag(ifft2c(slice_)) for slice_ in X_tstCpx]) y_tst1_real = np.array([np.real(ifft2c(slice_)) for slice_ in y_tstCpx]) y_tst1_imag = np.array([np.imag(ifft2c(slice_)) for slice_ in y_tstCpx]) X_tst1 = np.stack([X_tst1_real, X_tst1_imag], axis=1) y_tst1 = np.stack([y_tst1_real, y_tst1_imag], axis=1) X_test = torch.tensor(X_tst1, dtype=torch.float32).to(model_device) y_test = torch.tensor(y_tst1, dtype=torch.float32).to(model_device) y_pred_batches = [] for batch_start in range(0, X_test.shape[0], batch_size): batch_end = min(batch_start + batch_size, X_test.shape[0]) X_test_batch = X_test[batch_start:batch_end] with torch.no_grad(): y_pred_tensor_batch = model(X_test_batch) y_pred_batches.append(y_pred_tensor_batch.cpu().numpy()) predKsp = np.concatenate(y_pred_batches, axis=0).squeeze() pred_kspace = np.sqrt(predKsp[0, :, :]**2 + predKsp[1, :, :]**2) y_test_np = y_test.squeeze().cpu().numpy() y_test_np = np.sqrt(y_test_np[0, :, :]**2 + y_test_np[1, :, :]**2) X_test_np = X_test.squeeze().cpu().numpy() X_test_np = np.sqrt(X_test_np[0, :, :]**2 + X_test_np[1, :, :]**2) M_Imgimg = ud_Imgkspace M_Tgtimg = full_Gdtkspace M_Prdimg = fft2c(pred_kspace) ssimLR = ssim(np.abs(y_test_np), np.abs(X_test_np), data_range=safe_data_range(X_test_np)) psnrLR = psnr(np.abs(y_test_np), np.abs(X_test_np), data_range=safe_data_range(X_test_np)) ssimRec = ssim(np.abs(y_test_np), np.abs(pred_kspace), data_range=safe_data_range(pred_kspace)) psnrRec = psnr(np.abs(y_test_np), np.abs(pred_kspace), data_range=safe_data_range(pred_kspace)) return { "M_Imgimg": M_Imgimg, "M_Tgtimg": M_Tgtimg, "M_Prdimg": M_Prdimg, "X_test": X_test_np, "y_test": y_test_np, "pred_kspace": pred_kspace, "ssimLR": float(ssimLR), "psnrLR": float(psnrLR), "ssimRec": float(ssimRec), "psnrRec": float(psnrRec), "sample_idx": sample_idx, } def plot_prediction_results(pred_result: dict): """ Plot prediction outputs in the same 2x4 style as the notebook. """ fig = plt.figure(figsize=(20, 8)) plt.subplot(2, 4, 1) plt.imshow(np.log(np.abs(pred_result["M_Imgimg"]) + 1e-9), cmap="gray") plt.title("udLR k-space") plt.axis("off") plt.subplot(2, 4, 2) plt.imshow(np.log(np.abs(pred_result["M_Tgtimg"]) + 1e-9), cmap="gray") plt.title("fsHR k-space") plt.axis("off") plt.subplot(2, 4, 3) plt.imshow(np.log(np.abs(pred_result["M_Prdimg"]) + 1e-9), cmap="gray") plt.title("IQT k-space") plt.axis("off") plt.subplot(2, 4, 5) plt.imshow(np.abs(pred_result["X_test"]), cmap="gray") plt.title( f"udLR Img\nSSIM: {pred_result['ssimLR']:.4f}, PSNR: {pred_result['psnrLR']:.2f} dB" ) plt.axis("off") plt.subplot(2, 4, 6) plt.imshow(np.abs(pred_result["y_test"]), cmap="gray") plt.title("fsHR Img") plt.axis("off") plt.subplot(2, 4, 7) plt.imshow(np.abs(pred_result["pred_kspace"]), cmap="gray") plt.title( f"IQT Img\nSSIM: {pred_result['ssimRec']:.4f}, PSNR: {pred_result['psnrRec']:.2f} dB" ) plt.axis("off") plt.tight_layout() return fig # --------------------------------------------------- # Validate folders/files # --------------------------------------------------- if not HF_DIR.exists(): st.error(f"HF directory not found: {HF_DIR}") st.stop() if not LF_DIR.exists(): st.error(f"LF directory not found: {LF_DIR}") st.stop() if not MASK_FILE.exists(): st.error(f"Mask file not found: {MASK_FILE}") st.stop() if not WEIGHT_FILE.exists(): st.error(f"Weight file not found: {WEIGHT_FILE}") st.stop() # --------------------------------------------------- # Load paired dataset # --------------------------------------------------- ts_df = get_paired_files(HF_DIR, LF_DIR) if ts_df.empty: st.warning("No matching .npy file pairs found in data/HF and data/LF.") st.stop() # --------------------------------------------------- # Sidebar controls - EDA # --------------------------------------------------- with st.sidebar.expander("πŸ“‚ EDA Controls", expanded=False): st.caption("Select a paired LF/HF sample and choose what to inspect.") selected_name = st.selectbox( "Choose sample file", ts_df["sample_name"].tolist(), index=0 ) show_stats = st.checkbox("πŸ“ˆ Show array statistics", value=False) show_visualisation = st.checkbox("πŸ–ΌοΈ Display EDA visualisation", value=False) show_dataframe = st.sidebar.checkbox("πŸ—‚οΈ Show dataframe", value=False) # --------------------------------------------------- # Sidebar controls - Preprocessing # --------------------------------------------------- with st.sidebar.expander("βš™οΈ Preprocessing Controls", expanded=False): st.caption("Resize, transform to k-space, undersample, and reconstruct image magnitude.") target_height = st.number_input("Target height", min_value=32, max_value=1024, value=256, step=32) target_width = st.number_input("Target width", min_value=32, max_value=1024, value=256, step=32) apply_preprocessing = st.button("βš™οΈ Apply preprocessing") show_preprocessing_viz = st.checkbox("πŸ§ͺ Display preprocessing visualisation", value=False) # --------------------------------------------------- # Sidebar controls - Prediction # --------------------------------------------------- with st.sidebar.expander("πŸ€– Prediction Controls", expanded=False): st.caption("Run the trained U-Net reconstruction model on the currently processed sample.") batch_size = st.number_input("Batch size", min_value=1, max_value=32, value=2, step=1) predict_now = st.button("πŸš€ Predict") show_prediction_viz = st.checkbox("πŸ“Š Display prediction visualisation", value=False) # --------------------------------------------------- # Load selected sample from EDA # --------------------------------------------------- selected_row = ts_df[ts_df["sample_name"] == selected_name].iloc[0] img_path = selected_row["imgFiles"] # LF gdt_path = selected_row["gdtFiles"] # HF imgTs = load_npy_file(img_path) gdtTs = load_npy_file(gdt_path) # --------------------------------------------------- # Initialise session state # --------------------------------------------------- if "preprocessed_data" not in st.session_state: st.session_state["preprocessed_data"] = None if "preprocessed_sample_name" not in st.session_state: st.session_state["preprocessed_sample_name"] = None if "prediction_result" not in st.session_state: st.session_state["prediction_result"] = None if "prediction_sample_name" not in st.session_state: st.session_state["prediction_sample_name"] = None if "prediction_sample_idx" not in st.session_state: st.session_state["prediction_sample_idx"] = None # --------------------------------------------------- # Run preprocessing # --------------------------------------------------- if apply_preprocessing: try: with st.spinner("Applying preprocessing..."): processed = preprocess_single_pair( hr_array=gdtTs, lr_array=imgTs, mask_file=MASK_FILE, target_size=(int(target_height), int(target_width)) ) st.session_state["preprocessed_data"] = processed st.session_state["preprocessed_sample_name"] = selected_name st.session_state["prediction_result"] = None st.session_state["prediction_sample_name"] = None st.session_state["prediction_sample_idx"] = None st.success(f"Preprocessing completed for sample: {selected_name}") except Exception as e: st.error(f"Preprocessing failed: {e}") # --------------------------------------------------- # Prediction helper: choose sample index before predict # --------------------------------------------------- processed_for_prediction = st.session_state.get("preprocessed_data") processed_sample_name = st.session_state.get("preprocessed_sample_name") prediction_sample_idx = 0 if processed_for_prediction is not None and processed_sample_name == selected_name: if processed_for_prediction["num_samples"] > 1: prediction_sample_idx = st.sidebar.slider( "Prediction sample index", min_value=0, max_value=processed_for_prediction["num_samples"] - 1, value=0, key="prediction_sample_index_slider" ) # --------------------------------------------------- # Run prediction only when button is clicked # --------------------------------------------------- if predict_now: processed = st.session_state.get("preprocessed_data") processed_name = st.session_state.get("preprocessed_sample_name") if processed is None: st.error("Please apply preprocessing first before running prediction.") elif processed_name != selected_name: st.error("The selected file has changed. Please apply preprocessing again before prediction.") else: try: with st.spinner("Loading model and running prediction..."): model = load_model(str(WEIGHT_FILE), model_device=str(device)) pred_result = predict_single_processed_sample( model=model, processed=processed, sample_idx=prediction_sample_idx, batch_size=int(batch_size), model_device=str(device) ) st.session_state["prediction_result"] = pred_result st.session_state["prediction_sample_name"] = selected_name st.session_state["prediction_sample_idx"] = prediction_sample_idx st.success( f"Prediction completed for sample: {selected_name} " f"(index: {prediction_sample_idx})" ) except Exception as e: st.error(f"Prediction failed: {e}") # --------------------------------------------------- # Build visible tabs dynamically # --------------------------------------------------- tab_names = [] tab_keys = [] if show_dataframe: tab_names.append("Dataset") tab_keys.append("dataframe") if show_stats: tab_names.append("Statistics") tab_keys.append("stats") if show_visualisation: tab_names.append("EDA Visualisation") tab_keys.append("eda_viz") if show_preprocessing_viz: tab_names.append("Preprocessing Visualisation") tab_keys.append("prep_viz") if show_prediction_viz: tab_names.append("Prediction Visualisation") tab_keys.append("pred_viz") # --------------------------------------------------- # Main display # --------------------------------------------------- if not tab_names: st.empty() else: tabs = st.tabs(tab_names) for tab, key in zip(tabs, tab_keys): with tab: # --------------------------------------- # Dataset tab # --------------------------------------- if key == "dataframe": section_title("πŸ—‚οΈ Available Dataset") open_card() st.dataframe(ts_df, use_container_width=True) close_card() # --------------------------------------- # Statistics tab # --------------------------------------- elif key == "stats": section_title("πŸ“ˆ Selected Sample Statistics") img_stats = array_summary(imgTs) gdt_stats = array_summary(gdtTs) col1, col2 = st.columns(2) with col1: open_card() st.markdown("#### πŸ–ΌοΈ LF Image") stat_card("File", selected_name) stat_card("Shape", str(img_stats["shape"])) stat_card("Dimensions", f'{img_stats["ndim"]}D') stat_card("Dtype", img_stats["dtype"]) stat_card("Min", f'{img_stats["min"]:.6f}') stat_card("Max", f'{img_stats["max"]:.6f}') stat_card("Mean", f'{img_stats["mean"]:.6f}') close_card() with col2: open_card() st.markdown("#### 🎯 HF Ground Truth") stat_card("File", selected_name) stat_card("Shape", str(gdt_stats["shape"])) stat_card("Dimensions", f'{gdt_stats["ndim"]}D') stat_card("Dtype", gdt_stats["dtype"]) stat_card("Min", f'{gdt_stats["min"]:.6f}') stat_card("Max", f'{gdt_stats["max"]:.6f}') stat_card("Mean", f'{gdt_stats["mean"]:.6f}') close_card() # --------------------------------------- # EDA Visualisation tab # --------------------------------------- elif key == "eda_viz": section_title("πŸ–ΌοΈ EDA Image Visualisation") if imgTs.ndim == 2 and gdtTs.ndim == 2: img_show = imgTs gdt_show = gdtTs elif imgTs.ndim == 3 and gdtTs.ndim == 3: max_slice = min(imgTs.shape[0], gdtTs.shape[0]) - 1 slice_idx = st.slider( "Choose slice index", min_value=0, max_value=max_slice, value=0, key="eda_slice_slider" ) img_show = get_display_slice(imgTs, slice_idx) gdt_show = get_display_slice(gdtTs, slice_idx) st.info(f"Displaying EDA slice index: {slice_idx}") else: st.error("LF and HF arrays do not have compatible dimensions for joint display.") st.stop() plot_wrapper_start() fig = plot_side_by_side( img_show, gdt_show, lf_title=f"LF: {selected_name}", hf_title=f"HF: {selected_name}" ) st.pyplot(fig) plot_wrapper_end() # --------------------------------------- # Preprocessing Visualisation tab # --------------------------------------- elif key == "prep_viz": section_title("βš™οΈ Preprocessing Visualisation") processed = st.session_state.get("preprocessed_data") processed_sample_name = st.session_state.get("preprocessed_sample_name") if processed is None: st.warning("Please click 'βš™οΈ Apply preprocessing' in the sidebar first.") st.stop() if processed_sample_name != selected_name: st.warning( "The currently displayed preprocessing result belongs to a different selected file. " "Please click 'Apply preprocessing' again for the newly selected sample." ) st.stop() num_samples = processed["num_samples"] if num_samples == 1: sample_idx = 0 st.info("This sample is 2D, so only one processed image is available.") else: sample_idx = st.slider( "Choose preprocessing sample index", min_value=0, max_value=num_samples - 1, value=0, key="prep_sample_slider" ) st.info(f"Displaying preprocessing sample index: {sample_idx}") sample_udHRkspace = processed["ud_HR_kspace"][sample_idx] sample_fsHRkspace = processed["full_HR_kspace"][sample_idx] sample_udLRkspace = processed["ud_LR_kspace"][sample_idx] sample_fsLRkspace = processed["full_LR_kspace"][sample_idx] sample_udHRimg = processed["mag_HR_images"][sample_idx] sample_fsHRimg = processed["HR_images"][sample_idx] sample_udLRimg = processed["mag_LR_images"][sample_idx] sample_fsLRimg = processed["LR_images"][sample_idx] section_title("πŸ“ Processed Sample Shapes") col1, col2 = st.columns(2) # with col1: # open_card() # st.markdown("#### 🎯 HR Outputs") # stat_card("udHRkspace", str(sample_udHRkspace.shape)) # stat_card("fsHRkspace", str(sample_fsHRkspace.shape)) # stat_card("udHRimg", str(sample_udHRimg.shape)) # stat_card("fsHRimg", str(sample_fsHRimg.shape)) # close_card() # with col2: # open_card() # st.markdown("#### πŸ–ΌοΈ LR Outputs") # stat_card("udLRkspace", str(sample_udLRkspace.shape)) # stat_card("fsLRkspace", str(sample_fsLRkspace.shape)) # stat_card("udLRimg", str(sample_udLRimg.shape)) # stat_card("fsLRimg", str(sample_fsLRimg.shape)) # close_card() section_title("🧠 HR Domain Visualisation") plot_wrapper_start() fig_hr = plot_preprocessing_hr(sample_idx, processed) st.pyplot(fig_hr) plot_wrapper_end() section_title("πŸ”Ž LR Domain Visualisation") plot_wrapper_start() fig_lr = plot_preprocessing_lr(sample_idx, processed) st.pyplot(fig_lr) plot_wrapper_end() # --------------------------------------- # Prediction Visualisation tab # --------------------------------------- elif key == "pred_viz": section_title("πŸ€– Prediction Visualisation") pred_result = st.session_state.get("prediction_result") pred_sample_name = st.session_state.get("prediction_sample_name") pred_sample_idx = st.session_state.get("prediction_sample_idx") if pred_result is None: st.warning("Please click 'πŸš€ Predict' in the sidebar first.") st.stop() if pred_sample_name != selected_name: st.warning( "The currently displayed prediction belongs to a different selected file. " "Please run preprocessing and prediction again for the newly selected sample." ) st.stop() section_title("πŸ“Š Prediction Metrics") m1, m2, m3, m4 = st.columns(4) with m1: metric_card("πŸ–ΌοΈ LR SSIM", f"{pred_result['ssimLR']:.4f}") with m2: metric_card("πŸ“‘ LR PSNR", f"{pred_result['psnrLR']:.2f} dB") with m3: metric_card("🧠 Recon SSIM", f"{pred_result['ssimRec']:.4f}") with m4: metric_card("✨ Recon PSNR", f"{pred_result['psnrRec']:.2f} dB") st.markdown( f""" <span class="badge">πŸ“„ Sample: {selected_name}</span> <span class="badge">πŸ”’ Index: {pred_sample_idx}</span> """, unsafe_allow_html=True ) plot_wrapper_start() fig_pred = plot_prediction_results(pred_result) st.pyplot(fig_pred) plot_wrapper_end() # --------------------------------------------------- # Footer # --------------------------------------------------- st.markdown("---") st.markdown( """ <div style="text-align:center; color:#64748b; font-size:0.92rem; padding-bottom: 1rem;"> 🧠 MRI Reconstruction Studio β€’ Built for interactive EDA, preprocessing, and prediction <br><br> πŸ“˜ <a href="https://www.kaggle.com/code/danieltweneboaha/kiqt-tutorial" target="_blank" style="color:#2563eb; text-decoration:none; font-weight:600;"> Visit Code Tutorial! </a> </div> """, unsafe_allow_html=True )
# # (01) EDA
# from pathlib import Path
# import numpy as np
# import pandas as pd
# import matplotlib.pyplot as plt
# import streamlit as st
# # ---------------------------------------------------
# # Page config
# # ---------------------------------------------------
# st.set_page_config(
# page_title="MRI Reconstruction - EDA",
# layout="wide"
# )
# # ---------------------------------------------------
# # Intro text (always visible)
# # ---------------------------------------------------
# st.title("MRI Reconstruction App")
# st.subheader("Interactive Exploratory Data Analysis (EDA)")
# st.write(
# "Use the sidebar to explore the available HF and LF sample pairs, "
# "inspect their dimensions, and visualise them side by side."
# )
# # ---------------------------------------------------
# # Resolve project paths
# # ---------------------------------------------------
# ROOT_DIR = Path(__file__).resolve().parent.parent
# HF_DIR = ROOT_DIR / "data" / "HF"
# LF_DIR = ROOT_DIR / "data" / "LF"
# # ---------------------------------------------------
# # Helper functions
# # ---------------------------------------------------
# @st.cache_data
# def get_paired_files(hf_dir: Path, lf_dir: Path) -> pd.DataFrame:
# hf_files = sorted([f for f in hf_dir.glob("*.npy")])
# lf_files = sorted([f for f in lf_dir.glob("*.npy")])
# hf_map = {f.name: f for f in hf_files}
# lf_map = {f.name: f for f in lf_files}
# common_names = sorted(set(hf_map.keys()) & set(lf_map.keys()))
# return pd.DataFrame({
# "sample_name": common_names,
# "gdtFiles": [str(hf_map[name]) for name in common_names],
# "imgFiles": [str(lf_map[name]) for name in common_names],
# })
# @st.cache_data
# def load_npy_file(file_path: str) -> np.ndarray:
# return np.load(file_path)
# def array_summary(arr: np.ndarray) -> dict:
# return {
# "shape": arr.shape,
# "ndim": arr.ndim,
# "dtype": str(arr.dtype),
# "min": float(np.min(arr)),
# "max": float(np.max(arr)),
# "mean": float(np.mean(arr)),
# }
# def get_display_slice(arr: np.ndarray, slice_idx: int | None = None) -> np.ndarray:
# if arr.ndim == 2:
# return arr
# if arr.ndim == 3:
# return arr[slice_idx if slice_idx is not None else 0]
# raise ValueError(f"Unsupported array shape for display: {arr.shape}")
# def plot_side_by_side(lf_img: np.ndarray, hf_img: np.ndarray, lf_title="LF Image", hf_title="HF Image"):
# fig, axes = plt.subplots(1, 2, figsize=(12, 5))
# axes[0].imshow(lf_img, cmap="gray")
# axes[0].set_title(lf_title)
# axes[0].axis("off")
# axes[1].imshow(hf_img, cmap="gray")
# axes[1].set_title(hf_title)
# axes[1].axis("off")
# plt.tight_layout()
# return fig
# # ---------------------------------------------------
# # Validate folders and load paired data
# # ---------------------------------------------------
# if not HF_DIR.exists():
# st.error(f"HF directory not found: {HF_DIR}")
# st.stop()
# if not LF_DIR.exists():
# st.error(f"LF directory not found: {LF_DIR}")