DMRIFiberProfile

dmrifiberprofile is a tool that analyzes fiber tracts based on DTI volumes or scalar images.

_images/fiberprofile_ui.png

GUI Mode

DTIPlaygroundLab (Web UI)

Run:

$ dmriplaygroundlab

Then go to the DMRIFiberProfile menu. In the INPUT tab, enter the file path to the input datasheet containing the paths to the images to be analyzed. You can click the paper clip icon to browse for the file in a GUI. Do the same for selecting the output directory.

Next, click on the PROTOCOL tab to define the pipeline. For tract profile extraction, double-click the EXTRACT_Profile module to add it to the pipeline.

_images/extract_profile_ui.png

Fill in the fields in the EXTRACT_Profile module protocol. You must provide a comma-separated list of VTK files to profile. If an atlas directory is provided, these file paths may be relative (e.g., tract1.vtk). If no atlas directory is provided, the file paths must be absolute (e.g., /proj/NIRAL/users/alecj/fibers/tract1.vtk).

Check the box for “Input is DTI” if the input images are DTI volumes. If the input images are scalar images, uncheck this box. The program will search for scalar images corresponding to the scalar properties you want to profile.

The “Properties to Column Header Map” allows you to map parameters to the column headers in your input datasheet. Default column headers are provided, but they may not match your CSV. If they don’t, you can edit the “Column Header” field. For example, if your case IDs are in a column called “Subject ID,” you should enter this in the “Column Header” field for the “Case ID” parameter.

Once you’ve entered the requisite fields, you can click the GENERATE PROTOCOLS button to generate the protocol file. This file will be saved in the output directory you specified in the INPUT tab.

Finally, click the EXECUTE button to run the pipeline. Alternatively, you can copy the command and run it directly in the terminal.:

$ dmrifiberprofile run -i INPUT_DATASHEET -p OUTPUT_DIR/protocols.yml

CLI Mode (Linux/Windows-WSL)

For Windows users, install WSL2 and linux packages with python 3.11 or newer (3.11 recommended).

1. init - Initialize configuration (Default: $HOME/.niral-dti/dmrifiberprofile-<version>)

init command generates the configuration directory and files with following command. One just needs to execute this command only once unless a different configuration is needed. If you want to reset the initial configuration directory, you can run init again.:

$ dmrifiberprofile init

If you want to set different config directory other than default one:

$ dmrifiberprofile --config-dir my/config/dir init

Once run, config.yml and environment.yml will be in the directory.

You can manually specify the tool directory (which is generated by install-tools command) by –tools-dir option.:

$ dmrifiberprofile init --tools-dir <path/to/tool_dir>

2. update - Update if config.yml has been changed (e.g. in case of adding user module directory).

Changing config.yml file should be followed by updating environment.yml with running update command

$ dmrifiberprofile [--config-dir my/config/dir] update

This will update module-specific informations such as binary locations or package location used by the corresponding module. It simply updates environment.yml

3. make-protocols - Generating a default protocol file

The first thing to do is generate the default protocol file that has pipeline information:

$ dmrifiberprofile [base options] make-protocols -i INPUT_DATASHEET  [-o OUTPUT_DIRECTORY] [-d MODULE1 MODULE2 ... ]

if -o option is omitted, the output protocol will be printed on terminal.`-d` option specifies the list of modules for the analysis, with which command will generate the default pipeline and protocols of the sequence. Same module can be used redundantly. If -d option is not specified, the default pipeline will be generated from the file protocol_template.yml . You can change the default pipeline in protocol_template.yml file.

By default, the only module that will run is EXTRACT_Profile which extracts the profile of the fiber tracts provided.

Modifying the default protocol

If using the EXTRACT_Profile module, the default protocol file has two fields that define the tracts, null by default.

  1. atlas - The directory containing the tracts to be profiled. Must be provided as an absolute path (or with run –atlas).

  2. tracts - The list of tracts to be profiled. Must be provided as a comma-separated list of file names (spaces don’t matter), including the .vtk extension. These file names will be concatenated with the path specified by atlas to form the full path to the tracts. If empty, all the tracts (.vtk) of the atlas directory are profiled.

Optionally, you can also leave the atlas field blank and provide a list of absolute file paths in the tracts field.

If you try to use this protocol without providing an atlas or tracts, you will receive an error message.

Anatomy of EXTRACT_Profile protocol

Below are the options contained in the EXTRACT_Profile protocol.

protocol:
    atlas:
        type: directory
        default_value: null
        description: Directory containing a set of fiber tracts in the atlas to be analyzed.

    tracts:
        type: string
        default_value: null
        description: Selected set of tracts to use. Comma-delimited list of file names with .vtk extension included. Each entry must uniquely map to a VTK fiber file in the atlas location.

    inputIsDTI:
        type: boolean
        default_value: true
        description: Specifies whether the input image is a DTI, and properties are derived from it.

    propertiesToProfile:
        type: list
        default_value: FA, MD, RD, AD
        description: List of selected properties to profile along tracts.

    useDisplacementField:
        type: boolean
        default_value: true
        description: Determines whether to convert the image to atlas space using a displacement field. If set to false, the image will not be transformed to atlas space.

    parameterToColumnHeaderMap:
        type: dictionary
        default_value: null
        description: Optional map of parameters (e.g., scalar names, case id) to column headers to use for each property to profile.

    resultCaseColumnwise:
        type: boolean
        default_value: true
        description: Specifies whether to store cases as columns instead of rows in the output CSV.

    planeOfOrigin:
        type: string
        candidates:
            - value: Median
              description: Origin of profile will be median of tract.
            - value: CoG
              description: Origin of profile will be center of gravity.
        default_value: Median
        description: Determines the plane that sets the origin of the profile arc length.

    stepSize:
        type: integer
        default_value: 1
        description: Specifies how far along the tract to step for each new fiber profile location.

    supportBandwidth:
        type: float
        default_value: 3
        description: Standard deviation (mm) of the Gaussian kernel; points within this distance of a sample are averaged.

    noNaN:
        type: boolean
        default_value: false
        description: Specifies whether to remove fibers with NaN values, used both for FiberPostProcess and DTITractStat.

    mask:
        type: file
        default_value: null
        description: Optional mask file to use during profile extraction. The mask has to be defined in atlas space.

Here’s an example of what the EXTRACT_Profile protocol might look like with the atlas and tracts fields filled in:

protocol:
  atlas: /proj/NIRAL/users/alecjn/test_scripts/DTIPlayground-Tests/tests/input/fiberprofile/atlas
  inputIsDTI: true
  mask: null
  noNaN: false
  parameterToColumnHeaderMap:
    FA: FA for original
    Original DTI Image: Original DTI
  planeOfOrigin: Median
  propertiesToProfile: FA, MD
  resultCaseColumnwise: true
  stepSize: 1
  supportBandwidth: 3
  tracts: Arc_L_FrontoParietal-2_extracted_done.vtk, Corpus_Callosum-2_extracted_done.vtk
  useDisplacementField: true

4. run - Run pipeline

To run with existing protocol file:

$ dmrifiberprofile run -i INPUT_DATASHEET -p PROTOCOL_FILE -o OUTPUT_DIR

PROTOCOL_FILE is the file generated by make-protocols command and appropriately populated with the necessary information.

