Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add new CLI script to compute normalized metric ratios (MSCC, etc.) for compressed levels #4003

Merged
merged 224 commits into from Jul 11, 2023

Conversation

sandrinebedard
Copy link
Member

@sandrinebedard sandrinebedard commented Jan 19, 2023

Checklist

GitHub

PR contents

Description

This issue is related to #3733. It computes normalized metrics ratio (MSCC and others) using a reference dataset of healthy subject in the PAM50 anatomical space. It calls sct_process_segmentation to generate the spinal cord morphometrics perslice in the native space and in the PAM50 anatomical dimensions (if -normalize 1) to compute the metric ratio.

It relies on 3 inputs:

  • A label file identifying compression sites.
  • Spinal cord segmentation
  • Vertebral labels

How to test

  1. Prepare the development environment by running:

    cd $SCT_DIR
    git checkout sb/3733-bring-metrics-to-pam50-add_mscc 
    git pull
    ./install_sct
  2. Download the reference dataset of healthy controls to $SCT_DIR/data/ by running:

    sct_download_data -d PAM50_normalized_metrics
    
  3. Generate the 3 necessary input files from this subject file: sub-twh018_T2w.nii.gz

    1. Compression labels (sub-twh018_T2w_compression_labels.nii.gz)
    2. Spinal cord segmentation
    3. Vertebral labels
    # NB: These steps approximate what a tutorial would look like for using this function.
    
    # Identify compression sites using labels
    # NB: These steps are a workaround since -create-viewer can't create multiple labels with the same value 
    #     See also: https://github.com/spinalcordtoolbox/spinalcordtoolbox/issues/3984
    sct_label_utils -create-viewer 1 -i sub-twh018_T2w.nii.gz -o labels1.nii.gz
    sct_label_utils -create-viewer 1 -i sub-twh018_T2w.nii.gz -o labels2.nii.gz
    sct_label_utils -create-viewer 1 -i sub-twh018_T2w.nii.gz -o labels3.nii.gz
    sct_maths -i labels1.nii.gz -add labels2.nii.gz labels3.nii.gz -o sub-twh018_T2w_compression_labels.nii.gz
    
    # Generate spinal cord segmentation
    sct_deepseg_sc -i sub-twh018_T2w.nii.gz -c t2
    # NB: Some manual corrections were performed on the segmentation afterwards,
    #     due to the presence of spinal cord compression.
    
    # Get verterbral labeling
    sct_label_vertebrae -i sub-twh018_T2w.nii.gz -s sub-twh018_T2w_seg.nii.gz -c t2
    

    (Alternatively, you can just download the 3 generated files directly here :
    sub-twh018_T2w_testing_data.zip

  4. Run the following example commands:
    Compute ratio of (diameter ap):

    sct_compute_compression -i sub-twh018_T2w_seg.nii.gz -l sub-twh018_T2w_compression_labels.nii.gz -vertfile sub-twh018_T2w_seg_labeled.nii.gz -normalize 1 -o test_mscc.csv
    

    Compute ratio of area (CSA):

    sct_compute_compression -i sub-twh018_T2w_seg.nii.gz -l sub-twh018_T2w_compression_labels.nii.gz  -vertfile sub-twh018_T2w_seg_labeled.nii.gz -metric area -normalize 1 -o test_csa.csv
    

    Test specifying sex and age range

    sct_compute_compression -i sub-twh018_T2w_seg.nii.gz -l sub-twh018_T2w_compression_labels.nii.gz  -vertfile sub-twh018_T2w_seg_labeled.nii.gz  -normalize 1 -o test_mscc_age_sex.csv -sex F -age 35 60
    

    Test without normalization

    sct_compute_compression -i sub-twh018_T2w_seg.nii.gz -l sub-twh018_T2w_compression_labels.nii.gz  -vertfile sub-twh018_T2w_seg_labeled.nii.gz  -normalize 0 -o test_mscc_no_norm.csv
    

What is left

  • Remove default value for normalize
  • Adapt for multiples labeled slices for one compression
  • Add in documentation & tutorial

Linked issues

Fixes #3733.

@sandrinebedard sandrinebedard added the feature category: new functionality label Jan 19, 2023
@sandrinebedard sandrinebedard self-assigned this Jan 19, 2023
@sandrinebedard sandrinebedard marked this pull request as draft January 19, 2023 21:19
valosekj and others added 11 commits June 19, 2023 12:34
Distinguishing between the PAM50 z_range and the centerline z_range will help to make further refactors clearer.
This dict is necessary to properly compute the non-normalized `diameter_AP_ratio` quantity.
The first computed ratio (`{metric}_ratio`) should be consistent, regardless of whether `normalize_hc` is specified.
Before, this quantity would overlap with the `diameter_AP_ratio` key. Now, it is its own separate quantity.
This now matches the pattern suggested by Jan. :)

