Spaces:
Sleeping
Sleeping
Upload 5 files
Browse files- app.py +86 -10
- data_preprocessing.py +17 -0
- utils.py +20 -0
app.py
CHANGED
|
@@ -6,6 +6,7 @@ import matplotlib.pyplot as plt
|
|
| 6 |
from data_preprocessing import preprocess_fmri_to_fc, process_single_fmri
|
| 7 |
from visualization import plot_fc_matrices, plot_learning_curves
|
| 8 |
import os
|
|
|
|
| 9 |
from sklearn.metrics import mean_squared_error, r2_score, accuracy_score, f1_score
|
| 10 |
import json
|
| 11 |
import pickle
|
|
@@ -363,8 +364,68 @@ class AphasiaPredictionApp:
|
|
| 363 |
# For NIfTI files, we need to search the API or download regardless of demographic source
|
| 364 |
logger.info("Searching for NIfTI files in the dataset...")
|
| 365 |
|
| 366 |
-
#
|
| 367 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 368 |
|
| 369 |
if demographic_file == "FROM_DATASET_API":
|
| 370 |
logger.info("Using dataset API for demographics rather than files")
|
|
@@ -1788,9 +1849,15 @@ def create_interface():
|
|
| 1788 |
with gr.Row():
|
| 1789 |
with gr.Column(scale=1):
|
| 1790 |
data_dir = gr.Textbox(
|
| 1791 |
-
label="Data Directory",
|
| 1792 |
value="SreekarB/OSFData"
|
| 1793 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1794 |
latent_dim = gr.Slider(
|
| 1795 |
minimum=8, maximum=64, step=8,
|
| 1796 |
label="Latent Dimensions", value=32
|
|
@@ -1880,7 +1947,7 @@ def create_interface():
|
|
| 1880 |
}
|
| 1881 |
|
| 1882 |
# Handle train button click
|
| 1883 |
-
def handle_train(data_dir, latent_dim, nepochs, bsize, use_hf_dataset,
|
| 1884 |
prediction_type, outcome_variable, skip_behavioral,
|
| 1885 |
use_synthetic_nifti, use_synthetic_fc):
|
| 1886 |
# Set prediction config values for this run
|
|
@@ -1890,6 +1957,13 @@ def create_interface():
|
|
| 1890 |
PREDICTION_CONFIG['use_synthetic_nifti'] = use_synthetic_nifti
|
| 1891 |
PREDICTION_CONFIG['use_synthetic_fc'] = use_synthetic_fc
|
| 1892 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1893 |
# Log helpful information for the user
|
| 1894 |
logger.info(f"Looking for data in directory: {data_dir}")
|
| 1895 |
logger.info(f"Expected files: FC_graph_covariate_data.csv and treatment_outcomes.csv")
|
|
@@ -1912,7 +1986,7 @@ def create_interface():
|
|
| 1912 |
|
| 1913 |
train_btn.click(
|
| 1914 |
fn=handle_train,
|
| 1915 |
-
inputs=[data_dir, latent_dim, nepochs, bsize, use_hf_dataset,
|
| 1916 |
prediction_type, outcome_variable, skip_behavioral,
|
| 1917 |
use_synthetic_nifti, use_synthetic_fc],
|
| 1918 |
outputs=[fc_plot, importance_plot, prediction_plot, learning_plot]
|
|
@@ -1927,10 +2001,10 @@ def create_interface():
|
|
| 1927 |
# Add examples
|
| 1928 |
gr.Examples(
|
| 1929 |
examples=[
|
| 1930 |
-
["SreekarB/OSFData", 32, 200, 16, True, "regression", "wab_aq", True, False, False], # Standard training without synthetic data
|
| 1931 |
-
["SreekarB/OSFData", 16, 100, 8, True, "classification", "wab_aq", True, False, False] # Faster training with classification
|
| 1932 |
],
|
| 1933 |
-
inputs=[data_dir, latent_dim, nepochs, bsize, use_hf_dataset,
|
| 1934 |
prediction_type, outcome_variable, skip_behavioral,
|
| 1935 |
use_synthetic_nifti, use_synthetic_fc],
|
| 1936 |
)
|
|
@@ -1940,9 +2014,11 @@ def create_interface():
|
|
| 1940 |
## How to use this tool
|
| 1941 |
|
| 1942 |
1. **Train Models Tab**: First train the VAE and Random Forest models using your dataset
|
| 1943 |
-
- Provide the path to your data directory
|
|
|
|
|
|
|
| 1944 |
- fMRI files (NIfTI format, *.nii or *.nii.gz)
|
| 1945 |
-
- FC_graph_covariate_data.csv (with
|
| 1946 |
- treatment_outcomes.csv (with columns: subject_id, treatment_type, outcome_score)
|
| 1947 |
- Adjust parameters like latent dimensions and training epochs
|
| 1948 |
- Choose regression or classification prediction type
|
|
|
|
| 6 |
from data_preprocessing import preprocess_fmri_to_fc, process_single_fmri
|
| 7 |
from visualization import plot_fc_matrices, plot_learning_curves
|
| 8 |
import os
|
| 9 |
+
import glob
|
| 10 |
from sklearn.metrics import mean_squared_error, r2_score, accuracy_score, f1_score
|
| 11 |
import json
|
| 12 |
import pickle
|
|
|
|
| 364 |
# For NIfTI files, we need to search the API or download regardless of demographic source
|
| 365 |
logger.info("Searching for NIfTI files in the dataset...")
|
| 366 |
|
| 367 |
+
# First check if NIfTI files exist in a local directory
|
| 368 |
+
local_nii_files = []
|
| 369 |
+
|
| 370 |
+
# Check different possible local paths, starting with user-specified directory
|
| 371 |
+
possible_paths = []
|
| 372 |
+
|
| 373 |
+
# Add user-specified directory from config if available
|
| 374 |
+
if PREDICTION_CONFIG.get('local_nii_dir'):
|
| 375 |
+
user_dir = PREDICTION_CONFIG.get('local_nii_dir')
|
| 376 |
+
if os.path.exists(user_dir):
|
| 377 |
+
possible_paths.append(user_dir)
|
| 378 |
+
logger.info(f"Checking user-specified NIfTI directory: {user_dir}")
|
| 379 |
+
|
| 380 |
+
# Add other standard paths to check
|
| 381 |
+
possible_paths.extend([
|
| 382 |
+
os.path.join(os.path.dirname(os.path.abspath(__file__)), "nii_files"),
|
| 383 |
+
os.path.join(os.path.dirname(os.path.abspath(__file__)), "nifti"),
|
| 384 |
+
os.path.join(os.path.dirname(os.path.abspath(__file__)), "fmri"),
|
| 385 |
+
os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "nii_files"),
|
| 386 |
+
os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "nifti"),
|
| 387 |
+
"/tmp/nii_files" # In case files were manually placed here
|
| 388 |
+
])
|
| 389 |
+
|
| 390 |
+
for path in possible_paths:
|
| 391 |
+
if os.path.exists(path):
|
| 392 |
+
# Check for .nii or .nii.gz files
|
| 393 |
+
nii_files_here = []
|
| 394 |
+
nii_files_here.extend(glob.glob(os.path.join(path, "*.nii")))
|
| 395 |
+
nii_files_here.extend(glob.glob(os.path.join(path, "*.nii.gz")))
|
| 396 |
+
|
| 397 |
+
if nii_files_here:
|
| 398 |
+
local_nii_files.extend(nii_files_here)
|
| 399 |
+
logger.info(f"Found {len(nii_files_here)} local NIfTI files in {path}")
|
| 400 |
+
|
| 401 |
+
if local_nii_files:
|
| 402 |
+
logger.info(f"Using {len(local_nii_files)} local NIfTI files instead of searching HuggingFace dataset")
|
| 403 |
+
|
| 404 |
+
# Log filenames to help with debugging
|
| 405 |
+
for i, nii_file in enumerate(local_nii_files[:5]): # Log first 5 files
|
| 406 |
+
logger.info(f"Local NIfTI file {i+1}: {os.path.basename(nii_file)}")
|
| 407 |
+
|
| 408 |
+
if len(local_nii_files) > 5:
|
| 409 |
+
logger.info(f"... and {len(local_nii_files) - 5} more files")
|
| 410 |
+
|
| 411 |
+
nii_files = local_nii_files
|
| 412 |
+
else:
|
| 413 |
+
# If no local files found, find NIfTI files using our comprehensive search function
|
| 414 |
+
logger.info("No local NIfTI files found. Searching in the HuggingFace dataset...")
|
| 415 |
+
nii_files = find_nifti_files_in_hf_dataset(data_dir, dataset)
|
| 416 |
+
|
| 417 |
+
# Log what was found
|
| 418 |
+
if nii_files:
|
| 419 |
+
logger.info(f"Found {len(nii_files)} NIfTI files in the dataset")
|
| 420 |
+
|
| 421 |
+
# Log filenames to help with debugging
|
| 422 |
+
for i, nii_file in enumerate(nii_files[:5]): # Log first 5 files
|
| 423 |
+
logger.info(f"NIfTI file {i+1}: {os.path.basename(nii_file)}")
|
| 424 |
+
|
| 425 |
+
if len(nii_files) > 5:
|
| 426 |
+
logger.info(f"... and {len(nii_files) - 5} more files")
|
| 427 |
+
else:
|
| 428 |
+
logger.warning("No NIfTI files found in the dataset. This will likely cause an error later.")
|
| 429 |
|
| 430 |
if demographic_file == "FROM_DATASET_API":
|
| 431 |
logger.info("Using dataset API for demographics rather than files")
|
|
|
|
| 1849 |
with gr.Row():
|
| 1850 |
with gr.Column(scale=1):
|
| 1851 |
data_dir = gr.Textbox(
|
| 1852 |
+
label="Data Directory or HuggingFace Dataset ID",
|
| 1853 |
value="SreekarB/OSFData"
|
| 1854 |
)
|
| 1855 |
+
local_nii_dir = gr.Textbox(
|
| 1856 |
+
label="Local NIfTI Files Directory (Optional)",
|
| 1857 |
+
value="",
|
| 1858 |
+
placeholder="/path/to/nii_files",
|
| 1859 |
+
info="If provided, NIfTI files from this directory will be used instead of searching the dataset"
|
| 1860 |
+
)
|
| 1861 |
latent_dim = gr.Slider(
|
| 1862 |
minimum=8, maximum=64, step=8,
|
| 1863 |
label="Latent Dimensions", value=32
|
|
|
|
| 1947 |
}
|
| 1948 |
|
| 1949 |
# Handle train button click
|
| 1950 |
+
def handle_train(data_dir, local_nii_dir, latent_dim, nepochs, bsize, use_hf_dataset,
|
| 1951 |
prediction_type, outcome_variable, skip_behavioral,
|
| 1952 |
use_synthetic_nifti, use_synthetic_fc):
|
| 1953 |
# Set prediction config values for this run
|
|
|
|
| 1957 |
PREDICTION_CONFIG['use_synthetic_nifti'] = use_synthetic_nifti
|
| 1958 |
PREDICTION_CONFIG['use_synthetic_fc'] = use_synthetic_fc
|
| 1959 |
|
| 1960 |
+
# Store the local NIfTI directory if provided
|
| 1961 |
+
if local_nii_dir and os.path.exists(local_nii_dir):
|
| 1962 |
+
PREDICTION_CONFIG['local_nii_dir'] = local_nii_dir
|
| 1963 |
+
logger.info(f"Using local NIfTI directory: {local_nii_dir}")
|
| 1964 |
+
else:
|
| 1965 |
+
PREDICTION_CONFIG['local_nii_dir'] = None
|
| 1966 |
+
|
| 1967 |
# Log helpful information for the user
|
| 1968 |
logger.info(f"Looking for data in directory: {data_dir}")
|
| 1969 |
logger.info(f"Expected files: FC_graph_covariate_data.csv and treatment_outcomes.csv")
|
|
|
|
| 1986 |
|
| 1987 |
train_btn.click(
|
| 1988 |
fn=handle_train,
|
| 1989 |
+
inputs=[data_dir, local_nii_dir, latent_dim, nepochs, bsize, use_hf_dataset,
|
| 1990 |
prediction_type, outcome_variable, skip_behavioral,
|
| 1991 |
use_synthetic_nifti, use_synthetic_fc],
|
| 1992 |
outputs=[fc_plot, importance_plot, prediction_plot, learning_plot]
|
|
|
|
| 2001 |
# Add examples
|
| 2002 |
gr.Examples(
|
| 2003 |
examples=[
|
| 2004 |
+
["SreekarB/OSFData", "", 32, 200, 16, True, "regression", "wab_aq", True, False, False], # Standard training without synthetic data
|
| 2005 |
+
["SreekarB/OSFData", "", 16, 100, 8, True, "classification", "wab_aq", True, False, False] # Faster training with classification
|
| 2006 |
],
|
| 2007 |
+
inputs=[data_dir, local_nii_dir, latent_dim, nepochs, bsize, use_hf_dataset,
|
| 2008 |
prediction_type, outcome_variable, skip_behavioral,
|
| 2009 |
use_synthetic_nifti, use_synthetic_fc],
|
| 2010 |
)
|
|
|
|
| 2014 |
## How to use this tool
|
| 2015 |
|
| 2016 |
1. **Train Models Tab**: First train the VAE and Random Forest models using your dataset
|
| 2017 |
+
- Provide the path to your data directory or HuggingFace dataset ID (e.g., "SreekarB/OSFData")
|
| 2018 |
+
- You can optionally specify a local directory containing NIfTI files (.nii or .nii.gz format)
|
| 2019 |
+
- The system needs:
|
| 2020 |
- fMRI files (NIfTI format, *.nii or *.nii.gz)
|
| 2021 |
+
- FC_graph_covariate_data.csv (with columns: ID, wab_aq, age, mpo, education, gender, handedness)
|
| 2022 |
- treatment_outcomes.csv (with columns: subject_id, treatment_type, outcome_score)
|
| 2023 |
- Adjust parameters like latent dimensions and training epochs
|
| 2024 |
- Choose regression or classification prediction type
|
data_preprocessing.py
CHANGED
|
@@ -341,4 +341,21 @@ def load_and_preprocess_data(data_dir, demographic_file, use_hf_dataset=False,
|
|
| 341 |
# Process fMRI files to FC matrices
|
| 342 |
X, demo_data, demo_types = preprocess_fmri_to_fc(nii_files, demo_data, demo_types)
|
| 343 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 344 |
return X, demo_data, demo_types
|
|
|
|
| 341 |
# Process fMRI files to FC matrices
|
| 342 |
X, demo_data, demo_types = preprocess_fmri_to_fc(nii_files, demo_data, demo_types)
|
| 343 |
|
| 344 |
+
# Check for sample size consistency and fix if needed
|
| 345 |
+
print(f"After preprocessing: X shape: {X.shape}, demo_data lengths: {[len(d) for d in demo_data]}")
|
| 346 |
+
|
| 347 |
+
# Make sure all sample sizes match
|
| 348 |
+
if X.shape[0] != len(demo_data[0]):
|
| 349 |
+
print(f"WARNING: Sample size mismatch detected! X: {X.shape[0]}, demo: {len(demo_data[0])}")
|
| 350 |
+
|
| 351 |
+
# Determine the smaller size
|
| 352 |
+
min_samples = min(X.shape[0], len(demo_data[0]))
|
| 353 |
+
print(f"Adjusting to {min_samples} samples")
|
| 354 |
+
|
| 355 |
+
# Trim X and demographic data to match
|
| 356 |
+
X = X[:min_samples]
|
| 357 |
+
demo_data = [d[:min_samples] for d in demo_data]
|
| 358 |
+
|
| 359 |
+
print(f"After adjustment: X shape: {X.shape}, demo_data lengths: {[len(d) for d in demo_data]}")
|
| 360 |
+
|
| 361 |
return X, demo_data, demo_types
|
utils.py
CHANGED
|
@@ -70,6 +70,26 @@ def train_vae(vae, x, demo, demo_types, nepochs, pperiod, bsize,
|
|
| 70 |
train_losses = []
|
| 71 |
val_losses = []
|
| 72 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
for i, d, t in zip(range(len(demo)), demo, demo_types):
|
| 74 |
print(f'Fitting auxiliary guidance model for demographic {i} {t}...', end='')
|
| 75 |
if t == 'continuous':
|
|
|
|
| 70 |
train_losses = []
|
| 71 |
val_losses = []
|
| 72 |
|
| 73 |
+
# Check if sample sizes are consistent
|
| 74 |
+
n_samples = x.shape[0]
|
| 75 |
+
print(f"Sample sizes - X: {n_samples}, Demographics: {[len(d) for d in demo]}")
|
| 76 |
+
|
| 77 |
+
# Ensure all sample sizes match
|
| 78 |
+
if any(len(d) != n_samples for d in demo):
|
| 79 |
+
print("WARNING: Sample size mismatch detected! Fixing...")
|
| 80 |
+
|
| 81 |
+
# Trim to smallest size
|
| 82 |
+
min_samples = min(n_samples, *[len(d) for d in demo])
|
| 83 |
+
print(f"Adjusting to {min_samples} samples")
|
| 84 |
+
|
| 85 |
+
# Adjust x and demo
|
| 86 |
+
x = x[:min_samples]
|
| 87 |
+
demo = [d[:min_samples] for d in demo]
|
| 88 |
+
|
| 89 |
+
print(f"After adjustment - X: {x.shape[0]}, Demographics: {[len(d) for d in demo]}")
|
| 90 |
+
|
| 91 |
+
print(f"Using {x.shape[0]} samples for training")
|
| 92 |
+
|
| 93 |
for i, d, t in zip(range(len(demo)), demo, demo_types):
|
| 94 |
print(f'Fitting auxiliary guidance model for demographic {i} {t}...', end='')
|
| 95 |
if t == 'continuous':
|