Instead of a datasheet, -i can be a folder: the files of every scan below it are detected (grouped by case id, the part of the file names before _dwi) and written to OUTPUT_DIR/datasheet_detected.csv, and the column map of the protocol is set to match:

$ dmrifiberprofile run -i DATA_FOLDER -p PROTOCOL_FILE -o OUTPUT_DIR

With useDisplacementField: true (native space) each scan needs its tensor (<id>_dwi[_QCed]_tensor.nrrd or <id>_dwi[_QCed]_DTI.nrrd) and displacement field (…_GlobalDisplacementField.nrrd or …_DTI_DisplacementField.nrrd); with false (atlas space) its registered tensor (…_DeformedDTI.nrrd or …_DTI_Registered.nrrd). The maps of the other properties (e.g. …_NODDI_NDI.nii.gz, …_Registered_NDI.nii.gz) are optional. The run stops with an error listing the known file names if no scan matches. A scan registered more than once (two runs of DTI_Register in two folders, say) has two displacement fields or registered tensors and is left out; –registration-folder NAME (a folder name or a pattern such as DTI_Reg*, as for qc-registration) takes the registration outputs – the displacement field in native space, every image in atlas space – only from below the folders of that name. To check the detected datasheet first:

$ dmrifiberprofile make-datasheet DATA_FOLDER -p PROTOCOL_FILE -o datasheet.csv

Without a protocol file, the defaults of EXTRACT_Profile are used; –atlas sets the atlas folder, and without tracts all the tracts (.vtk) of the atlas folder are profiled:

$ dmrifiberprofile run -i DATA_FOLDER --atlas ATLAS_FIBERS_FOLDER -o OUTPUT_DIR

A later run into the same output folder (e.g. after an interruption, or with added scans) reuses the profiles that are unchanged – same input images (path, size, modification time), tract and settings – and only computes the others. When a scan is done, all its profiles are stored with their settings in one file, subject_profiles/<scan id>.npz, so a later run reads one file per scan. A scan without it (an interrupted scan, or an output of a version before 0.8.20) reuses its .fvp files, if kept (cleanup: noCleanup) next to the settings and input files they were computed from (<profile>.json). duringProcessing (the default since 0.8.20) removes each .fvp file once written and endOfProcessing at the end; both keep subject_profiles. overwrite recomputes everything.

Analysis and QC of the profiles

Besides running the EXTRACT_Profile pipeline (dmrifiberprofile run), dmrifiberprofile provides the tools that analyse and QC the profiles, ported from the FiberProfileAnalysis scripts. dmrifiberprofile <command> --help lists all the options of each.

flip-tensor

Reflect the tensor frame of a DTI NRRD along axes, for tensors whose components don’t match the frame of their header; --voxel-frame rotates components stored in the frame of the voxel axes.

detect-tensor-flip

Find the correction of the tensor frame that orients a DTI correctly, by the coherence of the principal directions along the tracts and, with --reference, their agreement with an atlas tensor. With a reference it also measures the rotation of the frame left after the best correction, and warns when it is larger than 5 degrees and removing it lowers the mean angle to the reference by more than 1 degree: no flip corrects such a rotation, DTI_Register tensorFlip: rotation does. The input has to be registered to the reference, or --transform gives the affine from the reference to the input (e.g. initialAffine.txt of DTI_Register): otherwise the head position would be taken for a rotation of the frame, and the command stops when the FA of the input and of the reference don’t correlate at the same positions.

parametrize-fibers

Resample fiber tracts on the arc length grid and store the arc lengths in the fibers, so that the atlas defines them once; replaces dtitractstat -f.

compute-axis

1D axis of the tracts (the average curve per arc length bin), used by impute-profiles.

gather

Collect the profiles of several runs into one table per tract and metric, <tract>/<tract>_<metric>.csv (rows: arc length, columns: the scans).

impute-profiles

Impute the missing values of profile tables (e.g. the cleaned profiles of qc-profiles) from the observed values of the same scan, using the 3-D positions of the tract axes: linear along the profile, linear or nearest neighbours in 3-D, or a SIREN per scan, on the deviations from a norm and a population model of a normative cohort, or a graph U-Net (after CONFETTI); several cohorts can be pooled with a batch correction. --validate compares them on hidden values. See Imputing the profiles.

qc-registration