Co-authored-by: Jan Valosek <39456460+valosekj@users.noreply.github.com>
This now better matches the order of the steps inside the loop, too.
@joshuacwnewton joshuacwnewton changed the title Morphometric normalization sct_compute_compression Add new CLI script to compute normalized metric ratios (MSCC, etc.) for compressed levels Jun 29, 2023
This now ACTUALLY matches the pattern suggested by Jan. :)

Co-authored-by: Jan Valosek <39456460+valosekj@users.noreply.github.com>
@joshuacwnewton joshuacwnewton merged commit 65ff7f0 into master Jul 11, 2023
24 checks passed
@joshuacwnewton joshuacwnewton deleted the sb/3733-bring-metrics-to-pam50-add_mscc branch July 11, 2023 16:23
@joshuacwnewton
Copy link
Member

Thank you so much @sandrinebedard and @valosekj for this massive effort! ♥️

@valosekj
Copy link
Member

@joshuacwnewton thank you for your detailed review and help! 💯

valosekj added a commit to sct-pipeline/dcm-metric-normalization that referenced this pull request Aug 16, 2023
valosekj added a commit to sct-pipeline/dcm-metric-normalization that referenced this pull request Aug 24, 2023
valosekj added a commit to sct-pipeline/dcm-metric-normalization that referenced this pull request Mar 26, 2024
* initial commit database

* get the max compression

* add mjoa correlation graphs and mean±std

* add logistic reg

* add ratio for categorical data and add r coeff on mscc graphs

* add ratio norm vs no norm graphs

* Update requirements.txt

* Rename metrics to METRICS and metrics_norm to METRICS_NORM to indicate that they are global variables

* Improve insertion of text with corr coef and pval

* Add function docstrings

* Improve output figure filenames

* Fix typos and small formatting issues

* add kfold cross-validation

* fix name

* compute z scores

* add ratio of levels groupby therapeutic decision

* change for repeated k fold and add composite z scores

* add VIF

* add logistic for composite z score

* Move code for the prediction of therapeutic_decision into a separate function

* Add functions to predict mJOA after 6m and 12m

* Expand regression functions to allow to compute either logistic or linear regression

* Add function to compare mJOA change between subjects with therapeutic_decision == 0 and subjects with therapeutic_decision == 1

* OS compatibility formatting fixes

* Add TODO

* Remove code which have been moved under predict_theurapeutic_decision function

* Fix variable name

* Remove plot.show

* Create sns.regplot between sex and weight

* Improve script description, help and args help

* add 95% CI for ROC curves

* Remove 'id' since it is probably not necessary?

* Add missing space

* Add TODO - read table with electrophysiology, anatomical and motion data

* Small fixes

* read electrophysiological data

* load electrophysiological data

* Make 'electro_file' non-required arg

* Read also ASIA/GRASSP subscores

* Update predict_theurapeutic_decision function docstring

* Print Candidate predictors

* Remove spaces

* Print where ROC curves are saved

* Read also mJOA subscores

- motor_dysfunction_UE_bl
- motor_dysfunction_LE_bl
- sensory_dysfunction_LE_bl
- sphincter_dysfunction_bl

* Print only 2 Candidate predictors perline

* Plot and save correlation matrix for mJOA, mJOA subscores, and ASIA/GRASSP

* Create read_clinical_file function to read clinical file

* Move correlation plotting into a separate function

* Simplify columns renaming in read_clinical_file function

* Add plt.close()

* Update input args description; make '-electro-file' required again

* Add read_electrophysiology_and_anatomical_file function to read electrophysiology and anatomical data

* Read separately anatomical_df and electrophysiology_df dataframes

* Rename df_combined to df_morphometrics to improve code readability

* Plot and save correlation matrix for anatomical (aSCOR and aMSCC) and morphometric metrics

* Small code improvments

* Drop columns with more than 25% nan values for correlation analysis

* Add per level correlations for anatomical (aSCOR and aMSCC) and morphometric metrics

* Read also motion data

* Plot and save correlation matrix for motion data

* Update docstring and prints

* Keep two levels for aSCOR and aMSCC correlations

* Create regplot for anatomical (aSCOR and aMSCC) and morphometric metrics

* Add loop across metrics to create_regplot_anatomical_and_morphometric_metrics function

* add function to merge df for reg

* Improve figure titles

* Drop 6m and 12m anatomical metrics. Because we have only baseline values for our morphometric metrics

* Drop 6m and 12m anatomical metrics. Because we have only baseline values for our morphometric metrics

* Insert text box with correlation coefficient to regplots

* Put number of subjects into title of all correlations plots. Drop subjects with nan for clinical scores corr matrix.

* Add textbox with correlation coefficient and p-value

* Merge all dataframes for prediction

* fix change mjoa for total mjoa and lenght of y

* add motion data to dataframe

* Update function for plotting of correlation matrix and pairplot for anatomical (aSCOR and aMSCC) and morphometric metrics

* Rename electrophysiology_and_anatomical_df to df_all

* Read also electrophysiology data; rename function to read_electrophysiology_anatomical_and_motion_file

* Set index to participant_id' right in read_electrophysiology_anatomical_and_motion_file function

* Move nan dropping into the relevant functions

* Remove create_regplot_anatomical_and_morphometric_metrics function -- it is no longer relevant and was replaced by compute_correlations_anatomical_and_morphometric_metrics

* Docstring update

* Move nan dropping for weight and height to the relevant function

* Improve comments, remove unused code

* Use final_df for compute_correlations_motion_and_morphometric_metrics function

* Introduce generate_correlation_matrix function to simplify the code

* Introduce generate_pairplot function to simplify the code

* Generate pairplot also for motion and clinical data

* Add print to generate_pairplot function

* Fix formatting

* Implement read_metric_file() function to read CSV file with computed metrics

* Compare read_metric_file() with read_MSCC()

* Remove debug code printing repeated indices

* Finalize read_metric_file() function to keep only levels with max compression

* Add comments

* Add TODO that name dict_exclude_subj is confusing -- it's not a dict, it's a list

* Fix typo

* Update merge_anatomical_morphological_final_for_pred() function to be compatible with  read_metric_file()

* Remove read_MSCC() function and relevant ifolder input arg

* Update '-input-file' input arg

* Rename metric names to be compatible with updated names

- for details see spinalcordtoolbox/spinalcordtoolbox#4003 (comment)

* update names

* update names saved now

* add a todo to update

* fix columns drop with new naming

* Move SmartFormatter class to utils.py

* Move SmartFormatter class to utils.py

* Remove unused csv2dataFrame function

* Move read_metric_file and fetch_participant_id functions to utils.py

* Move read_participants_file function to utils.py

* Move read_clinical_file function to utils.py

* Move read_electrophysiology_anatomical_and_motion_file function to utils.py

* Remove unused print

* Move format_pvalue function to utils.py

* Move compute_spearmans function to utils.py

* Create utils folder. Move utils.py into the util folder. Create utils/read_files.py. Move relevant functions from utils.py to utils/read_files.py

* Move plotting functions under utils/generate_figures.py. Add logger as input arg to the plotting functions.

* Move fit_reg function to utils.py

* Remove unused import

* Remove spaces and empty lines

* Move plot_correlation_for_clinical_scores function under generate_figures.py

* Move compute_correlations_motion_and_morphometric_metrics function under generate_figures.py and rename it to plot_correlations_motion_and_morphometric_metrics

* Pass logger to plot_correlation_for_clinical_scores

* Move compute_correlations_anatomical_and_morphometric_metrics function to generate_figures.py and rename it to plot_correlations_anatomical_and_morphometric_metrics

* Remove unused imports

* Move merge_anatomical_morphological_final_for_pred function to read_files.py

* Fix import from utils.py

* add logger as arg

* Split read_electrophysiology_anatomical_and_motion_file function into read_electrophysiology_file, read_anatomical_file, and read_motion_file functions to make the scripts compatible with XLSX files under phenotype folder

* rmeove 2 variables to create model

* add grid and comments

* Allow to read motion_data_maximum_stenosis.xlsx with motion data from the maximum stenosis level

* fix stepwise backward

* last fixes

---------

Co-authored-by: sandrinebedard <sandrine.bedard@polymtl.ca>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature category: new functionality sct_compute_compression context:
Projects
None yet
5 participants