QC of the registration of the subjects to the atlas: similarity of the deformed metric maps, angular error, CSF check and an age conditional normative model, with a combined outlier flag. --build-normative builds that model from a reference cohort, including the mean tensor of each age bin that DTI_Register can register to. The tensor frame of every subject is checked against the atlas: another flip correction that fits better (TENSOR_frame_best, TENSOR_frame_gain_deg) and the rotation left after the applied correction (TENSOR_frame_residual_deg, with a warning as detect-tensor-flip); the mean directions of the normative model are checked the same way. --batch-correct and --batch-column correct for sites and scanners (Batches: sites and scanners). The registered maps are found below --data-dir (sub-*/ses-*/AtlasReg/*_Deformed<METRIC>.nii.gz, or the DTI_Register outputs <scan>_Registered_<METRIC>.nii.gz / <scan>_DTI_Registered.nrrd in any subfolder). When a session holds several registrations (two runs of DTI_Register, say), --registration-folder NAME (a folder name or a pattern such as DTI_Reg*) reads only the outputs below the folders of that name; without it, the outputs of the same scan are one entry and the path that sorts first wins, with a warning. dmrifiberprofile run -i DATA_FOLDER and make-datasheet have the same option.

qc-profiles

Age binned statistics of the profiles (<tract>/<tract>_<metric>_agebinstats.csv) and their plots, and the QC of the profiles against prior (normative) statistics, which flags the profiles whose values leave the normative envelope or whose shape doesn’t follow it. Diffusivities above that of free water (failed fits) are dropped as single values (Diffusivities out of range).

A typical sequence, from the parametrized atlas fibers to the cleaned profiles:

$ dmrifiberprofile parametrize-fibers Atlas/FibersRaw -o Atlas/FibersParam
$ dmrifiberprofile gather --profiles-dir Output_Profiles --fibers-dir Atlas/FibersParam --out-dir Profiles
$ dmrifiberprofile compute-axis Atlas/FibersParam -o FiberAxis
$ dmrifiberprofile qc-registration --data-dir Data --atlas-dir Atlas --normative-dir Atlas/normativeModel --out-dir RegistrationQC
$ dmrifiberprofile qc-profiles --profiles-dir Profiles --prior-stats-dir Atlas/normProfiles --registration-qc RegistrationQC --clean-dir Profiles_Clean -o ProfileQC
$ dmrifiberprofile impute-profiles --profiles-dir ProfileQC/Profiles_Clean --axis-dir FiberAxis --out-dir Profiles_Imputed --prior-stats-dir Atlas/normProfiles

The imputation comes after the QC, so that the QC sees only measured values.

What qc-profiles reads

--profiles-dir takes the tables of gather (<tract>/<tract>_<metric>.csv) or, without gathering them first, the profiles of a single run as EXTRACT_Profile writes them (<output>/<datasheet>/00_EXTRACT_Profile/<metric>/<tract>_<metric>.csv, in either orientation), so one run can be QCed on its own. --prior-stats-dir takes either layout as well, since the age bin statistics are written next to the tables they were computed from.

The profiles are compared with the prior at their own arc lengths: arc lengths that differ from the prior’s only by rounding (by less than 1% of its spacing) are the same position, and profiles sampled at other arc lengths get the prior interpolated linearly between its two neighbouring positions (a warning names those tables). Positions beyond the range of the prior are not compared. If no profile can be compared with the prior (no arc length in common, or no prior statistics for the tracts or age bins of the profiles), qc-profiles stops with an error instead of reporting no outliers.

The age of a profile

The age decides the age bin of a profile. It is the row of the scan in --age-csv, a participants / sessions table (--age-column and --age-units describe its age column, --age-subject-column and --age-session-column name its subject and session columns when they aren’t detected), else --age-regex on the column name of the profile, ses-(\d+)m by default. The same table is used by qc-registration --age-csv and by the ageCSV option of the DTI_Register module of dmriprep. The table is matched on the first two parts of the column name, the subject and the session (BIDS sub-<id>_ses-<id>_..., or IBIS <id>_V<visit>_..., the visit found in the table with or without its leading V). --age-fallback gives an age (in --age-units) to the profiles that neither gives one, e.g. a cohort of one age with a few scans missing from the table; the profiles that get it are named in the log. qc-registration and impute-profiles have the same option. Profiles with no age at all are named at the end of the run, as they take part in no age bin: they are not QC’d against the prior, and they stay in the summaries and the cleaned profiles. --exclude-no-age excludes them instead: they are left out of the summaries and the cleaned profiles and listed in excluded_cases.csv with the reason no age.

Ages are kept as fractional months (an age of 1.5 years in the table is 18 months). The age bins are written in whole months (--bins 0-3,4-9,10-60): a bin lo-hi holds the ages from lo up to, not including, hi + 1 months, so 3.5 months is in 0-3m. The tables of --stats-dir give the age of every scan in the column age_<units>, in --age-units (age_months by default; --age-units years for a table in years gives age_years). qc-registration writes the age of each session in registration_qc.csv the same way.

Batches: sites and scanners

A scanner or protocol offset (another site, another b-value) shifts FA and scales the diffusivities of every scan of a batch. Both QCs compare the scans with a normative reference, so a batch that differs from it looks like a group of outliers without any registration or tracking error. qc-registration --batch-correct and qc-profiles --envelope-batch-correct estimate that offset and remove it before the comparison: additive for FA-like metrics, multiplicative for the diffusivities (--batch-mult-metrics), one value per batch, metric and age bin, the median over the scans of the batch of each scan’s median deviation from the reference. One badly registered scan, or one scan with bad profiles, cannot hide itself that way.

Without batches the whole cohort is one batch, which is right when it was acquired the same way. A cohort of several sites or scanners needs them, or the correction (taken from the largest site) leaves the other sites off. The batch of a scan comes from a column of a table, --batch-column site: of --age-csv by default (with its subject and session columns), or of --batch-csv (--batch-subject-column and --batch-session-column name its subject and session columns if they aren’t detected). --batch-regex takes the batch from group 1 of a pattern instead, on the path of the FA map for qc-registration and on the column name of the profile for qc-profiles, for the scans the table doesn’t have. A batch with fewer than --batch-min-scans scans (5) in an age bin gets the shift of the whole cohort; scans without a batch form one of their own.

A session can have two scans from different scanners or protocols (two prefixes, ..._acq-dir79_dwi and ..._acq-dir42_dwi). The table then has a row for each, with the same subject and session and different batches, and the batch of each scan is the row whose values appear in the scan name (the file name of its FA map for qc-registration, the column name of the profile for qc-profiles), case-insensitive: only the columns where those rows differ are compared, typically a prefix (the prefix of registration_qc.csv), acquisition, protocol or scan column, or the batch itself. Whole words first (CMRR_APPA or APPA in 999434_VSA-CVD_CMRR_APPA_tensor; dir6 is not in acq-dir64); when no row matches so, any part of the name of at least 2 characters (b2000 in acq-b2000dir32). The log says which column told the scans apart, and how. A scan that matches no row, or rows of different batches, gets --batch-regex if given, else no batch, with a warning that names it.

qc-registration also flags each session against its own batch: with batches, the median of the combined score (and of the features of --combine mahalanobis) of each batch is removed before the outlier cut. Its batch_shifts.csv lists the shifts (batch, bin, metric, kind, shift, n_scans, and source: batch, or cohort for a batch too small for its own), and registration_qc.csv has the batch of every session and, with batches, the combined_score_batch_centered. The correction applies to the z-scores, MAE, SSIM, NCC and the CSF check; the angular metrics don’t depend on such offsets.

On 40 sessions of the IBIS reference dataset with the scans of a small site (6 sessions) given a scanner offset (FA -0.04, MD/RD/AD x1.15), qc-registration with FA, MD, RD and AD flagged 4 of the 5 well registered sessions of that site without batches, and none with --batch-column; the two misregistered sessions (shifted by 3 mm) were flagged either way, with a higher score with the batches.

Locations sampled outside the brain

A metric that cannot be 0 in tissue (FA, MD, RD, AD, NDI, ODI, …) is 0 at a position where the fibers of that scan left the brain mask. That is a property of the location, so it is read as missing on every metric of that tract and case, including those where 0 is a valid measurement (--zero-valid-metrics, the free water fraction by default); --keep-outside-brain keeps them, and with --clean-dir those cells are written empty in the cleaned tables. A profile with less than --min-valid-frac (0.75) of its positions left is flagged as an outlier, since too little of it is there to judge.

Diffusivities out of range

The profiles measure white and gray matter, not fluid, so no diffusivity (MD, RD, AD and the free water corrected FWMD, FWRD, FWAD) can exceed that of free water at body temperature: 3.0e-3 mm^2/s at 37 C (CSF; about 3.2e-3 at the 38-39 C of a macaque). Tissue is well below it (adult white matter MD about 0.7e-3, AD up to 1.8e-3; neonatal white matter MD up to about 1.8e-3, AD 2.2e-3), and lesions (edema, fluid) come close to it. A value well above it is a failed fit, typically of the free water model, and is read as missing, that value only, not the profile: --max-diffusivity (mm^2/s, default 3.6e-3, 20% above free water so that lesions and noise are kept; 0: no check). A table in 10^-3 mm^2/s (median above 0.05) is compared in those units. --min-diffusivity drops values below a lower limit the same way (default 0: off; a value of 0 is left to the check of the locations outside the brain).

The dropped values are listed in out_of_range.csv of --stats-dir, one row per profile (tract, metric, case, the number and share of the values dropped, the largest value of the profile and the arc length range of the dropped values; see below), so the scans whose fits failed can be found and refitted; with --clean-dir those cells are written empty, and impute-profiles fills them. In an infant cohort (HBCD, 2,293 scans) the free water fit had failed somewhere in most scans (FWAD in 2,227 of them, values up to 0.46 mm^2/s), about a third of those in the middle of a tract; the values of MD, RD and AD above the limit were mostly at the ends of the tracts, next to CSF. In another cohort (BCP, 423 scans), 16 scans had any.

What qc-profiles writes

The output folders are in the -o folder (--plots-dir, --stats-dir, --clean-dir and --clean-plots-dir are folders in it unless they are absolute paths), or in the working directory without -o:

  • next to the tables it read: <tract>/<tract>_<metric>_agebinstats.csv, the age-bin statistics (the --prior-stats-dir of later QC runs)

  • --stats-dir (Profiles_Stats), the tables of the QC: summary_mean.csv and summary_median.csv, the whole-tract mean and median of every metric per tract and dataset of the cleaned data (with --clean-dir), and summary_mean_all.csv / summary_median_all.csv before the profile outliers are removed; excluded_cases.csv (one row per registration, preprocessing, no age (--exclude-no-age), profile or most tracts missing (--max-missing-tracts) exclusion), out_of_range.csv (the diffusivities dropped, --max-diffusivity), profile_qc_mean.csv (every profile compared with the prior, with the outlier decision of its tract and scan) and profile_qc_mean_clean.csv (the comparison on the cleaned data); batch_shifts_mean.csv with --envelope-batch-correct. mean is --corr-reference.

  • --clean-dir: the cleaned tables, in the layout of --profiles-dir, with their age-bin statistics. A scan missing more than --max-missing-tracts (default 0.5; 1: no limit) of the tracts after the profile QC (absent from the tables of a tract, or a profile outlier there) is removed from every table: what is left of it is not representative, and imputing it (impute-profiles) would give little more than the norm

  • --plots-dir (StatPlots) and --clean-plots-dir (StatsPlots_Clean): Plots/, the plots of all the data and of the cleaned data

The tables of Profiles_Stats

All of them are CSV files in --stats-dir (Profiles_Stats). <ref> in a name is --corr-reference (mean by default, else median). A scan is identified by the column name of its profile, <subject>_<session>_<prefix> (dataset or subject_session below, e.g. sub-1007_ses-012m_dwi). Ages are floats in --age-units, in a column named after them (age_months by default, age_years with --age-units years); a scan without an age has it empty. bin is the age bin of the scan (--bins, e.g. 10-60m).

File

Written

One row per

summary_mean_all.csv, summary_median_all.csv

always

tract and scan, before the profile outliers are removed

summary_mean.csv, summary_median.csv

with --clean-dir

tract and scan of the cleaned profiles

profile_qc_<ref>.csv

with --prior-stats-dir

tract, metric and scan compared with the prior, with the outlier decision

profile_qc_<ref>_clean.csv

with --prior-stats-dir and --clean-dir

tract, metric and scan of the cleaned profiles compared with the prior

batch_shifts_<ref>.csv

with --envelope-batch-correct

batch, metric and age bin

excluded_cases.csv

when a scan is excluded

exclusion

out_of_range.csv

when a diffusivity is out of range (--max-diffusivity)

tract, metric and scan

summary_mean_all.csv, summary_median_all.csv, summary_mean.csv, summary_median.csv – the whole-tract value of every metric: the mean (or median) of the profile along the arc length, ignoring missing positions and those sampled outside the brain. The _all tables hold every scan except those removed up front (--registration-qc, --prep-qc, --exclude-no-age); the others hold the cleaned profiles, without the profile outliers either.

  • tract, dataset; sub, ses, prefix: the parts of dataset (without sub- / ses-)

  • age_<units>

  • one column per metric (fa, md, rd, ad, …)

profile_qc_<ref>.csv – the comparison of each profile with the prior statistics of its tract, metric and age bin (--prior-stats-dir), at the arc lengths of the profile (see above). Profiles without an age, or of a tract, metric or age bin without prior statistics, have no row.

  • tract, metric, subject_session, age_<units>, bin

  • r: Pearson correlation of the profile with the prior mean (--corr-reference median: the prior median) along the arc length. It measures the shape, so a shift or a scaling of the values does not change it. Empty when there is nothing to correlate (fewer than 3 positions in common with the prior)

  • frac_inside: n_inside / n_valid, the fraction of the positions inside the envelope of the prior, mean ± k·std (--value-nsd, 3) or the --value-pct-lo .. --value-pct-hi percentile band (--value-envelope percentile); with --envelope-batch-correct the profile is corrected by the batch shift first. Empty when there is no envelope (an age bin of the prior with a single subject has no std)

  • n_valid: positions where the profile and the envelope both have a value; n_inside: those inside the envelope

  • n_present: positions where the profile has a value (not missing, not outside the brain); n_positions: positions of the arc length grid

The outlier decision is made once per tract and scan from all its metrics, and applies to all of them (a flagged scan is removed from every metric of that tract in --clean-dir), so the following columns have the same value on the rows of the metrics of a tract and scan (the rows of one metric, e.g. metric == fa, give one row per tract and scan):

  • joint_frac_inside: the fraction of the positions inside the envelope over the metrics of the tract, except --outlier-exclude-metrics (FWF): the sum of their n_inside over the sum of their n_valid

  • joint_frac_valid: how much of the profile is there over those metrics, the sum of n_present over the sum of n_positions

  • is_value_outlier: joint_frac_inside below --value-min-inside (0.9), or joint_frac_valid below --min-valid-frac (0.75: too little of the profile is left to judge it)

  • shape_r: r of the --shape-metric (fa)

  • is_shape_outlier: shape_r below --corr-min (0.5), or with --shape-outlier-method iqr below Q1 - k·IQR of the shape_r of the tract and age bin (--corr-iqr-k, 1.5)

  • is_outlier: is_value_outlier or is_shape_outlier

Up to version 0.8.14 the decision was also written to outliers_<ref>.csv, one row per tract and scan; a run removes that table from --stats-dir when it finds one.

profile_qc_<ref>_clean.csv – the columns of profile_qc_<ref>.csv up to n_positions, for the cleaned profiles: how the scans that are kept compare with the prior. No decision is made on them.

batch_shifts_<ref>.csv – the shift between the cohort and the prior used by --envelope-batch-correct, per batch (Batches: sites and scanners; one, named '', without --batch-column / --batch-regex), metric and age bin. It is estimated from all the tracts: for each profile, the median along the arc length of its difference to the prior median (value - prior), or of its ratio for the metrics of --batch-mult-metrics (md,rd,ad: value / prior); the shift is the median of those over the profiles. A profile is corrected by subtracting the shift (or dividing by it) before the envelope check; the shape check is not affected. The table only has the header line when no shift can be estimated (the run then warns).

  • batch, metric, bin

  • kind: add or mul

  • shift: the offset (add) or the ratio (mul)

  • n_profiles, n_scans: the number of profiles and of scans of the batch it was estimated from

  • source: batch, or cohort when the batch has fewer than --batch-min-scans scans in that age bin and gets the shift of the whole cohort

excluded_cases.csv – one row per exclusion, written when a scan is excluded.

  • sub, ses, prefix: the scan (without sub- / ses-); prefix is empty for a registration failure of a whole session

  • age_<units>

  • tract: the tract of a profile outlier; empty for the other reasons, which apply to every tract

  • reason: registration (flagged in --registration-qc), preprocessing (--prep-qc), no age (--exclude-no-age), profile (is_outlier in profile_qc_<ref>.csv) or <n> of <m> tracts missing (--max-missing-tracts)

out_of_range.csv – one row per profile with diffusivities out of range (--max-diffusivity, --min-diffusivity), which are read as missing; the rest of the profile is kept.

  • tract, metric, case (the column name of the scan), subject_session

  • n_values: the values of the profile; n_out_of_range: those dropped, share the ratio

  • max_value, min_value: the largest and the smallest positive value of the profile, in mm^2/s

  • arc_from, arc_to: the arc length range of the values dropped (whether at the ends of the tract or inside)

Imputing the profiles

impute-profiles fills the missing values of profile tables, typically the cleaned profiles of qc-profiles (Profiles_Clean). It reads every layout qc-profiles reads and writes the same layout to --out-dir (Profiles_Imputed); the observed cells are copied verbatim, so the tables can be QCed and analysed like the others. Two kinds of values are missing, and both are imputed the same way:

  • blank cells, e.g. the locations sampled outside the brain, which qc-profiles writes empty

  • whole profiles: a scan that is in the tables of other tracts but not in the table of a tract, e.g. a profile qc-profiles excluded as an outlier. The imputed profile is added to that table.

A scan that is in no table (excluded for its registration, its preprocessing or a missing age) has nothing to impute from and stays out.

Each scan is imputed from its own observed values, either the values themselves or, with the norm of a normative cohort (--prior-stats-dir), their deviations from it. Every profile location (tract, arc length) has a 3-D position in atlas space, the point of the tract axis at that arc length (--axis-dir, from compute-axis; beyond the ends of an axis, along its first or last segment). The tracts are dense in the brain, so a location that is missing has observed neighbours in other tracts of the same scan.

With the norm (--prior-stats-dir, the age bin statistics *_agebinstats.csv that qc-profiles writes for a normative cohort, either layout), the method imputes the scan’s deviation from the mean of its age bin, (value - mean) / SD at each location, and turns it back into a value with the mean and SD of the missing location (--relative-to-prior, the default with --prior-stats-dir; --no-relative-to-prior imputes the values). A scan that is above the norm in a tract tends to be above it in the neighbouring tracts as well, and the norm carries what the neighbours can’t: the level of each tract at the scan’s age. The age of a scan comes from --age-csv (--age-column, --age-subject-column, --age-session-column, --age-units, as for qc-profiles) or its name (--age-regex, default ses-<months>m), else --age-fallback; a scan without an age, or outside the age bins, is not imputed with the norm.

The methods (--method):

arc-linear (default without --prior-stats-dir)

Linear along the arc length of the same profile, between the observed values at both ends of a gap; gaps longer than --max-gap mm (default 15, the longest gaps validated) are left. The missing start or end of a profile (--arc-ends): left (none, default on the values), the nearest observed value repeated (constant, default on the deviations), or the line through the 3 nearest observed values extended (linear), up to --max-gap mm. It can’t fill a whole profile and needs no axes.

linear

Linear in 3-D: barycentric interpolation in the tetrahedra (Delaunay) of the observed positions of the same metric, in all tracts. A location outside them is left (--fallback knn fills it).

knn

The mean of the --k nearest observed positions in 3-D (default 20 on the deviations, 1 on the values), weighted by the inverse of their distance (--knn-weights uniform: equally).

siren

A sine network (SIREN) per scan, trained on the scan’s observed values of all metrics jointly, each standardized on its own; it predicts the missing ones. --siren-inputs sets what it sees of a location: the 3-D position (xyz), with the arc length (xyz+arc), or with the tract (xyz+tract; a one-hot code). Uses a GPU when there is one (--device; a scan takes seconds on a GPU, longer on a CPU); --epochs, --omega0, --hidden-layers, --hidden-width, --lr, --seed. On the deviations the default is xyz, --omega0 10, --epochs 500 (default with --prior-stats-dir), on the values xyz+tract, --omega0 30, --epochs 1000.

prior-mean

The mean of the scan’s age bin (needs --prior-stats-dir); it also fills a metric the scan doesn’t have at all.

population

A probabilistic PCA (--components, default 80; --noise: one noise variance for all values, isotropic, default, one per metric or one per value) of the deviations of a normative cohort from the norm of their age bins, over all tracts and metrics jointly. The observed deviations of a scan give the most likely values of its missing ones and their SD, so it imputes a whole profile, a region, and also a metric the scan doesn’t have at all (e.g. no free water fit) from its other metrics. Its SDs are calibrated per metric (--sd-calibration-folds, default 5: the model is fitted again in 5 folds of the scans, by subject, each predicting hidden whole profiles of the others, and the SDs are scaled so they match those errors). The model is fitted (EM, --max-iter; the cells observed in at least --min-scans scans) on the profiles being imputed, with --prior-stats-dir or, without it, the norm of their own age bins (--bins): with 80 components about 3 minutes, most of it the calibration of the SDs. --fit-model model.npz saves it, with the norm it was fitted with, and --model model.npz imputes another cohort on the same tracts with it (the model replaces --prior-stats-dir). A cell outside the model (observed in fewer than --min-scans scans of the fit) is imputed on the age bin norm instead, and the age bin mean fills what is left of it. A cohort too small for a model of its own (no cell observed in --min-scans scans, e.g. a few clinical scans) is imputed on the age bin norm (--norm age-bin, --fallback prior-mean) with a warning; impute it with a --model fitted on a normative cohort instead.

graph-unet

A graph convolutional U-Net of the deviations (after CONFETTI), over a multi-resolution graph of the profile locations: level L keeps every 2^L-th location of each tract (--graph-levels, default 4), and each location is linked to its neighbours along the tract and to the closest location of each other tract within 1.5 times (--graph-threshold) the median distance to the nearest axis of another tract (--graph-fibers-dir: to the nearest atlas fiber at the same arc length, as CONFETTI; a larger threshold that imputed worse). The network is trained on the profiles (a normative cohort, with the norm of --prior-stats-dir or of their age bins) to predict values hidden as in the validation (whole profiles, gaps, ends, regions, a whole measure) from the observed ones, with an SD, and corrects the prediction of a population model (--graph-hybrid, default 80 components, fitted without each training scan’s subject for its input; 0: the deviations only). --graph-hidden (128), --graph-convs (1), --graph-epochs (60, the epoch with the smallest error on held-out subjects is kept), --graph-lr. Training takes about 10 minutes on a GPU (5 population fits for the inputs and the network); --fit-graph-model model.pt saves the network and --graph-model model.pt imputes another cohort with the same tracts, arc lengths and metrics with it (the norm is that of the run). Its SDs are calibrated per metric on the held-out subjects and written to sd/. Like population it imputes a whole profile and a metric the scan lacks entirely. As --fallback graph-unet with the default (SIREN on the residuals from the population prediction within 4 mm), it fills the rest instead of the population model: in the validation on FA, MD, RD, AD, NDI, ODI and FWF, 0.7% less error overall, a quarter less when the four tensor metrics are missing and 13% less when the NODDI metrics are. The transformer below was better in every pattern of missing values.

transformer

A transformer of the deviations, trained like graph-unet (the same hidden values, a population model prediction it corrects, --transformer-hybrid default 80 components; 0: the deviations only). Each token is a patch of --transformer-patch (8) consecutive locations of a tract, with their positions, observed deviations and the population prediction; --transformer-layers (6) layers of attention over all the tokens of a scan (--transformer-width 192 features, a head per 32) relate every tract to every other, and a head per location gives the deviation and its SD. --transformer-epochs (400, 200 with a reference cohort; the epoch with the smallest error on held-out subjects is kept), --transformer-lr (1e-3). Training takes about 20 minutes on a GPU for 400 scans (hours on a CPU); --fit-transformer-model model.pt saves it and --transformer-model model.pt imputes another cohort with the same tracts, arc lengths and metrics with it. Alone it imputed 3% better overall than graph-unet (200 epochs; 400 epochs were 1% better again), and a whole measure the scan lacks 10-16% better. It is used by default through --ensemble (below), and can also be the method or --fallback. Extra inputs (the distance to the nearest observed value, the age, the acquisition) and averaging several networks did not impute better in the validation.

--transformer-reference-dir (opt-in) adds the profiles of a reference cohort, e.g. a large normative study on the same tracts and arc lengths, to the training of the transformer only. The reference is corrected to the profiles by the batch correction at the same age (--batch-*; its ages from --transformer-reference-age-csv), the transformer is trained on both with the norm of their pooled age bins, and the norm, the population model and SIREN stay those of the profiles. In the validation on BCP with HBCD as the reference (2,293 scans, 200 epochs, about an hour on a GPU), the transformer alone was 8% better and the blend 5% better (0.538 of the age bin mean overall, against 0.567) than with the transformer trained on BCP alone. Pooling the population model with the reference instead made the imputation worse.

--ensemble (default transformer with a prior and --norm population, else none) blends every imputed value with the prediction of that model: the value becomes (1 - w) x value + w x prediction. --ensemble-weights sets w:

  • table (default): a weight per metric and band of the distance to the nearest observed value of the metric, for the cells the method filled (0-0.5, 0.5-1, 1-2, 2-3, 3-4 mm), those of --fallback (4-6, 6-10, 10-20, beyond 20 mm) and a metric the scan has no observed value of. The built-in tables were fitted on the validation, one for a transformer trained on the profiles and one for a transformer trained with --transformer-reference-dir; the weight of the transformer grows from about 0.2-0.3 next to an observed value to 0.6-0.7 beyond 4 mm and 0.6-0.98 for a missing measure. A metric not in the table (the free water tensor) gets the mean of the others.

  • fit: the table fitted in the run itself, on the profiles of the transformer’s held-out subjects (about a tenth; at least 10 scans) with values hidden as in the validation, the population model refitted without them (a few minutes more); a band with fewer than 200 hidden cells keeps the built-in weight. Written to ensemble_weights.csv and saved with --fit-transformer-model, so a saved --transformer-model blends with its own weights.

  • NEAR,BEYOND: fixed weights on the cells the method filled within --max-distance and on the others (0.25,0.75 was the first default), or a CSV file in the format of ensemble_weights.csv.

The SD of a blended value combines the two SDs with the same weights. The blend needs --axis-dir (without it, the default is left out with a warning) and the training above, or a saved --transformer-model; --ensemble graph-unet blends with the graph U-Net instead (with --fallback graph-unet or --graph-model).

With a prior, --norm sets what the deviations of --relative-to-prior are from:

  • population (default): the scan’s own prediction by the population model and its SD. The method (e.g. siren) imputes what the model misses, the residuals, from the 3-D neighbours within --max-distance, and --fallback population fills the rest with the model’s prediction.

  • age-bin: the mean and SD of the scan’s age bin (the behaviour of 0.8.20).

--fallback runs a second method on the cells the first one left (e.g. --method arc-linear --fallback siren: gaps along the profile, the rest from the network).

The norm over age (--age-norm) is by default that of the age bins (bins: the mean and SD of each bin of --prior-stats-dir, or of --bins of the profiles themselves). Fitted on the profiles of a normative cohort (or kept in a --model), it can instead be continuous in the age, so a scan at the edge of a bin is not compared with the mean of the whole bin: the mean and SD of every location are smooth functions of log(age in months + --age-offset, default 1), a natural cubic spline (spline; --spline-df, default 3, for the mean and --spline-sd-df, default 2, for the variance) or a local-linear kernel regression (kernel; --kernel-bandwidth in log months, default cv: chosen by leave-one-out). Their SDs are calibrated per metric and age like those of the population model (--sd-calibration-folds). In the validation a continuous norm alone was 7% better than the age bin mean (0.93 of its error, paired over 162 scans, p < 1e-10), but with --norm population and SIREN it gave nothing more (1.005 of the error with age bins, p = 0.44), so bins stays the default.

The defaults are the settings with the smallest error over all kinds of missing values (gaps, ends, whole profiles, regions) in the validation on a normative infant cohort (Validation of impute-profiles):

  • with --prior-stats-dir (or --model): siren on the deviations from the population prediction (--norm population; xyz, --omega0 10, --epochs 500) within --max-distance 4 mm of an observed value and --fallback population (80 components) beyond, blended with the transformer (--ensemble, 400 epochs, the weights of the built-in table). In the validation on FA, MD, RD, AD, NDI, ODI and FWF (3 x 54 scans), the blend had about 7.5% less error than the same settings without it: gaps 0.42 of the age bin mean instead of 0.44, missing ends 0.50 instead of 0.55, whole profiles 0.64 instead of 0.70, regions 0.71 instead of 0.77, the four tensor metrics missing 0.42 instead of 0.70 and the NODDI metrics 0.62 instead of 0.80 (the first release of the blend, 200 epochs and fixed weights 0.25 / 0.75: 5.3% less error). With HBCD as --transformer-reference-dir, 12% less error (0.54 of the age bin mean overall, against 0.61). --ensemble none (the default of 0.9.5) needs no training. Without the blend, the error was 37% of that of the age bin mean for gaps inside profiles, 51% for missing ends, 64% for whole profiles, 68% for a region of rejected tracts and 59% for a whole measure the scan lacks (the free water tensor or NODDI metrics), 11% lower overall than siren on the deviations from the age bin norm (--norm age-bin, the default of 0.8.20), which can’t impute a missing measure. --method knn (k = 20) needs no GPU for the residuals and was about 7% worse overall.

  • without: arc-linear on the values (--arc-ends none, --fallback none), which fills only the gaps inside profiles. Without the norm, every method imputed missing ends no better than the age bin mean, and whole profiles and regions 2 to 2.5 times as far off; other methods and --fallback can still be chosen, but those values are estimates of limited use.

Limits:

  • --max-distance (mm; 0: none): the 3-D methods fill only cells within that distance of an observed position of the same metric, the others are left to --fallback. Default 4 on the deviations from the population prediction: farther, the model alone was better than its residuals imputed from the neighbours; 20 on the deviations from the age bin norm: up to there, the neighbours still imputed a region better than the age bin mean (0.84-0.90 of its error at 10-25 mm); 10 on the values, whose error grows fast with the distance

  • --min-observed (default 0.5): a metric of a scan with a smaller share of observed values is not imputed (except by prior-mean and population, which need no observed value of the metric)

  • --max-missing-tracts (default 0.5; 1: none): a scan missing a larger share of its tracts (no observed value of any metric, e.g. excluded by qc-profiles) is not imputed at all, by any method: its imputed values would be little more than the norm. In the normative cohort of the validation, 2 of 423 scans (38 and 63 of 69 tracts missing); with 0.25, 7 scans

Next to the tables, --report-dir (default <out-dir>_report) holds:

  • masks/: the tables again, with 1 for an imputed cell, 0 for an observed one and blank for one still missing, so the analyses can tell measured values from imputed ones

  • imputation_summary.csv: one row per scan, tract and metric with missing values: n_positions, n_observed, n_missing, shape (whole profile, or end gap for a missing start or end and gap for missing values inside the profile), n_imputed, n_left, methods, max_distance_mm (the largest distance from an imputed cell to an observed position), mean_sd (the mean SD of the values imputed with the population model) and left_reason

  • sd/: with the population model (or graph-unet, transformer), the tables again with the SD of each value imputed with it (blank elsewhere). For a value imputed from the residuals (--norm population), the SD is that of the model alone, an upper bound where the neighbours were close

  • imputation_settings.json: the options of the run

Imputed values are estimates, not measurements: report the share of imputed values, and consider leaving them out of analyses that handle missing values themselves (e.g. mixed models). With the norm, the imputed values of a scan are drawn towards its age bin mean where its own neighbours say little, so a group analysis of normative and other scans should not rely on imputed values for group differences.

Pooling several cohorts

Several --profiles-dir (e.g. BCP/Profiles_Clean HBCD/Profiles_Clean) are imputed together, one batch each (--batch-names, default the folder names or those of the first parents that tell them apart); a scan may be in one batch only, and the output has a folder per batch (<out-dir>/<batch>/...). The ages are needed (--age-csv takes several tables, e.g. one per batch). The acquisitions differ, so the batches are put into the units of a reference batch first (--batch-reference, default the first folder), at every location and metric, and the imputed values (and SDs) are turned back into the units of their own batch (--batch-correction shift-scale, default; none: pooled as they are):

  • the shift, at the same age: all batches follow one age curve (a natural cubic spline of log(age + --age-offset), --batch-df degrees of freedom, default 6) plus a shift per batch, fitted jointly, so batches with different age ranges are compared at the same ages. --batch-shift linear: the shift is linear in log age over the ages all batches have, constant beyond (default constant)

  • the scale: the ratio of the SDs of the residuals around that curve, over the ages all batches have, after the residuals are scaled by an age curve of the variance (--batch-sd-df, default 2), kept within 1/L and L (--batch-scale-limit, default 3,FWAD=10,FWMD=10)

  • --batch-robust yes: the diffusivities on the log scale, and Huber then bisquare weights of outlying residuals in the fit of the shift and in the SDs of the scale (not for FWF, which has many values of 0); default no

A location and metric with fewer than 10 values of a batch is left as it is. <report-dir>/batch_correction.csv gives, per batch and metric, the median shift (also in SDs) and scale over the locations, and the share of the locations whose scale is at the limit. The norm (and a population model) is then that of the corrected cohort; --prior-stats-dir (statistics in the units of one batch) can’t be used with several batches.

In the validation on BCP (423 scans) pooled with HBCD (2,293 scans, mostly 0-9 months; 3 seeds, the BCP scans in BCP units), pooling did not help the BCP scans: with the tensor and NODDI measures of HBCD only (its free water measures left out), the error was the same as with BCP alone (1.010 of it, 95% CI 0.99-1.03, p = 0.37), with all measures 5% larger (p = 2e-6), through the free water diffusivities, whose HBCD fits differ from BCP’s by more than a shift and a scale. The robust correction was not better than the plain one once the failed fits were dropped (qc-profiles --max-diffusivity). Pooling is for imputing the scans of a cohort too small for its own norm and model; a cohort with enough scans of every age is best imputed on its own. Run qc-profiles with --max-diffusivity on every cohort first: failed free water fits (values up to 0.46 mm^2/s) otherwise distort the correction of the whole location.

Validation

--validate compares the methods and their settings on values that were measured: in a sample of scans (--validate-scans, default 30, chosen with --validate-seed; --validate-scans-per-bin N: N of each age bin, and of each batch, so every age is represented, but at most --validate-max-share of the scans of a bin, default 0.5, so the norm and the models of a small bin keep enough scans) it hides whole profiles of a share of the tracts (--validate-whole-fraction, default 0.1, all metrics of the tract), one gap inside the profile in a share of the other tracts (--validate-gap-fraction, default 0.2; --validate-gap-mm, default 3 to 15 mm long) and the start or end of the profile in another share (pattern end gap; --validate-end-gap-fraction, default 0.2; --validate-end-gap-mm, default 1 to 8 mm, like the missing ends of real profiles), imputes them with every setting and compares with the hidden values. Those tracts are chosen at random, so their neighbours are usually observed. A regional artifact (signal dropout, susceptibility, motion) instead makes qc-profiles reject all the tracts that run through the same region, and takes away the neighbours the 3-D methods rely on. A second pass per scan hides such a region (pattern region): every tract with a position inside a sphere around a random observed position loses its whole profile (--validate-region-mm, radius 10 to 25 mm by default; a sphere reaching more than half of the scan’s tracts is drawn again; --validate-region-count, default 1, 0: no region pass). A third pass hides a whole measure (pattern whole measure): all values of one family of metrics the scan has, as for a scan without that model fit (--validate-measure-families, default dti,fw,noddi: dti the tensor metrics FA, MD, RD, AD; fw the free water tensor metrics FW-FA, FW-MD, FW-RD, FW-AD; noddi NDI, ODI and FWF, the isotropic free water fraction of the NODDI fit; none: no such pass). A family is hidden only while the scan keeps observed values of another one to impute it from. Only prior-mean, population and graph-unet can impute it. The hidden values of the first two passes don’t depend on the third, so they are the same as in a validation without it. --validate-rounds (default 1) repeats the passes on every scan with other tracts, gaps and regions, for more hidden values per location. Each setting is compared on the values and on the deviations from the norm (--validate-relative, default both), and prior-mean imputes the age bin mean. The norm comes from the cohort itself (--validate-prior cohort, default, for a normative cohort; age bins --bins, default 0-3,4-9,10-60 months) without every scan of the validated scan’s subject (--validate-leave-out subject, default: its other sessions are not independent of it; scan: the scan only), or from --prior-stats-dir (--validate-prior files, the statistics of another cohort: those of the cohort validated would include the hidden values). Only scans whose metrics are at least --min-observed observed, and that miss at most --max-missing-tracts of their tracts, are used. Nothing is imputed into --out-dir; the results are in <report-dir>/validation:

  • validation_summary.csv: per setting and pattern (gap, end gap, whole profile, region, whole measure) the share of hidden values filled (coverage) and the error, as an RMSE normalized by the between-scan SD at each location (nrmse; 1 is as far off as a scan typically is from the cohort mean there), its SD over the SIREN seeds, and nrmse_common, the error on the cells every setting filled (of the settings that fill any of the pattern, so without arc-linear for whole profiles and regions). The errors are averaged over the metrics, so each counts the same. The between-scan SD of a location is at least a quarter of the metric’s median SD over all locations, so a location where a metric hardly varies (e.g. the free water fraction in deep white matter) doesn’t dominate. The row cohort mean (reference) is not a method: it imputes the mean of the other scans at each location, so it shows what an error of a method means (--no-validate-reference: left out). Over a sample of scans its error is near 1 but not exactly: the scans sampled may lie closer to the cohort mean, or farther, than the cohort as a whole. vs_reference is therefore the error of a setting relative to that of the reference on the same cells: below 1, the setting does better than the cohort mean, whatever the sample. It is in every table but the one per location. When the scans have ages, vs_age_mean is the same relative to the mean of the scan’s age bin (prior-mean), the better reference across an age range with large changes such as infancy, and vs_age_mean_completed relative to it on every hidden value, with the values a setting leaves (e.g. farther than --max-distance) counted with the age bin mean; it compares settings that fill different shares of the values, as an imputation with --fallback prior-mean would. rmse_completed is that error in the units of the metric

  • validation_by_metric.csv, validation_by_tract.csv: the same per metric and per tract and metric, also in the units of the metric (rmse); the second one has the distance from the tract’s axis to the nearest other tract

  • validation_by_age_bin.csv: the same per metric and age bin of the scans validated (per batch and age bin with several --profiles-dir)

  • validation_by_age.csv: the error relative to the age bin mean per age of the scans validated

  • validation_by_scan.csv: per scan validated, setting, pattern and metric, the number of hidden values n scored against the age bin mean, the squared errors of the setting and of the age bin mean in the units of the metric (sse, sse_age_mean) and normalized (nsse, nsse_age_mean), and vs_age_mean; group is the batch and age bin. Two settings, or two runs with the same --validate-seed, can be compared scan by scan (paired), which separates small differences from the sampling of the scans

  • validation_by_location.csv: the error at every profile location (tract, arc length and its 3-D position x, y, z) of the best setting of each method for each pattern (--validate-location-settings all: of every setting), per metric and as the mean over the metrics (metric all), with the number of hidden values there (n_hidden); it shows whether some locations are harder to impute than others

  • error_maps/<setting>.vtk: the same on the tract axes, one polyline per tract at the profile locations, with the point data gap_n, gap_nrmse, gap_nrmse_<metric> and the same for end, whole and region (NaN where nothing was hidden); open it with the atlas tracts (e.g. in 3D Slicer or ParaView) and color by an error

  • error_maps/<setting>.png: the error per location (mean over the metrics) in three projections (axial, coronal, sagittal), per pattern; the largest errors are drawn on top, and locations with fewer than --validate-min-n (default 3) hidden values are gray

  • validation_by_distance.csv: the error by the distance from a hidden value to the nearest position still observed in that scan (bins 0-2, 2-4, 4-6, 6-10, 10-15, 15-20, 20-25, over 25 mm), per setting, pattern and metric and their mean (all); it shows how fast a method degrades as the observed neighbours get farther away

  • validation_calibration.csv: for population (and the combinations with it) and prior-mean (the SD of the age bin), the errors relative to the predicted SDs per setting, pattern and metric and their mean (all): rms_z, the RMS of error / SD (1 if the SDs are right, above 1 if they are too small) and within_1.96sd, the share of the errors within 1.96 SD (0.95 if right)

  • axis_proximity.csv: per tract, the distance from its positions to those of the nearest other tract (where the 3-D position alone can’t tell the tracts apart)

  • validation_siren_epochs.png: the error of every SIREN setting against the epochs, with the other methods as lines

  • validation_settings.json: the scans used and the settings

The settings compared: --validate-methods (default all), --validate-k (knn, default 1,3,5,10,20,50) with --validate-knn-weights (default both, distance and uniform), --validate-arc-ends (arc-linear, default all three) and for siren the grid of --validate-siren-inputs (default all three), --validate-omega0 (default 5,10,20,30) and --validate-epochs (default 100,200,500,1000; one training per setting, read off at each value), each trained --validate-seeds times (default 3). population is compared for each of --validate-components (default 5,10,20,40,80) and --validate-noise (default all three), alone and with the residuals from its prediction imputed by --validate-population-local (default knn,siren: knn with each --validate-k, siren with each input and omega_0 of the grid at its most epochs) within --max-distance, as --norm population does. Its model must not have seen the scans validated: the scans are split by subject into --validate-folds folds (default 5), and the model of a fold is fitted on the other subjects of the cohort, with their own norm (--validate-prior cohort). graph-unet (in --validate-methods) is fitted the same way, for each of --validate-graph-levels (4), --validate-graph-hidden (128), --validate-graph-convs (1) and --validate-graph-hybrid (80; 0: on the deviations only), alone and with the local residual methods; the setting <population> + <local>, <graph-unet> beyond is the default with --fallback graph-unet. transformer (in --validate-methods) is compared the same way with the settings of --validate-transformer-patch (8), --validate-transformer-width (128), --validate-transformer-layers (4) and --validate-transformer-hybrid (80). Each model of the deviations is also blended with the first population-and-local setting: ensemble settings graph near a beyond b (weight a within --max-distance, b beyond; the default is near 0.25 beyond 0.75 with the transformer) and precision (each value weighted by the inverse of its SD squared). --validate-age-norms (default bins) compares the settings on a norm with each age norm, spline for each of --validate-spline-df x --validate-spline-sd-df and kernel for each --validate-kernel-bandwidth; a continuous norm is fitted per fold without the fold’s subjects, and the errors stay relative to the age bin mean. With several --profiles-dir the batch correction is fitted without the subjects validated. The scans sampled depend on --validate-seed: with 14 to 20 scans per age bin, the result of a setting changed by up to 0.04 between seeds in an age bin (0.01 overall), more than many of the differences between settings, so compare settings over several seeds and on the same scans (validation_by_scan.csv). arc-linear fills every hidden gap and end there, whatever its length. The other limits (--max-distance, --min-observed) apply as in an imputation. With the default grid a scan takes about a minute on a GPU.

Further validation options, for an evaluation beyond the patterns of hidden values above:

  • --validate-real-masks yes: a fourth pass per scan hides exactly the real missing cells of another scan of the cohort (of the same age bin, another subject), as the profile QC left them (pattern real mask), so the error is that of the missingness the imputation actually meets

  • --validate-exclude-subjects FILE|LIST: subjects whose scans are not validated (they still train the models), e.g. those validated before, for an untouched test of settings chosen on earlier validations

  • --validate-batches, --validate-norm-batches, --validate-model-batches: with several --profiles-dir, validate only the scans of these batches, fit the age bin norm only on these batches, and fit the models of the deviations only on these batches, to tell what pooling a second cohort does to the norm and to the models

  • --validate-dump-dir DIR: the hidden cells of every scan with the default’s and each model’s prediction and SD, the distance and the truth (npz), to fit blend weights or other analyses offline

See the README for the remaining options.

Development of a new module

Adding a module

Once initialized, users can add their custom module from scratch or existing system/user modules by following command:

$ dmrifiberprofile add-module <module-name> [--base-module <base-module-name>] [--edit]

Following command will generate initial skeletal files of module:

$ dmrifiberprofile add-module HELLO_World

Then you can test if the module can be loaded properly with:

$ dmrifiberprofile update

You can use your module right in protocol file.

if -b , –base-module is specified, new model will copy existing code and data from the base module. e.g.:

$ dmrifiberprofile add-module MYFIRST_Module -b EXTRACT_Profile

MYFIRST_Module will have same codes and data (module definition yaml file) from EXTRACT_Profile module with new classname and filenames.

Developer

Once module is developed and tested in the user module directory, one can just move that directory in dtiplayground/dmri/fiberprofile/modules and commit. Make sure the custom module does not exist in both the user and system module directories.

Removing user module

User module can be removed by:

$ dmrifiberprofile remove-module <module-name>

e.g.:

$ dmrifiberprofile remove-module MYFIRST_Module

[NOTE] System module cannot be removed by this command. Only user module can be removed.

Modules in other directory

You can just copy module directory to $HOME/.niral-dti/modules/dmrifiberprofile and check with $ dmrifiberprofile update command. Same applies for removal of user modules.